after_merge
stringlengths 28
79.6k
| before_merge
stringlengths 20
79.6k
| url
stringlengths 38
71
| full_traceback
stringlengths 43
922k
| traceback_type
stringclasses 555
values |
|---|---|---|---|---|
def create(self):
if self.can_be_inline:
self.create_inline()
else:
self.create_via_sub_process()
# TODO: cleanup activation scripts
for lib in self.libs:
ensure_dir(lib)
super(Venv, self).create()
|
def create(self):
if self.can_be_inline:
self.create_inline()
else:
self.create_via_sub_process()
# TODO: cleanup activation scripts
for lib in self.libs:
ensure_dir(lib)
|
https://github.com/pypa/virtualenv/issues/1635
|
~ % source venv/bin/activate
source: no such file or directory: venv/bin/activate
~ % source venv/usr/local/opt/python@3.6.8/bin/activate
(venv) ~ % pip list
Traceback (most recent call last):
File "/Users/csalch/venv/usr/local/opt/python@3.6.8/bin/pip", line 5, in <module>
from pip._internal.cli.main import main
ModuleNotFoundError: No module named 'pip._internal.cli.main'
(venv) ~ % which python
/Users/csalch/venv/usr/local/opt/python@3.6.8/bin/python
(venv) ~ % python -m pip list
Package Version
------------------- -------
anisble 0.1
ansible 2.9.4
appdirs 1.4.3
cffi 1.13.2
cryptography 2.8
distlib 0.3.0
filelock 3.0.12
importlib-metadata 1.5.0
importlib-resources 1.0.2
Jinja2 2.10.3
MarkupSafe 1.1.1
pip 19.3.1
pycparser 2.19
PyYAML 5.3
ruamel.yaml 0.16.5
ruamel.yaml.clib 0.2.0
setuptools 42.0.2
six 1.13.0
virtualenv 20.0.4
wheel 0.33.6
zipp 2.2.0
(venv) ~ % cat $(which pip)
#!/Users/csalch/venv/usr/local/opt/python@3.6.8/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())
(venv) ~ %
|
ModuleNotFoundError
|
def copyfile(src, dest, symlink=True):
if symlink and hasattr(os, "symlink") and not IS_WIN:
return symlink_file_or_folder(src, dest)
if not os.path.exists(src):
# Some bad symlink in the src
logger.warn("Cannot find file %s (bad symlink)", src)
return
if os.path.exists(dest):
logger.debug("File %s already exists", dest)
return
if not os.path.exists(os.path.dirname(dest)):
logger.info("Creating parent directories for %s", os.path.dirname(dest))
os.makedirs(os.path.dirname(dest))
logger.info("Copying to %s", dest)
copy_file_or_folder(src, dest, symlink)
|
def copyfile(src, dest, symlink=True):
if not os.path.exists(src):
# Some bad symlink in the src
logger.warn("Cannot find file %s (bad symlink)", src)
return
if os.path.exists(dest):
logger.debug("File %s already exists", dest)
return
if not os.path.exists(os.path.dirname(dest)):
logger.info("Creating parent directories for %s", os.path.dirname(dest))
os.makedirs(os.path.dirname(dest))
if symlink and hasattr(os, "symlink") and not IS_WIN:
logger.info("Symlinking %s", dest)
try:
os.symlink(os.path.realpath(src), dest)
except (OSError, NotImplementedError):
logger.info("Symlinking failed, copying to %s", dest)
copy_file_or_folder(src, dest, symlink)
else:
logger.info("Copying to %s", dest)
copy_file_or_folder(src, dest, symlink)
|
https://github.com/pypa/virtualenv/issues/490
|
Symlinking Python bootstrap modules
Symlinking /lib/python2.7/config -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/config
Symlinking /lib/python2.7/lib-dynload -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/lib-dynload
Symlinking /lib/python2.7/os.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/os.py
Ignoring built-in bootstrap module: posix
Symlinking /lib/python2.7/posixpath.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/posixpath.py
Cannot import bootstrap module: nt
Symlinking /lib/python2.7/ntpath.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/ntpath.py
Symlinking /lib/python2.7/genericpath.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/genericpath.py
Symlinking /lib/python2.7/fnmatch.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/fnmatch.py
Symlinking /lib/python2.7/locale.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/locale.py
Symlinking /lib/python2.7/encodings -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/encodings
Symlinking /lib/python2.7/codecs.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/codecs.py
Symlinking /lib/python2.7/stat.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/stat.py
Symlinking /lib/python2.7/UserDict.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/UserDict.py
Symlinking /lib/python2.7/copy_reg.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/copy_reg.py
Symlinking /lib/python2.7/types.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/types.py
Symlinking /lib/python2.7/re.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/re.py
Symlinking /lib/python2.7/sre.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/sre.py
Symlinking /lib/python2.7/sre_parse.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/sre_parse.py
Symlinking /lib/python2.7/sre_constants.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/sre_constants.py
Symlinking /lib/python2.7/sre_compile.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/sre_compile.py
Symlinking /lib/python2.7/warnings.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/warnings.py
Symlinking /lib/python2.7/linecache.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/linecache.py
Symlinking /lib/python2.7/_abcoll.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/_abcoll.py
Symlinking /lib/python2.7/abc.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/abc.py
Symlinking /lib/python2.7/_weakrefset.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/_weakrefset.py
Creating /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/site-packages
Writing /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/site.py
Writing /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/orig-prefix.txt
Creating parent directories for /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/include
Symlinking /include/python2.7 -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/include/python2.7
Symlinking /bin/..//opt/python/lib/python2.7/mailbox.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/mailbox.py
Symlinking /bin/..//opt/python/lib/python2.7/repr.pyo -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/repr.pyo
Symlinking /bin/..//opt/python/lib/python2.7/symbol.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/symbol.py
Symlinking /bin/..//opt/python/lib/python2.7/mimify.pyo -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/mimify.pyo
Symlinking /bin/..//opt/python/lib/python2.7/ihooks.pyo -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/ihooks.pyo
Symlinking /bin/..//opt/python/lib/python2.7/macpath.pyo -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/macpath.pyo
Symlinking /bin/..//opt/python/lib/python2.7/mimetools.pyo -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/mimetools.pyo
Symlinking /bin/..//opt/python/lib/python2.7/smtplib.pyo -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/smtplib.pyo
Symlinking /bin/..//opt/python/lib/python2.7/sched.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/sched.py
Symlinking /bin/..//opt/python/lib/python2.7/zipfile.pyo -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/zipfile.pyo
Symlinking /bin/..//opt/python/lib/python2.7/user.pyo -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/user.pyo
Symlinking /bin/..//opt/python/lib/python2.7/_threading_local.pyo -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/_threading_local.pyo
Symlinking /bin/..//opt/python/lib/python2.7/xml -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/xml
Symlinking /bin/..//opt/python/lib/python2.7/SocketServer.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/SocketServer.py
Symlinking /bin/..//opt/python/lib/python2.7/robotparser.pyo -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/robotparser.pyo
Symlinking /bin/..//opt/python/lib/python2.7/re.py -> /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/re.py
Symlinking failed, copying to /src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/re.py
copy: src:/bin/..//opt/python/lib/python2.7/re.py dest:/src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/re.py
Traceback (most recent call last):
File "/src/build/firefox/mozilla-release/python/virtualenv/virtualenv.py", line 2573, in <module>
main()
File "/src/build/firefox/mozilla-release/python/virtualenv/virtualenv.py", line 974, in main
never_download=options.never_download)
File "/src/build/firefox/mozilla-release/python/virtualenv/virtualenv.py", line 1075, in create_environment
site_packages=site_packages, clear=clear))
File "/src/build/firefox/mozilla-release/python/virtualenv/virtualenv.py", line 1319, in install_python
copyfile(join(exec_dir, fn), join(lib_dir, fn))
File "/src/build/firefox/mozilla-release/python/virtualenv/virtualenv.py", line 447, in copyfile
copyfileordir(src, dest)
File "/src/build/firefox/mozilla-release/python/virtualenv/virtualenv.py", line 424, in copyfileordir
shutil.copy2(src, dest)
File "/lib/python2.7/shutil.py", line 128, in copy2
copyfile(src, dst)
File "/lib/python2.7/shutil.py", line 83, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 2] No such file or directory: '/src/build/firefox/mozilla-release/firefox-build-dir/_virtualenv/lib/python2.7/re.py'
Traceback (most recent call last):
File "/src/build/firefox/mozilla-release/build/virtualenv/populate_virtualenv.py", line 384, in <module>
manager.ensure()
File "/src/build/firefox/mozilla-release/build/virtualenv/populate_virtualenv.py", line 103, in ensure
return self.build()
File "/src/build/firefox/mozilla-release/build/virtualenv/populate_virtualenv.py", line 315, in build
self.create()
File "/src/build/firefox/mozilla-release/build/virtualenv/populate_virtualenv.py", line 122, in create
raise Exception('Error creating virtualenv.')
Exception: Error creating virtualenv.
|
IOError
|
def replacements(self, creator, dest_folder):
replacements = super(PythonActivator, self).replacements(creator, dest_folder)
site_dump = json.dumps(
list({os.path.relpath(str(i), str(dest_folder)) for i in creator.libs}),
indent=2,
)
replacements.update({"__SITE_PACKAGES__": site_dump})
return replacements
|
def replacements(self, creator, dest_folder):
replacements = super(PythonActivator, self).replacements(creator, dest_folder)
site_dump = json.dumps(
[os.path.relpath(str(i), str(dest_folder)) for i in creator.site_packages],
indent=2,
)
replacements.update({"__SITE_PACKAGES__": site_dump})
return replacements
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def replacements(self, creator, dest_folder):
return {
"__VIRTUAL_PROMPT__": "" if self.flag_prompt is None else self.flag_prompt,
"__VIRTUAL_ENV__": six.ensure_text(str(creator.dest_dir)),
"__VIRTUAL_NAME__": creator.env_name,
"__BIN_NAME__": six.ensure_text(
str(creator.bin_dir.relative_to(creator.dest_dir))
),
"__PATH_SEP__": os.pathsep,
}
|
def replacements(self, creator, dest_folder):
return {
"__VIRTUAL_PROMPT__": "" if self.flag_prompt is None else self.flag_prompt,
"__VIRTUAL_ENV__": six.ensure_text(str(creator.dest_dir)),
"__VIRTUAL_NAME__": creator.env_name,
"__BIN_NAME__": six.ensure_text(str(creator.bin_name)),
"__PATH_SEP__": os.pathsep,
}
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def is_fs_case_sensitive():
global _FS_CASE_SENSITIVE
if _FS_CASE_SENSITIVE is None:
with tempfile.NamedTemporaryFile(prefix="TmP") as tmp_file:
_FS_CASE_SENSITIVE = not os.path.exists(tmp_file.name.lower())
logging.debug(
"filesystem under %r is %scase-sensitive",
tmp_file.name,
"" if _FS_CASE_SENSITIVE else "not ",
)
return _FS_CASE_SENSITIVE
|
def is_fs_case_sensitive():
global _FS_CASE_SENSITIVE
if _FS_CASE_SENSITIVE is None:
with tempfile.NamedTemporaryFile(prefix="TmP") as tmp_file:
_FS_CASE_SENSITIVE = not os.path.exists(tmp_file.name.lower())
logging.debug(
"filesystem under is %r%s case-sensitive",
tmp_file.name,
"" if _FS_CASE_SENSITIVE else " not",
)
return _FS_CASE_SENSITIVE
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def __init__(self, options, interpreter):
self.interpreter = interpreter
self._debug = None
self.dest_dir = Path(options.dest_dir)
self.enable_system_site_package = options.system_site
self.clear = options.clear
self.pyenv_cfg = PyEnvCfg.from_folder(self.dest_dir)
self._stdlib = None
self._system_stdlib = None
self._conf_vars = None
|
def __init__(self, options, interpreter):
self.interpreter = interpreter
self._debug = None
self.dest_dir = Path(options.dest_dir)
self.enable_system_site_package = options.system_site
self.clear = options.clear
self.pyenv_cfg = PyEnvCfg.from_folder(self.dest_dir)
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def set_pyenv_cfg(self):
self.pyenv_cfg.content = {
"home": self.interpreter.system_exec_prefix,
"include-system-site-packages": "true"
if self.enable_system_site_package
else "false",
"implementation": self.interpreter.implementation,
"version_info": ".".join(str(i) for i in self.interpreter.version_info),
"virtualenv": __version__,
}
|
def set_pyenv_cfg(self):
self.pyenv_cfg.content = {
"home": self.interpreter.system_exec_prefix,
"include-system-site-packages": "true"
if self.enable_system_site_package
else "false",
"implementation": self.interpreter.implementation,
"virtualenv": __version__,
}
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def run():
"""print debug data about the virtual environment"""
try:
from collections import OrderedDict
except ImportError: # pragma: no cover
# this is possible if the standard library cannot be accessed
# noinspection PyPep8Naming
OrderedDict = dict # pragma: no cover
result = OrderedDict([("sys", OrderedDict())])
path_keys = (
"executable",
"_base_executable",
"prefix",
"base_prefix",
"real_prefix",
"exec_prefix",
"base_exec_prefix",
"path",
"meta_path",
)
for key in path_keys:
value = getattr(sys, key, None)
if isinstance(value, list):
value = encode_list_path(value)
else:
value = encode_path(value)
result["sys"][key] = value
result["sys"]["fs_encoding"] = sys.getfilesystemencoding()
result["sys"]["io_encoding"] = getattr(sys.stdout, "encoding", None)
result["version"] = sys.version
import os # landmark
result["os"] = repr(os)
try:
# noinspection PyUnresolvedReferences
import site # site
result["site"] = repr(site)
except ImportError as exception: # pragma: no cover
result["site"] = repr(exception) # pragma: no cover
try:
# noinspection PyUnresolvedReferences
import datetime # site
result["datetime"] = repr(datetime)
except ImportError as exception: # pragma: no cover
result["datetime"] = repr(exception) # pragma: no cover
try:
# noinspection PyUnresolvedReferences
import math # site
result["math"] = repr(math)
except ImportError as exception: # pragma: no cover
result["math"] = repr(exception) # pragma: no cover
# try to print out, this will validate if other core modules are available (json in this case)
try:
import json
result["json"] = repr(json)
print(json.dumps(result, indent=2))
except (ImportError, ValueError, TypeError) as exception: # pragma: no cover
result["json"] = repr(exception) # pragma: no cover
print(repr(result)) # pragma: no cover
raise SystemExit(1) # pragma: no cover
|
def run():
"""print debug data about the virtual environment"""
try:
from collections import OrderedDict
except ImportError: # pragma: no cover
# this is possible if the standard library cannot be accessed
# noinspection PyPep8Naming
OrderedDict = dict # pragma: no cover
result = OrderedDict([("sys", OrderedDict())])
path_keys = (
"executable",
"_base_executable",
"prefix",
"base_prefix",
"real_prefix",
"exec_prefix",
"base_exec_prefix",
"path",
"meta_path",
)
for key in path_keys:
value = getattr(sys, key, None)
if isinstance(value, list):
value = encode_list_path(value)
else:
value = encode_path(value)
result["sys"][key] = value
result["sys"]["fs_encoding"] = sys.getfilesystemencoding()
result["sys"]["io_encoding"] = getattr(sys.stdout, "encoding", None)
result["version"] = sys.version
import os # landmark
result["os"] = repr(os)
try:
# noinspection PyUnresolvedReferences
import site # site
result["site"] = repr(site)
except ImportError as exception: # pragma: no cover
result["site"] = repr(exception) # pragma: no cover
try:
# noinspection PyUnresolvedReferences
import datetime # site
result["datetime"] = repr(datetime)
except ImportError as exception: # pragma: no cover
result["datetime"] = repr(exception) # pragma: no cover
# try to print out, this will validate if other core modules are available (json in this case)
try:
import json
result["json"] = repr(json)
print(json.dumps(result, indent=2))
except (ImportError, ValueError, TypeError) as exception: # pragma: no cover
result["json"] = repr(exception) # pragma: no cover
print(repr(result)) # pragma: no cover
raise SystemExit(1) # pragma: no cover
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def ensure_directories(self):
return super(PyPy, self).ensure_directories() | {self.lib_pypy}
|
def ensure_directories(self):
dirs = super(PyPy, self).ensure_directories()
dirs.add(self.lib_pypy)
return dirs
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def _shared_lib_to(self):
return super(PyPy3, self)._shared_lib_to() + [self.stdlib.parent.parent]
|
def _shared_lib_to(self):
return super(PyPy3, self)._shared_lib_to() + [self.dest_dir / self.lib_name]
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def __init__(self, options, interpreter):
self.builtin_way = options.builtin_way
super(Venv, self).__init__(options, interpreter)
self.can_be_inline = (
interpreter is CURRENT
and interpreter.executable == interpreter.system_executable
)
self._context = None
|
def __init__(self, options, interpreter):
super(Venv, self).__init__(options, interpreter)
self.can_be_inline = (
interpreter is CURRENT
and interpreter.executable == interpreter.system_executable
)
self._context = None
self.builtin_way = options.builtin_way
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def create(self):
if self.can_be_inline:
self.create_inline()
else:
self.create_via_sub_process()
# TODO: cleanup activation scripts
for lib in self.libs:
ensure_dir(lib)
|
def create(self):
if self.can_be_inline:
self.create_inline()
else:
self.create_via_sub_process()
# TODO: cleanup activation scripts
if self.builtin_way is not None:
for site_package in self.builtin_way.site_packages:
ensure_dir(site_package)
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def fixup_python2(self):
"""Perform operations needed to make the created environment work on Python 2"""
for module in self.modules():
self.add_module(module)
# 2. install a patched site-package, the default Python 2 site.py is not smart enough to understand pyvenv.cfg,
# so we inject a small shim that can do this
site_py = self.stdlib / "site.py"
custom_site = get_custom_site()
if IS_ZIPAPP:
custom_site_text = read_from_zipapp(custom_site)
else:
custom_site_text = custom_site.read_text()
expected = json.dumps(
[
os.path.relpath(six.ensure_text(str(i)), six.ensure_text(str(site_py)))
for i in self.libs
]
)
site_py.write_text(
custom_site_text.replace("___EXPECTED_SITE_PACKAGES___", expected)
)
|
def fixup_python2(self):
"""Perform operations needed to make the created environment work on Python 2"""
for module in self.modules():
self.add_module(module)
# 2. install a patched site-package, the default Python 2 site.py is not smart enough to understand pyvenv.cfg,
# so we inject a small shim that can do this
site_py = self.lib_dir / "site.py"
relative_site_packages = [
os.path.relpath(six.ensure_text(str(s)), six.ensure_text(str(site_py)))
for s in self.site_packages
]
custom_site = get_custom_site()
if IS_ZIPAPP:
custom_site_text = read_from_zipapp(custom_site)
else:
custom_site_text = custom_site.read_text()
site_py.write_text(
custom_site_text.replace(
"___EXPECTED_SITE_PACKAGES___", json.dumps(relative_site_packages)
)
)
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def add_module(self, req):
for ext in ["py", "pyc"]:
file_path = "{}.{}".format(req, ext)
self.copier(self.system_stdlib / file_path, self.stdlib / file_path)
|
def add_module(self, req):
for ext in ["py", "pyc"]:
file_path = "{}.{}".format(req, ext)
self.copier(self.system_stdlib / file_path, self.lib_dir / file_path)
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def add_folder(self, folder):
self.copier(self.system_stdlib / folder, self.stdlib / folder)
|
def add_folder(self, folder):
self.copier(self.system_stdlib / folder, self.lib_dir / folder)
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def ensure_directories(self):
return {self.dest_dir, self.bin_dir, self.script_dir, self.stdlib} | set(self.libs)
|
def ensure_directories(self):
dirs = {self.dest_dir, self.bin_dir, self.lib_dir}
dirs.update(self.site_packages)
return dirs
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def __init__(self):
def u(v):
return v.decode("utf-8") if isinstance(v, bytes) else v
# qualifies the python
self.platform = u(sys.platform)
self.implementation = u(platform.python_implementation())
if self.implementation == "PyPy":
self.pypy_version_info = tuple(u(i) for i in sys.pypy_version_info)
# this is a tuple in earlier, struct later, unify to our own named tuple
self.version_info = VersionInfo(*list(u(i) for i in sys.version_info))
self.architecture = 64 if sys.maxsize > 2**32 else 32
self.executable = u(sys.executable) # executable we were called with
self.original_executable = u(self.executable)
self.base_executable = u(
getattr(sys, "_base_executable", None)
) # some platforms may set this
self.version = u(sys.version)
self.os = u(os.name)
# information about the prefix - determines python home
self.prefix = u(getattr(sys, "prefix", None)) # prefix we think
self.base_prefix = u(getattr(sys, "base_prefix", None)) # venv
self.real_prefix = u(getattr(sys, "real_prefix", None)) # old virtualenv
# information about the exec prefix - dynamic stdlib modules
self.base_exec_prefix = u(getattr(sys, "base_exec_prefix", None))
self.exec_prefix = u(getattr(sys, "exec_prefix", None))
try:
__import__("venv")
has = True
except ImportError:
has = False
self.has_venv = has
self.path = [u(i) for i in sys.path]
self.file_system_encoding = u(sys.getfilesystemencoding())
self.stdout_encoding = u(getattr(sys.stdout, "encoding", None))
self.sysconfig_paths = {
u(i): u(sysconfig.get_path(i, expand=False)) for i in sysconfig.get_path_names()
}
config_var_keys = set()
for element in self.sysconfig_paths.values():
for k in _CONF_VAR_RE.findall(element):
config_var_keys.add(u(k[1:-1]))
self.sysconfig_config_vars = {
u(i): u(sysconfig.get_config_var(i)) for i in config_var_keys
}
self.distutils_install = {u(k): u(v) for k, v in self._distutils_install().items()}
|
def __init__(self):
# qualifies the python
self.platform = sys.platform
self.implementation = platform.python_implementation()
self.pypy_version_info = (
tuple(sys.pypy_version_info) if self.implementation == "PyPy" else None
)
# this is a tuple in earlier, struct later, unify to our own named tuple
self.version_info = VersionInfo(*list(sys.version_info))
self.architecture = 64 if sys.maxsize > 2**32 else 32
self.executable = sys.executable # executable we were called with
self.original_executable = self.executable
self.base_executable = getattr(
sys, "_base_executable", None
) # some platforms may set this
self.version = sys.version
self.os = os.name
# information about the prefix - determines python home
self.prefix = getattr(sys, "prefix", None) # prefix we think
self.base_prefix = getattr(sys, "base_prefix", None) # venv
self.real_prefix = getattr(sys, "real_prefix", None) # old virtualenv
# information about the exec prefix - dynamic stdlib modules
self.base_exec_prefix = getattr(sys, "base_exec_prefix", None)
self.exec_prefix = getattr(sys, "exec_prefix", None)
try:
__import__("venv")
has = True
except ImportError:
has = False
self.has_venv = has
self.path = sys.path
self.file_system_encoding = sys.getfilesystemencoding()
self.stdout_encoding = getattr(sys.stdout, "encoding", None)
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def from_json(cls, payload):
data = json.loads(payload)
data["version_info"] = VersionInfo(
**data["version_info"]
) # restore this to a named tuple structure
result = cls()
result.__dict__ = {k: v for k, v in data.items()}
return result
|
def from_json(cls, payload):
data = json.loads(payload)
data["version_info"] = VersionInfo(
**data["version_info"]
) # restore this to a named tuple structure
result = cls()
for var in vars(result):
setattr(result, var, data[var])
return result
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def _load_for_exe(cls, exe):
from virtualenv.util.subprocess import subprocess, Popen
cmd = cls._get_exe_cmd(exe)
# noinspection DuplicatedCode
# this is duplicated here because this file is executed on its own, so cannot be refactored otherwise
logging.debug("get interpreter info via cmd: %s", Cmd(cmd))
try:
process = Popen(
cmd,
universal_newlines=True,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
)
out, err = process.communicate()
code = process.returncode
except OSError as os_error:
out, err, code = "", os_error.strerror, os_error.errno
result, failure = None, None
if code == 0:
result = cls.from_json(out)
result.executable = (
exe # keep original executable as this may contain initialization code
)
else:
msg = "failed to query {} with code {}{}{}".format(
exe,
code,
" out: {!r}".format(out) if out else "",
" err: {!r}".format(err) if err else "",
)
failure = RuntimeError(msg)
return failure, result
|
def _load_for_exe(cls, exe):
from virtualenv.util.subprocess import subprocess, Popen
cmd = cls._get_exe_cmd(exe)
# noinspection DuplicatedCode
# this is duplicated here because this file is executed on its own, so cannot be refactored otherwise
logging.debug("get interpreter info via cmd: %s", Cmd(cmd))
try:
process = Popen(
cmd,
universal_newlines=True,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
)
out, err = process.communicate()
code = process.returncode
except OSError as os_error:
out, err, code = "", os_error.strerror, os_error.errno
result, failure = None, None
if code == 0:
result = cls.from_json(out)
result.executable = (
exe # keep original executable as this may contain initialization code
)
else:
msg = "failed to query {} with code {}{}{}".format(
exe,
code,
" out: {!r}".format(out) if out else "",
" err: {!r}".format(err) if err else "",
)
failure = RuntimeError(msg)
return failure, result
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def __repr__(self):
def e(v):
return v.decode("utf-8") if isinstance(v, bytes) else v
cmd_repr = e(" ").join(pipes.quote(e(c)) for c in self.cmd)
if self.env is not None:
cmd_repr += e(" env of {!r}").format(self.env)
return cmd_repr
|
def __repr__(self):
cmd_repr = " ".join(pipes.quote(c) for c in self.cmd)
if self.env is not None:
cmd_repr += " env of {!r}".format(self.env)
return cmd_repr
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def install(self):
self._extracted = True
# sync image
for filename in self._image_dir.iterdir():
into = self._creator.purelib / filename.name
logging.debug("%s %s from %s", self.__class__.__name__, into, filename)
if into.exists():
if into.is_dir() and not into.is_symlink():
shutil.rmtree(str(into))
else:
into.unlink()
self._sync(filename, into)
# generate console executables
consoles = set()
script_dir = self._creator.script_dir
for name, module in self._console_scripts.items():
consoles.update(self._create_console_entry_point(name, module, script_dir))
logging.debug("generated console scripts %s", " ".join(i.name for i in consoles))
|
def install(self):
self._extracted = True
# sync image
site_package = self._creator.site_packages[0]
for filename in self._image_dir.iterdir():
into = site_package / filename.name
logging.debug("%s %s from %s", self.__class__.__name__, into, filename)
if into.exists():
if into.is_dir() and not into.is_symlink():
shutil.rmtree(str(into))
else:
into.unlink()
self._sync(filename, into)
# generate console executables
consoles = set()
bin_dir = self._creator.bin_dir
for name, module in self._console_scripts.items():
consoles.update(self._create_console_entry_point(name, module, bin_dir))
logging.debug("generated console scripts %s", " ".join(i.name for i in consoles))
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def _generate_new_files(self):
new_files = set()
installer = self._dist_info / "INSTALLER"
installer.write_text("pip\n")
new_files.add(installer)
# inject a no-op root element, as workaround for bug added
# by https://github.com/pypa/pip/commit/c7ae06c79#r35523722
marker = self._image_dir / "{}.virtualenv".format(self._dist_info.name)
marker.write_text("")
new_files.add(marker)
folder = mkdtemp()
try:
to_folder = Path(folder)
rel = os.path.relpath(
six.ensure_text(str(self._creator.script_dir)),
six.ensure_text(str(self._creator.purelib)),
)
for name, module in self._console_scripts.items():
new_files.update(
Path(
os.path.normpath(
six.ensure_text(str(self._image_dir / rel / i.name))
)
)
for i in self._create_console_entry_point(name, module, to_folder)
)
finally:
shutil.rmtree(folder, ignore_errors=True)
return new_files
|
def _generate_new_files(self):
new_files = set()
installer = self._dist_info / "INSTALLER"
installer.write_text("pip\n")
new_files.add(installer)
# inject a no-op root element, as workaround for bug added
# by https://github.com/pypa/pip/commit/c7ae06c79#r35523722
marker = self._image_dir / "{}.virtualenv".format(self._dist_info.name)
marker.write_text("")
new_files.add(marker)
folder = mkdtemp()
try:
to_folder = Path(folder)
rel = os.path.relpath(
six.ensure_text(str(self._creator.bin_dir)),
six.ensure_text(str(self._creator.site_packages[0])),
)
for name, module in self._console_scripts.items():
new_files.update(
Path(
os.path.normpath(
six.ensure_text(str(self._image_dir / rel / i.name))
)
)
for i in self._create_console_entry_point(name, module, to_folder)
)
finally:
shutil.rmtree(folder, ignore_errors=True)
return new_files
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def make_exe(filename):
original_mode = filename.stat().st_mode
levels = [S_IXUSR, S_IXGRP, S_IXOTH]
for at in range(len(levels), 0, -1):
try:
mode = original_mode
for level in levels[:at]:
mode |= level
filename.chmod(mode)
break
except OSError:
continue
|
def make_exe(filename):
original_mode = filename.stat().st_mode
levels = [S_IXUSR, S_IXGRP, S_IXOTH]
for at in range(len(levels), 0, -1):
try:
mode = original_mode
for level in levels[:at]:
mode |= level
filename.chmod(mode)
break
except PermissionError:
continue
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def symlink_or_copy(do_copy, src, dst, relative_symlinks_ok=False):
"""
Try symlinking a target, and if that fails, fall back to copying.
"""
if not src.exists():
raise RuntimeError("source {} does not exists".format(src))
if src == dst:
raise RuntimeError("source {} is same as destination ".format(src))
def norm(val):
if IS_PYPY and six.PY3:
return str(val).encode(sys.getfilesystemencoding())
return six.ensure_text(str(val))
if do_copy is False and HAS_SYMLINK is False: # if no symlink, always use copy
do_copy = True
if not do_copy:
try:
if not dst.is_symlink(): # can't link to itself!
if relative_symlinks_ok:
assert src.parent == dst.parent
os.symlink(norm(src.name), norm(dst))
else:
os.symlink(norm(str(src)), norm(dst))
except OSError as exception:
logging.warning(
"symlink failed %r, for %s to %s, will try copy",
exception,
six.ensure_text(str(src)),
six.ensure_text(str(dst)),
)
do_copy = True
if do_copy:
copier = shutil.copy2 if src.is_file() else shutil.copytree
copier(norm(src), norm(dst))
logging.debug(
"%s %s to %s",
"copy" if do_copy else "symlink",
six.ensure_text(str(src)),
six.ensure_text(str(dst)),
)
|
def symlink_or_copy(do_copy, src, dst, relative_symlinks_ok=False):
"""
Try symlinking a target, and if that fails, fall back to copying.
"""
def norm(val):
if IS_PYPY and six.PY3:
return str(val).encode(sys.getfilesystemencoding())
return six.ensure_text(str(val))
if do_copy is False and HAS_SYMLINK is False: # if no symlink, always use copy
do_copy = True
if not do_copy:
try:
if not dst.is_symlink(): # can't link to itself!
if relative_symlinks_ok:
assert src.parent == dst.parent
os.symlink(norm(src.name), norm(dst))
else:
os.symlink(norm(str(src)), norm(dst))
except OSError as exception:
logging.warning(
"symlink failed %r, for %s to %s, will try copy",
exception,
six.ensure_text(str(src)),
six.ensure_text(str(dst)),
)
do_copy = True
if do_copy:
copier = shutil.copy2 if src.is_file() else shutil.copytree
copier(norm(src), norm(dst))
logging.debug(
"%s %s to %s",
"copy" if do_copy else "symlink",
six.ensure_text(str(src)),
six.ensure_text(str(dst)),
)
|
https://github.com/pypa/virtualenv/issues/1332
|
$ <scl_base>/bin/virtualenv --python <scl_base>/bin/python --always-copy --verbose TEST
Running virtualenv with interpreter <scl_base>/bin/python
Using base prefix '<scl_base>'
Creating <somedir>/TEST/lib/python3.6
Copying to <somedir>/TEST/lib64
Symlinking Python bootstrap modules
Copying to <somedir>/TEST/lib/python3.6/config-3.6m-x86_64-linux-gnu
Copying to <somedir>/TEST/lib/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/os.py
Ignoring built-in bootstrap module: posix
Copying to <somedir>/TEST/lib64/python3.6/posixpath.py
Cannot import bootstrap module: nt
Copying to <somedir>/TEST/lib64/python3.6/ntpath.py
Copying to <somedir>/TEST/lib64/python3.6/genericpath.py
Copying to <somedir>/TEST/lib64/python3.6/fnmatch.py
Copying to <somedir>/TEST/lib64/python3.6/locale.py
Copying to <somedir>/TEST/lib64/python3.6/encodings
Copying to <somedir>/TEST/lib64/python3.6/codecs.py
Copying to <somedir>/TEST/lib64/python3.6/stat.py
Cannot import bootstrap module: UserDict
Creating parent directories for <somedir>/TEST/lib64/python3.6/lib-dynload
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/readline.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: copy_reg
Copying to <somedir>/TEST/lib64/python3.6/types.py
Copying to <somedir>/TEST/lib64/python3.6/re.py
Cannot import bootstrap module: sre
Copying to <somedir>/TEST/lib64/python3.6/sre_parse.py
Copying to <somedir>/TEST/lib64/python3.6/sre_constants.py
Copying to <somedir>/TEST/lib64/python3.6/sre_compile.py
Copying to <somedir>/TEST/lib64/python3.6/lib-dynload/zlib.cpython-36m-x86_64-linux-gnu.so
Cannot import bootstrap module: _abcoll
Copying to <somedir>/TEST/lib64/python3.6/warnings.py
Copying to <somedir>/TEST/lib64/python3.6/linecache.py
Copying to <somedir>/TEST/lib64/python3.6/abc.py
Copying to <somedir>/TEST/lib64/python3.6/io.py
Copying to <somedir>/TEST/lib64/python3.6/_weakrefset.py
Copying to <somedir>/TEST/lib64/python3.6/copyreg.py
Copying to <somedir>/TEST/lib64/python3.6/tempfile.py
Copying to <somedir>/TEST/lib64/python3.6/random.py
Copying to <somedir>/TEST/lib64/python3.6/__future__.py
Copying to <somedir>/TEST/lib64/python3.6/collections
Copying to <somedir>/TEST/lib64/python3.6/keyword.py
Copying to <somedir>/TEST/lib64/python3.6/tarfile.py
Copying to <somedir>/TEST/lib64/python3.6/shutil.py
Copying to <somedir>/TEST/lib64/python3.6/struct.py
Copying to <somedir>/TEST/lib64/python3.6/copy.py
Copying to <somedir>/TEST/lib64/python3.6/tokenize.py
Copying to <somedir>/TEST/lib64/python3.6/token.py
Copying to <somedir>/TEST/lib64/python3.6/functools.py
Copying to <somedir>/TEST/lib64/python3.6/heapq.py
Copying to <somedir>/TEST/lib64/python3.6/bisect.py
Copying to <somedir>/TEST/lib64/python3.6/weakref.py
Copying to <somedir>/TEST/lib64/python3.6/reprlib.py
Copying to <somedir>/TEST/lib64/python3.6/base64.py
Copying to <somedir>/TEST/lib64/python3.6/_dummy_thread.py
Copying to <somedir>/TEST/lib64/python3.6/hashlib.py
Copying to <somedir>/TEST/lib64/python3.6/hmac.py
Copying to <somedir>/TEST/lib64/python3.6/imp.py
Copying to <somedir>/TEST/lib64/python3.6/importlib
Copying to <somedir>/TEST/lib64/python3.6/rlcompleter.py
Copying to <somedir>/TEST/lib64/python3.6/operator.py
Copying to <somedir>/TEST/lib64/python3.6/_collections_abc.py
Copying to <somedir>/TEST/lib64/python3.6/_bootlocale.py
Copying to <somedir>/TEST/lib64/python3.6/enum.py
No LICENSE.txt / LICENSE found in source
Creating <somedir>/TEST/lib/python3.6/site-packages
Writing <somedir>/TEST/lib64/python3.6/site.py
Writing <somedir>/TEST/lib64/python3.6/orig-prefix.txt
Writing <somedir>/TEST/lib64/python3.6/no-global-site-packages.txt
Creating <somedir>/TEST/bin
New python executable in <somedir>/TEST/bin/python
Changed mode of <somedir>/TEST/bin/python to 0o775
Copying to <somedir>/TEST/bin/python3
Copying to <somedir>/TEST/bin/python3.6
Testing executable with <somedir>/TEST/bin/python -c "import sys;out=sys.stdout;getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))"
Got sys.prefix result: '<somedir>/TEST'
Creating <somedir>/TEST/lib64/python3.6/distutils
Writing <somedir>/TEST/lib64/python3.6/distutils/__init__.py
Writing <somedir>/TEST/lib64/python3.6/distutils/distutils.cfg
Traceback (most recent call last):
File "<scl_base>/lib64/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "<scl_base>/lib64/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/__main__.py", line 16, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_internal/__init__.py", line 19, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/__init__.py", line 8, in <module>
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv_support/pip-19.0.3-py2.py3-none-any.whl/pip/_vendor/urllib3/connectionpool.py", line 7, in <module>
File "<scl_base>/lib64/python3.6/socket.py", line 49, in <module>
import _socket
ModuleNotFoundError: No module named '_socket'
Command <somedir>/TEST/bin/python -m pip config list had error code 1
Installing setuptools, pip, wheel...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
Complete output from command <somedir>/TEST/bin/python - setuptools pip wheel:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<somedir>/TEST/lib64/python3.6/tempfile.py", line 45, in <module>
from random import Random as _Random
File "<somedir>/TEST/lib64/python3.6/random.py", line 42, in <module>
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
ModuleNotFoundError: No module named 'math'
----------------------------------------
...Installing setuptools, pip, wheel...done.
Traceback (most recent call last):
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 2567, in <module>
main()
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1088, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 1025, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "<scl_base>/usr/lib/python3.6/site-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command <somedir>/TEST/bin/python - setuptools pip wheel failed with error code 1
|
ModuleNotFoundError
|
def _pip_config(py_executable, python_path):
cmd = [py_executable, "-m", "pip", "config", "list"]
config = {}
for line in call_subprocess(
cmd,
show_stdout=False,
extra_env={"PYTHONPATH": python_path, "JYTHONPATH": python_path},
remove_from_env=["PIP_VERBOSE", "PIP_QUIET"],
raise_on_return_code=False,
):
key, _, value = line.partition("=")
if value:
config[key] = ast.literal_eval(value)
return config
|
def _pip_config(py_executable, python_path):
cmd = [py_executable, "-m", "pip", "config", "list"]
config = {}
for line in call_subprocess(
cmd,
show_stdout=False,
extra_env={"PYTHONPATH": python_path, "JYTHONPATH": python_path},
remove_from_env=["PIP_VERBOSE", "PIP_QUIET"],
):
key, _, value = line.partition("=")
if value:
config[key] = ast.literal_eval(value)
return config
|
https://github.com/pypa/virtualenv/issues/1301
|
$ pip --version
pip 9.0.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)
$ pip list | grep virtualenv
virtualenv (16.3.0)
$ virtualenv /tmp/venv
New python executable in /tmp/venv/bin/python
Complete output from command /tmp/venv/bin/python -m pip config list:
ERROR: unknown command "config"
----------------------------------------
Traceback (most recent call last):
File "/usr/local/bin/virtualenv", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 793, in main
symlink=options.symlink,
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 1087, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 935, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 964, in _install_wheel_with_search_dir
config = _pip_config(py_executable, python_path)
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 1038, in _pip_config
remove_from_env=["PIP_VERBOSE", "PIP_QUIET"],
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 886, in call_subprocess
raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode))
OSError: Command /tmp/venv/bin/python -m pip config list failed with error code 1
|
OSError
|
def copy_required_modules(dst_prefix, symlink):
import imp
# If we are running under -p, we need to remove the current
# directory from sys.path temporarily here, so that we
# definitely get the modules from the site directory of
# the interpreter we are running under, not the one
# virtualenv.py is installed under (which might lead to py2/py3
# incompatibility issues)
_prev_sys_path = sys.path
if os.environ.get("VIRTUALENV_INTERPRETER_RUNNING"):
sys.path = sys.path[1:]
try:
for modname in REQUIRED_MODULES:
if modname in sys.builtin_module_names:
logger.info("Ignoring built-in bootstrap module: %s" % modname)
continue
try:
f, filename, _ = imp.find_module(modname)
except ImportError:
logger.info("Cannot import bootstrap module: %s" % modname)
else:
if f is not None:
f.close()
# special-case custom readline.so on OS X, but not for pypy:
if (
modname == "readline"
and sys.platform == "darwin"
and not (
is_pypy or filename.endswith(join("lib-dynload", "readline.so"))
)
):
dst_filename = join(
dst_prefix, "lib", "python%s" % sys.version[:3], "readline.so"
)
elif modname == "readline" and sys.platform == "win32":
# special-case for Windows, where readline is not a
# standard module, though it may have been installed in
# site-packages by a third-party package
pass
else:
dst_filename = change_prefix(filename, dst_prefix)
copyfile(filename, dst_filename, symlink)
if filename.endswith(".pyc"):
pyfile = filename[:-1]
if os.path.exists(pyfile):
copyfile(pyfile, dst_filename[:-1], symlink)
finally:
sys.path = _prev_sys_path
|
def copy_required_modules(dst_prefix, symlink):
import imp
# If we are running under -p, we need to remove the current
# directory from sys.path temporarily here, so that we
# definitely get the modules from the site directory of
# the interpreter we are running under, not the one
# virtualenv.py is installed under (which might lead to py2/py3
# incompatibility issues)
_prev_sys_path = sys.path
if os.environ.get("VIRTUALENV_INTERPRETER_RUNNING"):
sys.path = sys.path[1:]
try:
for modname in REQUIRED_MODULES:
if modname in sys.builtin_module_names:
logger.info("Ignoring built-in bootstrap module: %s" % modname)
continue
try:
f, filename, _ = imp.find_module(modname)
except ImportError:
logger.info("Cannot import bootstrap module: %s" % modname)
else:
if f is not None:
f.close()
# special-case custom readline.so on OS X, but not for pypy:
if (
modname == "readline"
and sys.platform == "darwin"
and not (
is_pypy or filename.endswith(join("lib-dynload", "readline.so"))
)
):
dst_filename = join(
dst_prefix, "lib", "python%s" % sys.version[:3], "readline.so"
)
else:
dst_filename = change_prefix(filename, dst_prefix)
copyfile(filename, dst_filename, symlink)
if filename.endswith(".pyc"):
pyfile = filename[:-1]
if os.path.exists(pyfile):
copyfile(pyfile, dst_filename[:-1], symlink)
finally:
sys.path = _prev_sys_path
|
https://github.com/pypa/virtualenv/issues/4
|
Traceback (most recent call last):
File "virtualenv.py", line 1645, in <module>
main()
File "virtualenv.py", line 556, in main
prompt=options.prompt)
File "virtualenv.py", line 645, in create_environment
site_packages=site_packages, clear=clear))
File "virtualenv.py", line 769, in install_python
copy_required_modules(home_dir)
File "virtualenv.py", line 723, in copy_required_modules
dst_filename = change_prefix(filename, dst_prefix)
File "virtualenv.py", line 708, in change_prefix
(filename, prefixes)
AssertionError: Filename /home/apy/.local/lib/python2.6/site-packages/readline.so does not start with any of these prefixes: ['/opt/ActivePython-2.6']
|
AssertionError
|
def _cpp_jit(
fun: F,
static_argnums: Union[int, Iterable[int]] = (),
device: Optional[xc.Device] = None,
backend: Optional[str] = None,
donate_argnums: Union[int, Iterable[int]] = (),
) -> F:
"""An implementation of `jit` that tries to do as much as possible in C++.
The goal of this function is to speed up the time it takes to process the
arguments, find the correct C++ executable, start the transfer of arguments
and schedule the computation.
As long as it does not support all features of the Python implementation
the C++ code will fallback to `_python_jit` when it faces some unsupported
feature.
"""
_check_callable(fun)
static_argnums = _ensure_index_tuple(static_argnums)
donate_argnums = _ensure_index_tuple(donate_argnums)
donate_argnums = rebase_donate_argnums(donate_argnums, static_argnums)
if device is not None and backend is not None:
raise ValueError(
"can't specify both a device and a backend for jit, "
f"got device={device} and backend={backend}."
)
def cache_miss(_, *args, **kwargs):
### This first part is basically the same code as in _python_jit.
# An alternative would be for cache_miss to accept from C++ the arguments
# (dyn_args, donated_invars, args_flat, in_tree), since otherwise we have
# work/code that is redundant between C++ and Python. We can try that later.
if max(static_argnums + donate_argnums, default=-1) >= len(args):
msg = (
"jitted function has static_argnums={}, donate_argnums={} but "
"was called with only {} positional arguments."
)
raise ValueError(msg.format(static_argnums, donate_argnums, len(args)))
f = lu.wrap_init(fun)
if static_argnums:
f, dyn_args = argnums_partial_except(f, static_argnums, args)
else:
dyn_args = args
args_flat, in_tree = tree_flatten((dyn_args, kwargs))
if donate_argnums:
donated_invars = donation_vector(donate_argnums, dyn_args, kwargs)
else:
donated_invars = (False,) * len(args_flat)
for arg in args_flat:
_check_arg(arg)
flat_fun, out_tree = flatten_fun(f, in_tree)
out_flat = xla.xla_call(
flat_fun,
*args_flat,
device=device,
backend=backend,
name=flat_fun.__name__,
donated_invars=donated_invars,
)
out_pytree_def = out_tree()
out = tree_unflatten(out_pytree_def, out_flat)
### Decide whether we can support the C++ fast path
# High level note: The Python tracing mechanism is complex; in particular
# to know whether `jax.jit(f)(x)` will execute or trace, it's not enough to
# inspect the argument x, we actually do need to execute it and look at the
# outputs that could be tracers (if f is capturing `Tracer` by closure).
execute: Optional[functools.partial] = xla._xla_callable.most_recent_entry()
use_fastpath = (
# This is if we have already executed this code-path (most-recent entry
# has been reset to None). Thus, we do not support the fast-path.
execute is not None
and execute.func is xla._execute_compiled # not trivial, not pmap
and
# Not supported: ShardedDeviceArray, DeviceConstant.
all(xla.type_is_device_array(x) for x in out_flat)
and
# TODO(mattjj): Add support for lazy-expression.
# If the input is a DeviceArray, then it should have a trivial LazyExpr.
all(
type(x) is not xla.DeviceArray or xla.lazy.is_trivial(x._lazy_expr)
for x in args_flat
)
)
### If we can use the fastpath, we return required info to the caller.
if use_fastpath:
xla_executable, _, result_handlers = execute.args
sticky_device = None
avals = []
lazy_exprs = []
for result_handler in result_handlers:
aval, sticky_device, lazy_expr = result_handler.args
avals.append(aval)
lazy_exprs.append(None if xla.lazy.is_trivial(lazy_expr) else lazy_expr)
assert len(avals) == len(out_flat)
fastpath_data = (
xla_executable,
out_pytree_def,
sticky_device,
avals,
lazy_exprs,
)
else:
fastpath_data = None
return out, fastpath_data
def get_device_info():
"""Backends do not exist before __main__ is being executed."""
committed_to_device = device is not None or backend is not None
if device is not None:
default_device = device
else:
backend_ = xb.get_backend(backend)
default_device = backend_.get_default_device_assignment(1)[0]
return _BackendAndDeviceInfo(default_device, committed_to_device)
def get_jax_enable_x64():
"""Returns the value of the flag after GoogleInit.
We must wait until flags have been parsed (in particular for top-level
functions decorated with jax.jit), so we delay inspecting the value
of the jax_enable_x64 flag until JIT time.
"""
# TODO(jblespiau): Delete when jaxlib 0.1.62 is the minimal version.
if lib._xla_extension_version >= 4:
return config.read("jax_enable_x64")
else:
return config.x64_enabled
def get_jax_disable_jit_flag():
"""Returns the value of the `jax_disable_jit` flag.
Both a flag and the `disable_jit` context manager can disable jit. We access
the flag only once, when jitting the function, and the context manager
modifies a C++ thread-local value.
"""
return config.read("jax_disable_jit")
static_argnums_ = (0,) + tuple(i + 1 for i in static_argnums)
cpp_jitted_f = jax_jit.jit(
fun,
cache_miss,
get_device_info,
get_jax_enable_x64,
get_jax_disable_jit_flag,
static_argnums_,
)
# TODO(mattjj): make cpp callable follow descriptor protocol for bound methods
@wraps(fun)
@api_boundary
def f_jitted(*args, **kwargs):
# TODO(jblespiau): We can remove `config.x64_enabled` when jaxlib has
# extension version 4
context = (
getattr(core.thread_local_state.trace_state.trace_stack, "dynamic", None),
config.x64_enabled,
)
# TODO(jblespiau): Move this to C++.
if (FLAGS.jax_debug_nans or FLAGS.jax_debug_infs) and not _jit_is_disabled():
device_arrays = cpp_jitted_f(context, *args, **kwargs)
try:
xla.check_special(
xla.xla_call_p,
[
da.device_buffer
for da in tree_leaves(device_arrays)
if hasattr(da, "device_buffer")
],
)
return device_arrays
except FloatingPointError:
assert (
FLAGS.jax_debug_nans or FLAGS.jax_debug_infs
) # compiled_fun can only raise in this case
print(
"Invalid nan value encountered in the output of a C++-jit "
"function. Calling the de-optimized version."
)
return cache_miss(context, *args, **kwargs)[0] # probably won't return
elif _jit_is_disabled():
return cpp_jitted_f(*args, **kwargs)
else:
return cpp_jitted_f(context, *args, **kwargs)
f_jitted._cpp_jitted_f = cpp_jitted_f
return f_jitted
|
def _cpp_jit(
fun: F,
static_argnums: Union[int, Iterable[int]] = (),
device: Optional[xc.Device] = None,
backend: Optional[str] = None,
donate_argnums: Union[int, Iterable[int]] = (),
) -> F:
"""An implementation of `jit` that tries to do as much as possible in C++.
The goal of this function is to speed up the time it takes to process the
arguments, find the correct C++ executable, start the transfer of arguments
and schedule the computation.
As long as it does not support all features of the Python implementation
the C++ code will fallback to `_python_jit` when it faces some unsupported
feature.
"""
_check_callable(fun)
static_argnums = _ensure_index_tuple(static_argnums)
donate_argnums = _ensure_index_tuple(donate_argnums)
donate_argnums = rebase_donate_argnums(donate_argnums, static_argnums)
if device is not None and backend is not None:
raise ValueError(
"can't specify both a device and a backend for jit, "
f"got device={device} and backend={backend}."
)
def cache_miss(_, *args, **kwargs):
### This first part is basically the same code as in _python_jit.
# An alternative would be for cache_miss to accept from C++ the arguments
# (dyn_args, donated_invars, args_flat, in_tree), since otherwise we have
# work/code that is redundant between C++ and Python. We can try that later.
if max(static_argnums + donate_argnums, default=-1) >= len(args):
msg = (
"jitted function has static_argnums={}, donate_argnums={} but "
"was called with only {} positional arguments."
)
raise ValueError(msg.format(static_argnums, donate_argnums, len(args)))
f = lu.wrap_init(fun)
if static_argnums:
f, dyn_args = argnums_partial_except(f, static_argnums, args)
else:
dyn_args = args
args_flat, in_tree = tree_flatten((dyn_args, kwargs))
if donate_argnums:
donated_invars = donation_vector(donate_argnums, dyn_args, kwargs)
else:
donated_invars = (False,) * len(args_flat)
for arg in args_flat:
_check_arg(arg)
flat_fun, out_tree = flatten_fun(f, in_tree)
out_flat = xla.xla_call(
flat_fun,
*args_flat,
device=device,
backend=backend,
name=flat_fun.__name__,
donated_invars=donated_invars,
)
out_pytree_def = out_tree()
out = tree_unflatten(out_pytree_def, out_flat)
### Decide whether we can support the C++ fast path
# High level note: The Python tracing mechanism is complex; in particular
# to know whether `jax.jit(f)(x)` will execute or trace, it's not enough to
# inspect the argument x, we actually do need to execute it and look at the
# outputs that could be tracers (if f is capturing `Tracer` by closure).
execute: Optional[functools.partial] = xla._xla_callable.most_recent_entry()
use_fastpath = (
# This is if we have already executed this code-path (most-recent entry
# has been reset to None). Thus, we do not support the fast-path.
execute is not None
and execute.func is xla._execute_compiled # not trivial, not pmap
and
# Not supported: ShardedDeviceArray, DeviceConstant.
all(xla.type_is_device_array(x) for x in out_flat)
and
# TODO(mattjj): Add support for lazy-expression.
# If the input is a DeviceArray, then it should have a trivial LazyExpr.
all(
type(x) is not xla.DeviceArray or xla.lazy.is_trivial(x._lazy_expr)
for x in args_flat
)
)
### If we can use the fastpath, we return required info to the caller.
if use_fastpath:
xla_executable, _, result_handlers = execute.args
sticky_device = None
avals = []
lazy_exprs = []
for result_handler in result_handlers:
aval, sticky_device, lazy_expr = result_handler.args
avals.append(aval)
lazy_exprs.append(None if xla.lazy.is_trivial(lazy_expr) else lazy_expr)
assert len(avals) == len(out_flat)
fastpath_data = (
xla_executable,
out_pytree_def,
sticky_device,
avals,
lazy_exprs,
)
else:
fastpath_data = None
return out, fastpath_data
def get_device_info():
"""Backends do not exist before __main__ is being executed."""
committed_to_device = device is not None or backend is not None
if device is not None:
default_device = device
else:
backend_ = xb.get_backend(backend)
default_device = backend_.get_default_device_assignment(1)[0]
return _BackendAndDeviceInfo(default_device, committed_to_device)
def get_jax_enable_x64():
"""Returns the value of the flag after GoogleInit.
We must wait until flags have been parsed (in particular for top-level
functions decorated with jax.jit), so we delay inspecting the value
of the jax_enable_x64 flag until JIT time.
"""
return config.x64_enabled
def get_jax_disable_jit_flag():
"""Returns the value of the `jax_disable_jit` flag.
Both a flag and the `disable_jit` context manager can disable jit. We access
the flag only once, when jitting the function, and the context manager
modifies a C++ thread-local value.
"""
return config.read("jax_disable_jit")
static_argnums_ = (0,) + tuple(i + 1 for i in static_argnums)
cpp_jitted_f = jax_jit.jit(
fun,
cache_miss,
get_device_info,
get_jax_enable_x64,
get_jax_disable_jit_flag,
static_argnums_,
)
# TODO(mattjj): make cpp callable follow descriptor protocol for bound methods
@wraps(fun)
@api_boundary
def f_jitted(*args, **kwargs):
context = (
getattr(core.thread_local_state.trace_state.trace_stack, "dynamic", None),
config.x64_enabled,
)
# TODO(jblespiau): Move this to C++.
if (FLAGS.jax_debug_nans or FLAGS.jax_debug_infs) and not _jit_is_disabled():
device_arrays = cpp_jitted_f(context, *args, **kwargs)
try:
xla.check_special(
xla.xla_call_p,
[
da.device_buffer
for da in tree_leaves(device_arrays)
if hasattr(da, "device_buffer")
],
)
return device_arrays
except FloatingPointError:
assert (
FLAGS.jax_debug_nans or FLAGS.jax_debug_infs
) # compiled_fun can only raise in this case
print(
"Invalid nan value encountered in the output of a C++-jit "
"function. Calling the de-optimized version."
)
return cache_miss(context, *args, **kwargs)[0] # probably won't return
elif _jit_is_disabled():
return cpp_jitted_f(*args, **kwargs)
else:
return cpp_jitted_f(context, *args, **kwargs)
f_jitted._cpp_jitted_f = cpp_jitted_f
return f_jitted
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def get_jax_enable_x64():
"""Returns the value of the flag after GoogleInit.
We must wait until flags have been parsed (in particular for top-level
functions decorated with jax.jit), so we delay inspecting the value
of the jax_enable_x64 flag until JIT time.
"""
# TODO(jblespiau): Delete when jaxlib 0.1.62 is the minimal version.
if lib._xla_extension_version >= 4:
return config.read("jax_enable_x64")
else:
return config.x64_enabled
|
def get_jax_enable_x64():
"""Returns the value of the flag after GoogleInit.
We must wait until flags have been parsed (in particular for top-level
functions decorated with jax.jit), so we delay inspecting the value
of the jax_enable_x64 flag until JIT time.
"""
return config.x64_enabled
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def f_jitted(*args, **kwargs):
# TODO(jblespiau): We can remove `config.x64_enabled` when jaxlib has
# extension version 4
context = (
getattr(core.thread_local_state.trace_state.trace_stack, "dynamic", None),
config.x64_enabled,
)
# TODO(jblespiau): Move this to C++.
if (FLAGS.jax_debug_nans or FLAGS.jax_debug_infs) and not _jit_is_disabled():
device_arrays = cpp_jitted_f(context, *args, **kwargs)
try:
xla.check_special(
xla.xla_call_p,
[
da.device_buffer
for da in tree_leaves(device_arrays)
if hasattr(da, "device_buffer")
],
)
return device_arrays
except FloatingPointError:
assert (
FLAGS.jax_debug_nans or FLAGS.jax_debug_infs
) # compiled_fun can only raise in this case
print(
"Invalid nan value encountered in the output of a C++-jit "
"function. Calling the de-optimized version."
)
return cache_miss(context, *args, **kwargs)[0] # probably won't return
elif _jit_is_disabled():
return cpp_jitted_f(*args, **kwargs)
else:
return cpp_jitted_f(context, *args, **kwargs)
|
def f_jitted(*args, **kwargs):
context = (
getattr(core.thread_local_state.trace_state.trace_stack, "dynamic", None),
config.x64_enabled,
)
# TODO(jblespiau): Move this to C++.
if (FLAGS.jax_debug_nans or FLAGS.jax_debug_infs) and not _jit_is_disabled():
device_arrays = cpp_jitted_f(context, *args, **kwargs)
try:
xla.check_special(
xla.xla_call_p,
[
da.device_buffer
for da in tree_leaves(device_arrays)
if hasattr(da, "device_buffer")
],
)
return device_arrays
except FloatingPointError:
assert (
FLAGS.jax_debug_nans or FLAGS.jax_debug_infs
) # compiled_fun can only raise in this case
print(
"Invalid nan value encountered in the output of a C++-jit "
"function. Calling the de-optimized version."
)
return cache_miss(context, *args, **kwargs)[0] # probably won't return
elif _jit_is_disabled():
return cpp_jitted_f(*args, **kwargs)
else:
return cpp_jitted_f(context, *args, **kwargs)
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def x64_enabled(self):
if lib._xla_extension_version >= 4:
if lib.jax_jit.get_enable_x64() is None:
lib.jax_jit.set_enable_x64(bool(self.read("jax_enable_x64")))
return lib.jax_jit.get_enable_x64()
else:
# TODO(jakevdp): Remove when minimum jaxlib is has extension version 4
if self._thread_local_state.enable_x64 is None:
self._thread_local_state.enable_x64 = bool(self.read("jax_enable_x64"))
return self._thread_local_state.enable_x64
|
def x64_enabled(self):
if self._thread_local_state.enable_x64 is None:
self._thread_local_state.enable_x64 = bool(self.read("jax_enable_x64"))
return self._thread_local_state.enable_x64
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def _set_x64_enabled(self, state):
if lib._xla_extension_version >= 4:
lib.jax_jit.set_enable_x64(bool(state))
else:
# TODO(jakevdp): Remove when minimum jaxlib is has extension version 4
self._thread_local_state.enable_x64 = bool(state)
|
def _set_x64_enabled(self, state):
self._thread_local_state.enable_x64 = bool(state)
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def cache(max_size=4096):
def wrap(f):
@functools.lru_cache(max_size)
def cached(_, *args, **kwargs):
return f(*args, **kwargs)
@functools.wraps(f)
def wrapper(*args, **kwargs):
if jax.core.debug_state.check_leaks:
return f(*args, **kwargs)
else:
return cached(bool(config.x64_enabled), *args, **kwargs)
wrapper.cache_clear = cached.cache_clear
wrapper.cache_info = cached.cache_info
return wrapper
return wrap
|
def cache(max_size=4096):
def wrap(f):
@functools.lru_cache(max_size)
def cached(_, *args, **kwargs):
return f(*args, **kwargs)
@functools.wraps(f)
def wrapper(*args, **kwargs):
if jax.core.debug_state.check_leaks:
return f(*args, **kwargs)
else:
return cached(bool(FLAGS.jax_enable_x64), *args, **kwargs)
wrapper.cache_clear = cached.cache_clear
wrapper.cache_info = cached.cache_info
return wrapper
return wrap
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def wrap(f):
@functools.lru_cache(max_size)
def cached(_, *args, **kwargs):
return f(*args, **kwargs)
@functools.wraps(f)
def wrapper(*args, **kwargs):
if jax.core.debug_state.check_leaks:
return f(*args, **kwargs)
else:
return cached(bool(config.x64_enabled), *args, **kwargs)
wrapper.cache_clear = cached.cache_clear
wrapper.cache_info = cached.cache_info
return wrapper
|
def wrap(f):
@functools.lru_cache(max_size)
def cached(_, *args, **kwargs):
return f(*args, **kwargs)
@functools.wraps(f)
def wrapper(*args, **kwargs):
if jax.core.debug_state.check_leaks:
return f(*args, **kwargs)
else:
return cached(bool(FLAGS.jax_enable_x64), *args, **kwargs)
wrapper.cache_clear = cached.cache_clear
wrapper.cache_info = cached.cache_info
return wrapper
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def wrapper(*args, **kwargs):
if jax.core.debug_state.check_leaks:
return f(*args, **kwargs)
else:
return cached(bool(config.x64_enabled), *args, **kwargs)
|
def wrapper(*args, **kwargs):
if jax.core.debug_state.check_leaks:
return f(*args, **kwargs)
else:
return cached(bool(FLAGS.jax_enable_x64), *args, **kwargs)
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def memoize(f):
@functools.lru_cache(None)
def memoized(_, *args, **kwargs):
return f(*args, **kwargs)
@functools.wraps(f)
def wrapper(*args, **kwargs):
return memoized(bool(config.x64_enabled), *args, **kwargs)
wrapper.cache_clear = memoized.cache_clear
wrapper.cache_info = memoized.cache_info
return wrapper
|
def memoize(f):
@functools.lru_cache(None)
def memoized(_, *args, **kwargs):
return f(*args, **kwargs)
@functools.wraps(f)
def wrapper(*args, **kwargs):
return memoized(bool(FLAGS.jax_enable_x64), *args, **kwargs)
wrapper.cache_clear = memoized.cache_clear
wrapper.cache_info = memoized.cache_info
return wrapper
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def wrapper(*args, **kwargs):
return memoized(bool(config.x64_enabled), *args, **kwargs)
|
def wrapper(*args, **kwargs):
return memoized(bool(FLAGS.jax_enable_x64), *args, **kwargs)
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def _cpp_jit(
fun: F,
static_argnums: Union[int, Iterable[int]] = (),
device: Optional[xc.Device] = None,
backend: Optional[str] = None,
donate_argnums: Union[int, Iterable[int]] = (),
) -> F:
"""An implementation of `jit` that tries to do as much as possible in C++.
The goal of this function is to speed up the time it takes to process the
arguments, find the correct C++ executable, start the transfer of arguments
and schedule the computation.
As long as it does not support all features of the Python implementation
the C++ code will fallback to `_python_jit` when it faces some unsupported
feature.
"""
_check_callable(fun)
static_argnums = _ensure_index_tuple(static_argnums)
donate_argnums = _ensure_index_tuple(donate_argnums)
donate_argnums = rebase_donate_argnums(donate_argnums, static_argnums)
if device is not None and backend is not None:
raise ValueError(
"can't specify both a device and a backend for jit, "
f"got device={device} and backend={backend}."
)
def cache_miss(_, *args, **kwargs):
### This first part is basically the same code as in _python_jit.
# An alternative would be for cache_miss to accept from C++ the arguments
# (dyn_args, donated_invars, args_flat, in_tree), since otherwise we have
# work/code that is redundant between C++ and Python. We can try that later.
if max(static_argnums + donate_argnums, default=-1) >= len(args):
msg = (
"jitted function has static_argnums={}, donate_argnums={} but "
"was called with only {} positional arguments."
)
raise ValueError(msg.format(static_argnums, donate_argnums, len(args)))
f = lu.wrap_init(fun)
if static_argnums:
f, dyn_args = argnums_partial_except(f, static_argnums, args)
else:
dyn_args = args
args_flat, in_tree = tree_flatten((dyn_args, kwargs))
if donate_argnums:
donated_invars = donation_vector(donate_argnums, dyn_args, kwargs)
else:
donated_invars = (False,) * len(args_flat)
for arg in args_flat:
_check_arg(arg)
flat_fun, out_tree = flatten_fun(f, in_tree)
out_flat = xla.xla_call(
flat_fun,
*args_flat,
device=device,
backend=backend,
name=flat_fun.__name__,
donated_invars=donated_invars,
)
out_pytree_def = out_tree()
out = tree_unflatten(out_pytree_def, out_flat)
### Decide whether we can support the C++ fast path
# High level note: The Python tracing mechanism is complex; in particular
# to know whether `jax.jit(f)(x)` will execute or trace, it's not enough to
# inspect the argument x, we actually do need to execute it and look at the
# outputs that could be tracers (if f is capturing `Tracer` by closure).
execute: Optional[functools.partial] = xla._xla_callable.most_recent_entry()
use_fastpath = (
# This is if we have already executed this code-path (most-recent entry
# has been reset to None). Thus, we do not support the fast-path.
execute is not None
and execute.func is xla._execute_compiled # not trivial, not pmap
and
# Not supported: ShardedDeviceArray, DeviceConstant.
all(xla.type_is_device_array(x) for x in out_flat)
and
# TODO(mattjj): Add support for lazy-expression.
# If the input is a DeviceArray, then it should have a trivial LazyExpr.
all(
type(x) is not xla.DeviceArray or xla.lazy.is_trivial(x._lazy_expr)
for x in args_flat
)
)
### If we can use the fastpath, we return required info to the caller.
if use_fastpath:
xla_executable, _, result_handlers = execute.args
sticky_device = None
avals = []
lazy_exprs = []
for result_handler in result_handlers:
aval, sticky_device, lazy_expr = result_handler.args
avals.append(aval)
lazy_exprs.append(None if xla.lazy.is_trivial(lazy_expr) else lazy_expr)
assert len(avals) == len(out_flat)
if version >= (0, 1, 58):
fastpath_data = (
xla_executable,
out_pytree_def,
sticky_device,
avals,
lazy_exprs,
)
else:
fastpath_data = (xla_executable, result_handlers, out_pytree_def)
else:
fastpath_data = None
return out, fastpath_data
def get_device_info():
"""Backends do not exist before __main__ is being executed."""
committed_to_device = device is not None or backend is not None
if device is not None:
default_device = device
else:
backend_ = xb.get_backend(backend)
default_device = backend_.get_default_device_assignment(1)[0]
return _BackendAndDeviceInfo(default_device, committed_to_device)
def get_jax_enable_x64():
"""Returns the value of the flag after GoogleInit.
We must wait until flags have been parsed (in particular for top-level
functions decorated with jax.jit), so we delay inspecting the value
of the jax_enable_x64 flag until JIT time.
"""
return config.x64_enabled
def get_jax_disable_jit_flag():
"""Returns the value of the `jax_disable_jit` flag.
Both a flag and the `disable_jit` context manager can disable jit. We access
the flag only once, when jitting the function, and the context manager
modifies a C++ thread-local value.
"""
return config.read("jax_disable_jit")
static_argnums_ = (0,) + tuple(i + 1 for i in static_argnums)
cpp_jitted_f = jax_jit.jit(
fun,
cache_miss,
get_device_info,
get_jax_enable_x64,
get_jax_disable_jit_flag,
static_argnums_,
)
# TODO(mattjj): make cpp callable follow descriptor protocol for bound methods
@wraps(fun)
@api_boundary
def f_jitted(*args, **kwargs):
context = (
getattr(core.thread_local_state.trace_state.trace_stack, "dynamic", None),
config.x64_enabled,
)
# TODO(jblespiau): Move this to C++.
if (FLAGS.jax_debug_nans or FLAGS.jax_debug_infs) and not _jit_is_disabled():
device_arrays = cpp_jitted_f(context, *args, **kwargs)
try:
xla.check_special(
xla.xla_call_p,
[
da.device_buffer
for da in tree_leaves(device_arrays)
if hasattr(da, "device_buffer")
],
)
return device_arrays
except FloatingPointError:
assert (
FLAGS.jax_debug_nans or FLAGS.jax_debug_infs
) # compiled_fun can only raise in this case
print(
"Invalid nan value encountered in the output of a C++-jit "
"function. Calling the de-optimized version."
)
return cache_miss(context, *args, **kwargs)[0] # probably won't return
elif _jit_is_disabled():
return cpp_jitted_f(*args, **kwargs)
else:
return cpp_jitted_f(context, *args, **kwargs)
f_jitted._cpp_jitted_f = cpp_jitted_f
return f_jitted
|
def _cpp_jit(
fun: F,
static_argnums: Union[int, Iterable[int]] = (),
device: Optional[xc.Device] = None,
backend: Optional[str] = None,
donate_argnums: Union[int, Iterable[int]] = (),
) -> F:
"""An implementation of `jit` that tries to do as much as possible in C++.
The goal of this function is to speed up the time it takes to process the
arguments, find the correct C++ executable, start the transfer of arguments
and schedule the computation.
As long as it does not support all features of the Python implementation
the C++ code will fallback to `_python_jit` when it faces some unsupported
feature.
"""
_check_callable(fun)
static_argnums = _ensure_index_tuple(static_argnums)
donate_argnums = _ensure_index_tuple(donate_argnums)
donate_argnums = rebase_donate_argnums(donate_argnums, static_argnums)
if device is not None and backend is not None:
raise ValueError(
"can't specify both a device and a backend for jit, "
f"got device={device} and backend={backend}."
)
def cache_miss(_, *args, **kwargs):
### This first part is basically the same code as in _python_jit.
# An alternative would be for cache_miss to accept from C++ the arguments
# (dyn_args, donated_invars, args_flat, in_tree), since otherwise we have
# work/code that is redundant between C++ and Python. We can try that later.
if max(static_argnums + donate_argnums, default=-1) >= len(args):
msg = (
"jitted function has static_argnums={}, donate_argnums={} but "
"was called with only {} positional arguments."
)
raise ValueError(msg.format(static_argnums, donate_argnums, len(args)))
f = lu.wrap_init(fun)
if static_argnums:
f, dyn_args = argnums_partial_except(f, static_argnums, args)
else:
dyn_args = args
args_flat, in_tree = tree_flatten((dyn_args, kwargs))
if donate_argnums:
donated_invars = donation_vector(donate_argnums, dyn_args, kwargs)
else:
donated_invars = (False,) * len(args_flat)
for arg in args_flat:
_check_arg(arg)
flat_fun, out_tree = flatten_fun(f, in_tree)
out_flat = xla.xla_call(
flat_fun,
*args_flat,
device=device,
backend=backend,
name=flat_fun.__name__,
donated_invars=donated_invars,
)
out_pytree_def = out_tree()
out = tree_unflatten(out_pytree_def, out_flat)
### Decide whether we can support the C++ fast path
# High level note: The Python tracing mechanism is complex; in particular
# to know whether `jax.jit(f)(x)` will execute or trace, it's not enough to
# inspect the argument x, we actually do need to execute it and look at the
# outputs that could be tracers (if f is capturing `Tracer` by closure).
execute: Optional[functools.partial] = xla._xla_callable.most_recent_entry()
use_fastpath = (
# This is if we have already executed this code-path (most-recent entry
# has been reset to None). Thus, we do not support the fast-path.
execute is not None
and execute.func is xla._execute_compiled # not trivial, not pmap
and
# Not supported: ShardedDeviceArray, DeviceConstant.
all(xla.type_is_device_array(x) for x in out_flat)
and
# TODO(mattjj): Add support for lazy-expression.
# If the input is a DeviceArray, then it should have a trivial LazyExpr.
all(
type(x) is not xla.DeviceArray or xla.lazy.is_trivial(x._lazy_expr)
for x in args_flat
)
)
### If we can use the fastpath, we return required info to the caller.
if use_fastpath:
xla_executable, _, result_handlers = execute.args
sticky_device = None
avals = []
lazy_exprs = []
for result_handler in result_handlers:
aval, sticky_device, lazy_expr = result_handler.args
avals.append(aval)
lazy_exprs.append(None if xla.lazy.is_trivial(lazy_expr) else lazy_expr)
assert len(avals) == len(out_flat)
if version >= (0, 1, 58):
fastpath_data = (
xla_executable,
out_pytree_def,
sticky_device,
avals,
lazy_exprs,
)
else:
fastpath_data = (xla_executable, result_handlers, out_pytree_def)
else:
fastpath_data = None
return out, fastpath_data
def get_device_info():
"""Backends do not exist before __main__ is being executed."""
committed_to_device = device is not None or backend is not None
if device is not None:
default_device = device
else:
backend_ = xb.get_backend(backend)
default_device = backend_.get_default_device_assignment(1)[0]
return _BackendAndDeviceInfo(default_device, committed_to_device)
def get_jax_enable_x64():
"""Returns the value of the flag after GoogleInit.
We must wait until flags have been parsed (in particular for top-level
functions decorated with jax.jit), so we delay inspecting the value
of the jax_enable_x64 flag until JIT time.
"""
return FLAGS.jax_enable_x64
def get_jax_disable_jit_flag():
"""Returns the value of the `jax_disable_jit` flag.
Both a flag and the `disable_jit` context manager can disable jit. We access
the flag only once, when jitting the function, and the context manager
modifies a C++ thread-local value.
"""
return config.read("jax_disable_jit")
static_argnums_ = (0,) + tuple(i + 1 for i in static_argnums)
cpp_jitted_f = jax_jit.jit(
fun,
cache_miss,
get_device_info,
get_jax_enable_x64,
get_jax_disable_jit_flag,
static_argnums_,
)
# TODO(mattjj): make cpp callable follow descriptor protocol for bound methods
@wraps(fun)
@api_boundary
def f_jitted(*args, **kwargs):
context = (
getattr(core.thread_local_state.trace_state.trace_stack, "dynamic", None),
bool(FLAGS.jax_enable_x64),
)
# TODO(jblespiau): Move this to C++.
if (FLAGS.jax_debug_nans or FLAGS.jax_debug_infs) and not _jit_is_disabled():
device_arrays = cpp_jitted_f(context, *args, **kwargs)
try:
xla.check_special(
xla.xla_call_p,
[
da.device_buffer
for da in tree_leaves(device_arrays)
if hasattr(da, "device_buffer")
],
)
return device_arrays
except FloatingPointError:
assert (
FLAGS.jax_debug_nans or FLAGS.jax_debug_infs
) # compiled_fun can only raise in this case
print(
"Invalid nan value encountered in the output of a C++-jit "
"function. Calling the de-optimized version."
)
return cache_miss(context, *args, **kwargs)[0] # probably won't return
elif _jit_is_disabled():
return cpp_jitted_f(*args, **kwargs)
else:
return cpp_jitted_f(context, *args, **kwargs)
f_jitted._cpp_jitted_f = cpp_jitted_f
return f_jitted
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def get_jax_enable_x64():
"""Returns the value of the flag after GoogleInit.
We must wait until flags have been parsed (in particular for top-level
functions decorated with jax.jit), so we delay inspecting the value
of the jax_enable_x64 flag until JIT time.
"""
return config.x64_enabled
|
def get_jax_enable_x64():
"""Returns the value of the flag after GoogleInit.
We must wait until flags have been parsed (in particular for top-level
functions decorated with jax.jit), so we delay inspecting the value
of the jax_enable_x64 flag until JIT time.
"""
return FLAGS.jax_enable_x64
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def f_jitted(*args, **kwargs):
context = (
getattr(core.thread_local_state.trace_state.trace_stack, "dynamic", None),
config.x64_enabled,
)
# TODO(jblespiau): Move this to C++.
if (FLAGS.jax_debug_nans or FLAGS.jax_debug_infs) and not _jit_is_disabled():
device_arrays = cpp_jitted_f(context, *args, **kwargs)
try:
xla.check_special(
xla.xla_call_p,
[
da.device_buffer
for da in tree_leaves(device_arrays)
if hasattr(da, "device_buffer")
],
)
return device_arrays
except FloatingPointError:
assert (
FLAGS.jax_debug_nans or FLAGS.jax_debug_infs
) # compiled_fun can only raise in this case
print(
"Invalid nan value encountered in the output of a C++-jit "
"function. Calling the de-optimized version."
)
return cache_miss(context, *args, **kwargs)[0] # probably won't return
elif _jit_is_disabled():
return cpp_jitted_f(*args, **kwargs)
else:
return cpp_jitted_f(context, *args, **kwargs)
|
def f_jitted(*args, **kwargs):
context = (
getattr(core.thread_local_state.trace_state.trace_stack, "dynamic", None),
bool(FLAGS.jax_enable_x64),
)
# TODO(jblespiau): Move this to C++.
if (FLAGS.jax_debug_nans or FLAGS.jax_debug_infs) and not _jit_is_disabled():
device_arrays = cpp_jitted_f(context, *args, **kwargs)
try:
xla.check_special(
xla.xla_call_p,
[
da.device_buffer
for da in tree_leaves(device_arrays)
if hasattr(da, "device_buffer")
],
)
return device_arrays
except FloatingPointError:
assert (
FLAGS.jax_debug_nans or FLAGS.jax_debug_infs
) # compiled_fun can only raise in this case
print(
"Invalid nan value encountered in the output of a C++-jit "
"function. Calling the de-optimized version."
)
return cache_miss(context, *args, **kwargs)[0] # probably won't return
elif _jit_is_disabled():
return cpp_jitted_f(*args, **kwargs)
else:
return cpp_jitted_f(context, *args, **kwargs)
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def canonicalize_dtype(dtype):
"""Convert from a dtype to a canonical dtype based on config.x64_enabled."""
if isinstance(dtype, str) and dtype == "bfloat16":
dtype = bfloat16
try:
dtype = np.dtype(dtype)
except TypeError as e:
raise TypeError(f"dtype {dtype!r} not understood") from e
if config.x64_enabled:
return dtype
else:
return _dtype_to_32bit_dtype.get(dtype, dtype)
|
def canonicalize_dtype(dtype):
"""Convert from a dtype to a canonical dtype based on FLAGS.jax_enable_x64."""
if isinstance(dtype, str) and dtype == "bfloat16":
dtype = bfloat16
try:
dtype = np.dtype(dtype)
except TypeError as e:
raise TypeError(f"dtype {dtype!r} not understood") from e
if FLAGS.jax_enable_x64:
return dtype
else:
return _dtype_to_32bit_dtype.get(dtype, dtype)
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def enable_x64():
"""Experimental context manager to temporarily enable X64 mode.
Usage::
>>> import jax.numpy as jnp
>>> with enable_x64():
... print(jnp.arange(10.0).dtype)
...
float64
See Also
--------
jax.experimental.disable_x64 : temporarily disable X64 mode.
"""
_x64_state = config.x64_enabled
config._set_x64_enabled(True)
try:
yield
finally:
config._set_x64_enabled(_x64_state)
|
def enable_x64():
"""Experimental context manager to temporarily enable X64 mode.
Usage::
>>> import jax.numpy as jnp
>>> with enable_x64():
... print(jnp.arange(10.0).dtype)
...
float64
See Also
--------
jax.experimental.disable_x64 : temporarily disable X64 mode.
"""
_x64_state = config.FLAGS.jax_enable_x64
config.update("jax_enable_x64", True)
try:
yield
finally:
config.update("jax_enable_x64", _x64_state)
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def disable_x64():
"""Experimental context manager to temporarily disable X64 mode.
Usage::
>>> import jax.numpy as jnp
>>> with disable_x64():
... print(jnp.arange(10.0).dtype)
...
float32
See Also
--------
jax.experimental.enable_x64 : temporarily enable X64 mode.
"""
_x64_state = config.x64_enabled
config._set_x64_enabled(False)
try:
yield
finally:
config._set_x64_enabled(_x64_state)
|
def disable_x64():
"""Experimental context manager to temporarily disable X64 mode.
Usage::
>>> import jax.numpy as jnp
>>> with disable_x64():
... print(jnp.arange(10.0).dtype)
...
float32
See Also
--------
jax.experimental.enable_x64 : temporarily enable X64 mode.
"""
_x64_state = config.FLAGS.jax_enable_x64
config.update("jax_enable_x64", False)
try:
yield
finally:
config.update("jax_enable_x64", _x64_state)
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def dtype_to_etype(dtype):
"""Convert from dtype to canonical etype (reading config.x64_enabled)."""
return xla_client.dtype_to_etype(dtypes.canonicalize_dtype(dtype))
|
def dtype_to_etype(dtype):
"""Convert from dtype to canonical etype (reading FLAGS.jax_enable_x64)."""
return xla_client.dtype_to_etype(dtypes.canonicalize_dtype(dtype))
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def cache(call: Callable):
"""Memoization decorator for functions taking a WrappedFun as first argument.
Args:
call: a Python callable that takes a WrappedFun as its first argument. The
underlying transforms and params on the WrappedFun are used as part of the
memoization cache key.
Returns:
A memoized version of ``call``.
"""
fun_caches: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
thread_local: threading.local = _CacheLocalContext()
def memoized_fun(fun: WrappedFun, *args):
cache = fun_caches.setdefault(fun.f, {})
if core.debug_state.check_leaks:
key = (
_copy_main_traces(fun.transforms),
fun.params,
args,
config.x64_enabled,
)
else:
key = (fun.transforms, fun.params, args, config.x64_enabled)
result = cache.get(key, None)
if result is not None:
ans, stores = result
fun.populate_stores(stores)
else:
ans = call(fun, *args)
cache[key] = (ans, fun.stores)
thread_local.most_recent_entry = weakref.ref(ans)
return ans
def _most_recent_entry():
most_recent_entry = thread_local.most_recent_entry
if most_recent_entry is not None:
result = most_recent_entry()
thread_local.most_recent_entry = None
return result
memoized_fun.most_recent_entry = _most_recent_entry # type: ignore
memoized_fun.cache_clear = fun_caches.clear # type: ignore
return memoized_fun
|
def cache(call: Callable):
"""Memoization decorator for functions taking a WrappedFun as first argument.
Args:
call: a Python callable that takes a WrappedFun as its first argument. The
underlying transforms and params on the WrappedFun are used as part of the
memoization cache key.
Returns:
A memoized version of ``call``.
"""
fun_caches: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
thread_local: threading.local = _CacheLocalContext()
def memoized_fun(fun: WrappedFun, *args):
cache = fun_caches.setdefault(fun.f, {})
if core.debug_state.check_leaks:
key = (
_copy_main_traces(fun.transforms),
fun.params,
args,
bool(FLAGS.jax_enable_x64),
)
else:
key = (fun.transforms, fun.params, args, bool(FLAGS.jax_enable_x64))
result = cache.get(key, None)
if result is not None:
ans, stores = result
fun.populate_stores(stores)
else:
ans = call(fun, *args)
cache[key] = (ans, fun.stores)
thread_local.most_recent_entry = weakref.ref(ans)
return ans
def _most_recent_entry():
most_recent_entry = thread_local.most_recent_entry
if most_recent_entry is not None:
result = most_recent_entry()
thread_local.most_recent_entry = None
return result
memoized_fun.most_recent_entry = _most_recent_entry # type: ignore
memoized_fun.cache_clear = fun_caches.clear # type: ignore
return memoized_fun
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def memoized_fun(fun: WrappedFun, *args):
cache = fun_caches.setdefault(fun.f, {})
if core.debug_state.check_leaks:
key = (_copy_main_traces(fun.transforms), fun.params, args, config.x64_enabled)
else:
key = (fun.transforms, fun.params, args, config.x64_enabled)
result = cache.get(key, None)
if result is not None:
ans, stores = result
fun.populate_stores(stores)
else:
ans = call(fun, *args)
cache[key] = (ans, fun.stores)
thread_local.most_recent_entry = weakref.ref(ans)
return ans
|
def memoized_fun(fun: WrappedFun, *args):
cache = fun_caches.setdefault(fun.f, {})
if core.debug_state.check_leaks:
key = (
_copy_main_traces(fun.transforms),
fun.params,
args,
bool(FLAGS.jax_enable_x64),
)
else:
key = (fun.transforms, fun.params, args, bool(FLAGS.jax_enable_x64))
result = cache.get(key, None)
if result is not None:
ans, stores = result
fun.populate_stores(stores)
else:
ans = call(fun, *args)
cache[key] = (ans, fun.stores)
thread_local.most_recent_entry = weakref.ref(ans)
return ans
|
https://github.com/google/jax/issues/5532
|
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
jax._src.traceback_util.FilteredStackTrace: RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tmp.py", line 11, in <module>
f() # <--- fails
File "tmp.py", line 4, in <lambda>
f = lambda: random.uniform(random.PRNGKey(0), (10,), 'float64', -1, 1)
File "/Users/vanderplas/github/google/jax/jax/_src/random.py", line 365, in uniform
return _uniform(key, shape, dtype, minval, maxval) # type: ignore
File "/Users/vanderplas/github/google/jax/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/vanderplas/github/google/jax/jax/api.py", line 401, in f_jitted
return cpp_jitted_f(context, *args, **kwargs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 1: want s64[], got s32[]: while running replica 0 and partition 0 of a replicated computation (other replicas may have failed as well).
|
RuntimeError
|
def minimize(
fun: Callable,
x0: jnp.ndarray,
args: Tuple = (),
*,
method: str,
tol: Optional[float] = None,
options: Optional[Mapping[str, Any]] = None,
) -> OptimizeResults:
"""Minimization of scalar function of one or more variables.
This API for this function matches SciPy with some minor deviations:
- Gradients of ``fun`` are calculated automatically using JAX's autodiff
support when required.
- The ``method`` argument is required. You must specify a solver.
- Various optional arguments in the SciPy interface have not yet been
implemented.
- Optimization results may differ from SciPy due to differences in the line
search implementation.
``minimize`` supports ``jit`` compilation. It does not yet support
differentiation or arguments in the form of multi-dimensional arrays, but
support for both is planned.
Args:
fun: the objective function to be minimized, ``fun(x, *args) -> float``,
where ``x`` is an 1-D array with shape ``(n,)`` and ``args`` is a tuple
of the fixed parameters needed to completely specify the function.
``fun`` must support differentiation.
x0: initial guess. Array of real elements of size ``(n,)``, where 'n' is
the number of independent variables.
args: extra arguments passed to the objective function.
method: solver type. Currently only "BFGS" is supported.
tol: tolerance for termination. For detailed control, use solver-specific
options.
options: a dictionary of solver options. All methods accept the following
generic options:
maxiter : int
Maximum number of iterations to perform. Depending on the
method each iteration may use several function evaluations.
Returns: OptimizeResults object.
"""
if options is None:
options = {}
if not isinstance(args, tuple):
msg = "args argument to jax.scipy.optimize.minimize must be a tuple, got {}"
raise TypeError(msg.format(args))
fun_with_args = lambda x: fun(x, *args)
if method.lower() == "bfgs":
results = minimize_bfgs(fun_with_args, x0, **options)
message = (
"status meaning: 0=converged, 1=max BFGS iters reached, "
"3=zoom failed, 4=saddle point reached, "
"5=max line search iters reached, -1=undefined"
)
success = (results.converged) & jnp.logical_not(results.failed)
return OptimizeResults(
x=results.x_k,
success=success,
status=results.status,
message=message,
fun=results.f_k,
jac=results.g_k,
hess_inv=results.H_k,
nfev=results.nfev,
njev=results.ngev,
nit=results.k,
)
raise ValueError("Method {} not recognized".format(method))
|
def minimize(
fun: Callable,
x0: jnp.ndarray,
args: Tuple = (),
*,
method: str,
tol: Optional[float] = None,
options: Optional[Mapping[str, Any]] = None,
) -> OptimizeResults:
"""Minimization of scalar function of one or more variables.
This API for this function matches SciPy with some minor deviations:
- Gradients of ``fun`` are calculated automatically using JAX's autodiff
support when required.
- The ``method`` argument is required. You must specify a solver.
- Various optional arguments in the SciPy interface have not yet been
implemented.
- Optimization results may differ from SciPy due to differences in the line
search implementation.
``minimize`` supports ``jit`` compilation. It does not yet support
differentiation or arguments in the form of multi-dimensional arrays, but
support for both is planned.
Args:
fun: the objective function to be minimized, ``fun(x, *args) -> float``,
where ``x`` is an 1-D array with shape ``(n,)`` and ``args`` is a tuple
of the fixed parameters needed to completely specify the function.
``fun`` must support differentiation.
x0: initial guess. Array of real elements of size ``(n,)``, where 'n' is
the number of independent variables.
args: extra arguments passed to the objective function.
method: solver type. Currently only "BFGS" is supported.
tol: tolerance for termination. For detailed control, use solver-specific
options.
options: a dictionary of solver options. All methods accept the following
generic options:
maxiter : int
Maximum number of iterations to perform. Depending on the
method each iteration may use several function evaluations.
Returns: OptimizeResults object.
"""
if options is None:
options = {}
fun_with_args = lambda x: fun(x, *args)
if method.lower() == "bfgs":
results = minimize_bfgs(fun_with_args, x0, **options)
message = (
"status meaning: 0=converged, 1=max BFGS iters reached, "
"3=zoom failed, 4=saddle point reached, "
"5=max line search iters reached, -1=undefined"
)
success = (results.converged) & jnp.logical_not(results.failed)
return OptimizeResults(
x=results.x_k,
success=success,
status=results.status,
message=message,
fun=results.f_k,
jac=results.g_k,
hess_inv=results.H_k,
nfev=results.nfev,
njev=results.ngev,
nit=results.k,
)
raise ValueError("Method {} not recognized".format(method))
|
https://github.com/google/jax/issues/5732
|
WARNING:absl:No GPU/TPU found, falling back to CPU. (Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.)
testing nll = [5.0628967 5.4723964]
Traceback (most recent call last):
File "test.py", line 37, in <module>
sopt.minimize(NLL, jnp.zeros((3, 2)), Y, method="BFGS")
File "/Users/nicholas/opt/miniconda3/lib/python3.8/site-packages/jax/_src/scipy/optimize/minimize.py", line 96, in minimize
results = minimize_bfgs(fun_with_args, x0, **options)
File "/Users/nicholas/opt/miniconda3/lib/python3.8/site-packages/jax/_src/scipy/optimize/bfgs.py", line 99, in minimize_bfgs
f_0, g_0 = jax.value_and_grad(fun)(x0)
File "/Users/nicholas/opt/miniconda3/lib/python3.8/site-packages/jax/_src/scipy/optimize/minimize.py", line 93, in <lambda>
fun_with_args = lambda x: fun(x, *args)
jax._src.traceback_util.FilteredStackTrace: ValueError: vmap in_axes specification must be a tree prefix of the corresponding value, got specification (1, 1) for value tree PyTreeDef(tuple, [*,*,*,*,*,*,*,*,*,*,*]).
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "test.py", line 37, in <module>
sopt.minimize(NLL, jnp.zeros((3, 2)), Y, method="BFGS")
File "/Users/nicholas/opt/miniconda3/lib/python3.8/site-packages/jax/_src/scipy/optimize/minimize.py", line 96, in minimize
results = minimize_bfgs(fun_with_args, x0, **options)
File "/Users/nicholas/opt/miniconda3/lib/python3.8/site-packages/jax/_src/scipy/optimize/bfgs.py", line 99, in minimize_bfgs
f_0, g_0 = jax.value_and_grad(fun)(x0)
File "/Users/nicholas/opt/miniconda3/lib/python3.8/site-packages/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/nicholas/opt/miniconda3/lib/python3.8/site-packages/jax/api.py", line 808, in value_and_grad_f
ans, vjp_py = _vjp(f_partial, *dyn_args)
File "/Users/nicholas/opt/miniconda3/lib/python3.8/site-packages/jax/api.py", line 1914, in _vjp
out_primal, out_vjp = ad.vjp(flat_fun, primals_flat)
File "/Users/nicholas/opt/miniconda3/lib/python3.8/site-packages/jax/interpreters/ad.py", line 114, in vjp
out_primals, pvals, jaxpr, consts = linearize(traceable, *primals)
File "/Users/nicholas/opt/miniconda3/lib/python3.8/site-packages/jax/interpreters/ad.py", line 101, in linearize
jaxpr, out_pvals, consts = pe.trace_to_jaxpr(jvpfun_flat, in_pvals)
File "/Users/nicholas/opt/miniconda3/lib/python3.8/site-packages/jax/interpreters/partial_eval.py", line 506, in trace_to_jaxpr
jaxpr, (out_pvals, consts, env) = fun.call_wrapped(pvals)
File "/Users/nicholas/opt/miniconda3/lib/python3.8/site-packages/jax/linear_util.py", line 166, in call_wrapped
ans = self.f(*args, **dict(self.params, **kwargs))
File "/Users/nicholas/opt/miniconda3/lib/python3.8/site-packages/jax/_src/scipy/optimize/minimize.py", line 93, in <lambda>
fun_with_args = lambda x: fun(x, *args)
File "/Users/nicholas/opt/miniconda3/lib/python3.8/site-packages/jax/_src/traceback_util.py", line 139, in reraise_with_filtered_traceback
return fun(*args, **kwargs)
File "/Users/nicholas/opt/miniconda3/lib/python3.8/site-packages/jax/api.py", line 1220, in batched_fun
in_axes_flat = flatten_axes("vmap in_axes", in_tree, (in_axes, 0), kws=True)
File "/Users/nicholas/opt/miniconda3/lib/python3.8/site-packages/jax/api_util.py", line 188, in flatten_axes
raise ValueError(f"{name} specification must be a tree prefix of the "
ValueError: vmap in_axes specification must be a tree prefix of the corresponding value, got specification (1, 1) for value tree PyTreeDef(tuple, [*,*,*,*,*,*,*,*,*,*,*]).
|
ValueError
|
def eval_shape(fun: Callable, *args, **kwargs):
"""Compute the shape/dtype of ``fun`` without any FLOPs.
This utility function is useful for performing shape inference. Its
input/output behavior is defined by::
def eval_shape(fun, *args, **kwargs):
out = fun(*args, **kwargs)
return jax.tree_util.tree_map(shape_dtype_struct, out)
def shape_dtype_struct(x):
return ShapeDtypeStruct(x.shape, x.dtype)
class ShapeDtypeStruct:
__slots__ = ["shape", "dtype"]
def __init__(self, shape, dtype):
self.shape = shape
self.dtype = dtype
In particular, the output is a pytree of objects that have ``shape`` and
``dtype`` attributes, but nothing else about them is guaranteed by the API.
But instead of applying ``fun`` directly, which might be expensive, it uses
JAX's abstract interpretation machinery to evaluate the shapes without doing
any FLOPs.
Using :py:func:`eval_shape` can also catch shape errors, and will raise same
shape errors as evaluating ``fun(*args, **kwargs)``.
Args:
fun: The function whose output shape should be evaluated.
*args: a positional argument tuple of arrays, scalars, or (nested) standard
Python containers (tuples, lists, dicts, namedtuples, i.e. pytrees) of
those types. Since only the ``shape`` and ``dtype`` attributes are
accessed, only values that duck-type arrays are required, rather than real
ndarrays. The duck-typed objects cannot be namedtuples because those are
treated as standard Python containers. See the example below.
**kwargs: a keyword argument dict of arrays, scalars, or (nested) standard
Python containers (pytrees) of those types. As in ``args``, array values
need only be duck-typed to have ``shape`` and ``dtype`` attributes.
For example:
>>> import jax
>>> import jax.numpy as jnp
>>>
>>> f = lambda A, x: jnp.tanh(jnp.dot(A, x))
>>> class MyArgArray(object):
... def __init__(self, shape, dtype):
... self.shape = shape
... self.dtype = dtype
...
>>> A = MyArgArray((2000, 3000), jnp.float32)
>>> x = MyArgArray((3000, 1000), jnp.float32)
>>> out = jax.eval_shape(f, A, x) # no FLOPs performed
>>> print(out.shape)
(2000, 1000)
>>> print(out.dtype)
float32
"""
def dtype(x):
try:
return dtypes.result_type(x)
except ValueError:
return dtypes.result_type(getattr(x, "dtype"))
def abstractify(x):
return ShapedArray(np.shape(x), dtype(x))
args_flat, in_tree = tree_flatten((args, kwargs))
wrapped_fun, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)
out = pe.abstract_eval_fun(wrapped_fun.call_wrapped, *map(abstractify, args_flat))
out = [ShapeDtypeStruct(x.shape, x.dtype) for x in out]
return tree_unflatten(out_tree(), out)
|
def eval_shape(fun: Callable, *args, **kwargs):
"""Compute the shape/dtype of ``fun`` without any FLOPs.
This utility function is useful for performing shape inference. Its
input/output behavior is defined by::
def eval_shape(fun, *args, **kwargs):
out = fun(*args, **kwargs)
return jax.tree_util.tree_map(shape_dtype_struct, out)
def shape_dtype_struct(x):
return ShapeDtypeStruct(x.shape, x.dtype)
class ShapeDtypeStruct:
__slots__ = ["shape", "dtype"]
def __init__(self, shape, dtype):
self.shape = shape
self.dtype = dtype
In particular, the output is a pytree of objects that have ``shape`` and
``dtype`` attributes, but nothing else about them is guaranteed by the API.
But instead of applying ``fun`` directly, which might be expensive, it uses
JAX's abstract interpretation machinery to evaluate the shapes without doing
any FLOPs.
Using :py:func:`eval_shape` can also catch shape errors, and will raise same
shape errors as evaluating ``fun(*args, **kwargs)``.
Args:
fun: The function whose output shape should be evaluated.
*args: a positional argument tuple of arrays, scalars, or (nested) standard
Python containers (tuples, lists, dicts, namedtuples, i.e. pytrees) of
those types. Since only the ``shape`` and ``dtype`` attributes are
accessed, only values that duck-type arrays are required, rather than real
ndarrays. The duck-typed objects cannot be namedtuples because those are
treated as standard Python containers. See the example below.
**kwargs: a keyword argument dict of arrays, scalars, or (nested) standard
Python containers (pytrees) of those types. As in ``args``, array values
need only be duck-typed to have ``shape`` and ``dtype`` attributes.
For example:
>>> import jax
>>> import jax.numpy as jnp
>>>
>>> f = lambda A, x: jnp.tanh(jnp.dot(A, x))
>>> class MyArgArray(object):
... def __init__(self, shape, dtype):
... self.shape = shape
... self.dtype = dtype
...
>>> A = MyArgArray((2000, 3000), jnp.float32)
>>> x = MyArgArray((3000, 1000), jnp.float32)
>>> out = jax.eval_shape(f, A, x) # no FLOPs performed
>>> print(out.shape)
(2000, 1000)
>>> print(out.dtype)
float32
"""
def abstractify(x):
return ShapedArray(np.shape(x), dtypes.result_type(x))
args_flat, in_tree = tree_flatten((args, kwargs))
wrapped_fun, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)
out = pe.abstract_eval_fun(wrapped_fun.call_wrapped, *map(abstractify, args_flat))
out = [ShapeDtypeStruct(x.shape, x.dtype) for x in out]
return tree_unflatten(out_tree(), out)
|
https://github.com/google/jax/issues/5683
|
import objax
import jax
m = objax.nn.Sequential([objax.nn.Linear(3, 4)])
v = objax.random.uniform(((32, 3)))
jax.eval_shape(m, v) # ShapeDtypeStruct(shape=(32, 4), dtype=float32)
d = objax.util.EasyDict(shape=(32, 3), dtype=v.dtype)
print(repr(d.shape), repr(d.dtype)) # (32, 3) dtype('float32')
print(hasattr(d, 'shape'), hasattr(d, 'dtype')) # True True
jax.eval_shape(m, d)
#
Traceback (most recent call last):
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3417, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-24-d48e201250f2>", line 1, in <module>
jax.eval_shape(m, d)
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/api.py", line 2283, in eval_shape
*map(abstractify, args_flat))
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/util.py", line 36, in safe_map
return list(map(f, *args))
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/api.py", line 2279, in abstractify
return ShapedArray(np.shape(x), dtypes.result_type(x))
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/dtypes.py", line 294, in result_type
return canonicalize_dtype(dtype(args[0]))
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/dtypes.py", line 288, in dtype
return np.result_type(x)
File "<__array_function__ internals>", line 5, in result_type
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/numpy/core/_internal.py", line 64, in _usefields
names, formats, offsets, titles = _makenames_list(adict, align)
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/numpy/core/_internal.py", line 40, in _makenames_list
format = dtype(obj[0], align=align)
TypeError: data type not understood
|
TypeError
|
def abstractify(x):
return ShapedArray(np.shape(x), dtype(x))
|
def abstractify(x):
return ShapedArray(np.shape(x), dtypes.result_type(x))
|
https://github.com/google/jax/issues/5683
|
import objax
import jax
m = objax.nn.Sequential([objax.nn.Linear(3, 4)])
v = objax.random.uniform(((32, 3)))
jax.eval_shape(m, v) # ShapeDtypeStruct(shape=(32, 4), dtype=float32)
d = objax.util.EasyDict(shape=(32, 3), dtype=v.dtype)
print(repr(d.shape), repr(d.dtype)) # (32, 3) dtype('float32')
print(hasattr(d, 'shape'), hasattr(d, 'dtype')) # True True
jax.eval_shape(m, d)
#
Traceback (most recent call last):
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3417, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-24-d48e201250f2>", line 1, in <module>
jax.eval_shape(m, d)
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/api.py", line 2283, in eval_shape
*map(abstractify, args_flat))
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/util.py", line 36, in safe_map
return list(map(f, *args))
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/api.py", line 2279, in abstractify
return ShapedArray(np.shape(x), dtypes.result_type(x))
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/dtypes.py", line 294, in result_type
return canonicalize_dtype(dtype(args[0]))
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/dtypes.py", line 288, in dtype
return np.result_type(x)
File "<__array_function__ internals>", line 5, in result_type
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/numpy/core/_internal.py", line 64, in _usefields
names, formats, offsets, titles = _makenames_list(adict, align)
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/numpy/core/_internal.py", line 40, in _makenames_list
format = dtype(obj[0], align=align)
TypeError: data type not understood
|
TypeError
|
def _result_type_raw(*args):
if len(args) == 1:
return _jax_type(args[0])
return _least_upper_bound(*{_jax_type(arg) for arg in args})
|
def _result_type_raw(*args):
if len(args) < 2:
return _jax_type(args[0])
return _least_upper_bound(*{_jax_type(arg) for arg in args})
|
https://github.com/google/jax/issues/5683
|
import objax
import jax
m = objax.nn.Sequential([objax.nn.Linear(3, 4)])
v = objax.random.uniform(((32, 3)))
jax.eval_shape(m, v) # ShapeDtypeStruct(shape=(32, 4), dtype=float32)
d = objax.util.EasyDict(shape=(32, 3), dtype=v.dtype)
print(repr(d.shape), repr(d.dtype)) # (32, 3) dtype('float32')
print(hasattr(d, 'shape'), hasattr(d, 'dtype')) # True True
jax.eval_shape(m, d)
#
Traceback (most recent call last):
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3417, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-24-d48e201250f2>", line 1, in <module>
jax.eval_shape(m, d)
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/api.py", line 2283, in eval_shape
*map(abstractify, args_flat))
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/util.py", line 36, in safe_map
return list(map(f, *args))
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/api.py", line 2279, in abstractify
return ShapedArray(np.shape(x), dtypes.result_type(x))
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/dtypes.py", line 294, in result_type
return canonicalize_dtype(dtype(args[0]))
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/dtypes.py", line 288, in dtype
return np.result_type(x)
File "<__array_function__ internals>", line 5, in result_type
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/numpy/core/_internal.py", line 64, in _usefields
names, formats, offsets, titles = _makenames_list(adict, align)
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/numpy/core/_internal.py", line 40, in _makenames_list
format = dtype(obj[0], align=align)
TypeError: data type not understood
|
TypeError
|
def result_type(*args):
"""Convenience function to apply Numpy argument dtype promotion."""
if len(args) == 0:
raise ValueError("at least one array or dtype is required")
return canonicalize_dtype(_result_type_raw(*args))
|
def result_type(*args):
"""Convenience function to apply Numpy argument dtype promotion."""
return canonicalize_dtype(_result_type_raw(*args))
|
https://github.com/google/jax/issues/5683
|
import objax
import jax
m = objax.nn.Sequential([objax.nn.Linear(3, 4)])
v = objax.random.uniform(((32, 3)))
jax.eval_shape(m, v) # ShapeDtypeStruct(shape=(32, 4), dtype=float32)
d = objax.util.EasyDict(shape=(32, 3), dtype=v.dtype)
print(repr(d.shape), repr(d.dtype)) # (32, 3) dtype('float32')
print(hasattr(d, 'shape'), hasattr(d, 'dtype')) # True True
jax.eval_shape(m, d)
#
Traceback (most recent call last):
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3417, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-24-d48e201250f2>", line 1, in <module>
jax.eval_shape(m, d)
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/api.py", line 2283, in eval_shape
*map(abstractify, args_flat))
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/util.py", line 36, in safe_map
return list(map(f, *args))
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/api.py", line 2279, in abstractify
return ShapedArray(np.shape(x), dtypes.result_type(x))
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/dtypes.py", line 294, in result_type
return canonicalize_dtype(dtype(args[0]))
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/jax/dtypes.py", line 288, in dtype
return np.result_type(x)
File "<__array_function__ internals>", line 5, in result_type
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/numpy/core/_internal.py", line 64, in _usefields
names, formats, offsets, titles = _makenames_list(adict, align)
File "/usr/local/google/home/dberth/jax3/lib/python3.8/site-packages/numpy/core/_internal.py", line 40, in _makenames_list
format = dtype(obj[0], align=align)
TypeError: data type not understood
|
TypeError
|
def id_tap(tap_func, arg, *, result=None, tap_with_device=False, **kwargs):
"""Host-callback tap primitive, like identity function with a call to ``tap_func``.
**Experimental: please give feedback, and expect changes!**
``id_tap`` behaves semantically like the identity function but has the
side-effect that a user-defined Python function is called with the runtime
value of the argument.
Args:
tap_func: tap function to call like ``tap_func(arg, transforms)``, with
``arg`` as described below and where ``transforms`` is the sequence of
applied JAX transformations in the form ``(name, params)``. If the
`tap_with_device` optional argument is True, then the invocation also
includes the device from which the value is tapped as a keyword argument:
``tap_func(arg, transforms, device=dev)``.
arg: the argument passed to the tap function, can be a pytree of JAX
types.
result: if given, specifies the return value of ``id_tap``. This value is
not passed to the tap function, and in fact is not sent from the device to
the host. If the ``result`` parameter is not specified then the return
value of ``id_tap`` is ``arg``.
tap_with_device: if True then the tap function is invoked with the
device from which the tap originates as a keyword argument.
Returns:
``arg``, or ``result`` if given.
The order of execution is by data dependency: after all the arguments and
the value of ``result`` if present, are computed and before the returned
value is used. At least one of the returned values of ``id_tap`` must be
used in the rest of the computation, or else this operation has no effect.
Tapping works even for code executed on accelerators and even for code under
JAX transformations.
For more details see the
`module documentation
<jax.experimental.host_callback.html>`_.
"""
if kwargs:
msg = (
"Support for **kwargs in ``id_tap`` has been removed. Instead, "
"pre-apply keyword arguments, either by using a closure or by passing "
"``functools.partial(tap_func, **kwargs)``."
)
raise TypeError(msg)
if result is not None:
flat_results, result_treedef = pytree.flatten(result)
for result in flat_results:
api._check_arg(result)
call_res = _call(
tap_func,
arg,
call_with_device=tap_with_device,
result_shape=None,
identity=True,
)
if result is not None:
# Return the results, but add a dependency on the call, to ensure it
# is kept in the graph.
call_flat_results, _ = pytree.flatten(call_res)
if call_flat_results:
call_flat_results = [
id_tap_dep_p.bind(r, call_flat_results[0]) for r in flat_results
]
else:
call_flat_results = flat_results
return result_treedef.unflatten(call_flat_results)
else:
return call_res
|
def id_tap(tap_func, arg, *, result=None, tap_with_device=False, **kwargs):
"""Host-callback tap primitive, like identity function with a call to ``tap_func``.
**Experimental: please give feedback, and expect changes!**
``id_tap`` behaves semantically like the identity function but has the
side-effect that a user-defined Python function is called with the runtime
value of the argument.
Args:
tap_func: tap function to call like ``tap_func(arg, transforms)``, with
``arg`` as described below and where ``transforms`` is the sequence of
applied JAX transformations in the form ``(name, params)``. If the
`tap_with_device` optional argument is True, then the invocation also
includes the device from which the value is tapped as a keyword argument:
``tap_func(arg, transforms, device=dev)``.
arg: the argument passed to the tap function, can be a pytree of JAX
types.
result: if given, specifies the return value of ``id_tap``. This value is
not passed to the tap function, and in fact is not sent from the device to
the host. If the ``result`` parameter is not specified then the return
value of ``id_tap`` is ``arg``.
tap_with_device: if True then the tap function is invoked with the
device from which the tap originates as a keyword argument.
Returns:
``arg``, or ``result`` if given.
The order of execution is by data dependency: after all the arguments and
the value of ``result`` if present, are computed and before the returned
value is used. At least one of the returned values of ``id_tap`` must be
used in the rest of the computation, or else this operation has no effect.
Tapping works even for code executed on accelerators and even for code under
JAX transformations.
For more details see the
`module documentation
<jax.experimental.host_callback.html>`_.
"""
if kwargs:
msg = (
"Support for **kwargs in ``id_tap`` has been removed. Instead, "
"pre-apply keyword arguments, either by using a closure or by passing "
"``functools.partial(tap_func, **kwargs)``."
)
raise TypeError(msg)
if result is not None:
flat_results, result_treedef = pytree.flatten(result)
for result in flat_results:
api._check_arg(result)
call_res = _call(
tap_func,
arg,
call_with_device=tap_with_device,
result_shape=None,
identity=True,
)
if result is not None:
# Return the results, but add a dependency on the call, to ensure it
# is kept in the graph.
call_flat_results, _ = pytree.flatten(call_res)
assert call_flat_results
call_flat_results = [
id_tap_dep_p.bind(r, call_flat_results[0]) for r in flat_results
]
return result_treedef.unflatten(call_flat_results)
else:
return call_res
|
https://github.com/google/jax/issues/5414
|
Traceback (most recent call last):
File "/home/neil/src/a.py", line 13, in <module>
print(scan(f, None, None, 10))
File "/home/neil/src/jax/jax/_src/lax/control_flow.py", line 1266, in scan
init_flat, carry_avals, carry_avals_out, init_tree, *rest = _create_jaxpr(init)
File "/home/neil/src/jax/jax/_src/lax/control_flow.py", line 1253, in _create_jaxpr
jaxpr, consts, out_tree = _initial_style_jaxpr(f, in_tree, carry_avals + x_avals)
File "/home/neil/src/jax/jax/_src/lax/control_flow.py", line 72, in _initial_style_jaxpr
jaxpr, consts, out_tree = _initial_style_open_jaxpr(fun, in_tree, in_avals)
File "/home/neil/src/jax/jax/_src/lax/control_flow.py", line 67, in _initial_style_open_jaxpr
jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(wrapped_fun, in_avals)
File "/home/neil/src/jax/jax/interpreters/partial_eval.py", line 1191, in trace_to_jaxpr_dynamic
jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, main, in_avals)
File "/home/neil/src/jax/jax/interpreters/partial_eval.py", line 1201, in trace_to_subjaxpr_dynamic
ans = fun.call_wrapped(*in_tracers)
File "/home/neil/src/jax/jax/linear_util.py", line 160, in call_wrapped
ans = self.f(*args, **dict(self.params, **kwargs))
File "/home/neil/src/a.py", line 11, in f
id_tap(tap_function, None, result=trajectory)
File "/home/neil/src/jax/jax/experimental/host_callback.py", line 464, in id_tap
assert call_flat_results
AssertionError
|
AssertionError
|
def dynamic_slice_in_dim(operand, start_index, slice_size, axis=0):
"""Convenience wrapper around dynamic_slice applying to one dimension."""
start_indices = [onp.array([0], dtype=_dtype(start_index))] * operand.ndim
slice_sizes = list(operand.shape)
axis = int(axis)
axis_size = _const(start_index, operand.shape[axis])
start_indices[axis] = reshape(rem(start_index, axis_size), [1])
slice_sizes[axis] = int(slice_size)
start_indices = concatenate(start_indices, 0)
return dynamic_slice(operand, start_indices, slice_sizes)
|
def dynamic_slice_in_dim(operand, start_index, slice_size, axis=0):
"""Convenience wrapper around dynamic_slice applying to one dimension."""
start_indices = [onp.array([0])] * operand.ndim
slice_sizes = list(operand.shape)
axis = int(axis)
axis_size = _const(start_index, operand.shape[axis])
start_indices[axis] = reshape(rem(start_index, axis_size), [1])
slice_sizes[axis] = int(slice_size)
start_indices = concatenate(start_indices, 0)
return dynamic_slice(operand, start_indices, slice_sizes)
|
https://github.com/google/jax/issues/826
|
(1, 2, 2) (3, 2)
[[1. 1.]
[1. 1.]
[1. 1.]]
/Users/skainswo/.local/share/virtualenvs/research-OGGq2tNy/lib/python3.7/site-packages/jax/lib/xla_bridge.py:130: UserWarning: No GPU/TPU found, falling back to CPU.
warnings.warn('No GPU/TPU found, falling back to CPU.')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~/nu/skainswo/research/gan_with_the_wind/mle_normal.py in <module>
31 print(A.shape, b.shape)
32 print(np.linalg.solve(A, b))
---> 33 print(jp.linalg.solve(A, b))
~/.local/share/virtualenvs/research-OGGq2tNy/lib/python3.7/site-packages/jax/numpy/linalg.py in solve(a, b)
247 x = b if a_ndims == b_ndims else b[..., None]
248
--> 249 permutation = lax_linalg.lu_pivots_to_permutation(pivots, m)
250 x = x[..., permutation, :]
251
~/.local/share/virtualenvs/research-OGGq2tNy/lib/python3.7/site-packages/jax/lax_linalg.py in lu_pivots_to_permutation(swaps, k)
462 return swaps, permutation
463
--> 464 n, = np.shape(swaps)
465 permutation = np.arange(k)
466 _, permutation = lax.fori_loop(
ValueError: too many values to unpack (expected 1)
|
ValueError
|
def lu_pivots_to_permutation(swaps, m):
"""Converts the pivots (row swaps) returned by LU to a permutation.
We build a permutation rather than applying `swaps` directly to the rows
of a matrix because lax loops aren't differentiable.
Args:
swaps: an array of shape (..., k) of row swaps to perform
m: the size of the output permutation. m should be >= k.
Returns:
An int32 array of shape (..., m).
"""
assert len(swaps.shape) >= 1
batch_dims = swaps.shape[:-1]
k = swaps.shape[-1]
def body_fn(i, permutation):
j = swaps[..., i]
iotas = np.ix_(*(lax.iota(np.int32, b) for b in batch_dims))
x = permutation[..., i]
y = permutation[iotas + (j,)]
permutation = ops.index_update(permutation, ops.index[..., i], y)
return ops.index_update(permutation, ops.index[iotas + (j,)], x)
permutation = lax.broadcasted_iota(np.int32, batch_dims + (m,), len(batch_dims))
return lax.fori_loop(
onp.array(0, onp.int32), onp.array(k, onp.int32), body_fn, permutation
)
|
def lu_pivots_to_permutation(swaps, k):
"""Converts the pivots (row swaps) returned by LU to a permutation."""
def body_fn(i, loop_carry):
swaps, permutation = loop_carry
j = swaps[i]
x, y = np.ravel(permutation[i]), np.ravel(permutation[j])
permutation = lax.dynamic_update_index_in_dim(permutation, y, i, axis=0)
permutation = lax.dynamic_update_index_in_dim(permutation, x, j, axis=0)
return swaps, permutation
(n,) = np.shape(swaps)
permutation = np.arange(k)
_, permutation = lax.fori_loop(
onp.array(0, onp.int32), onp.array(n, onp.int32), body_fn, (swaps, permutation)
)
return permutation
|
https://github.com/google/jax/issues/826
|
(1, 2, 2) (3, 2)
[[1. 1.]
[1. 1.]
[1. 1.]]
/Users/skainswo/.local/share/virtualenvs/research-OGGq2tNy/lib/python3.7/site-packages/jax/lib/xla_bridge.py:130: UserWarning: No GPU/TPU found, falling back to CPU.
warnings.warn('No GPU/TPU found, falling back to CPU.')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~/nu/skainswo/research/gan_with_the_wind/mle_normal.py in <module>
31 print(A.shape, b.shape)
32 print(np.linalg.solve(A, b))
---> 33 print(jp.linalg.solve(A, b))
~/.local/share/virtualenvs/research-OGGq2tNy/lib/python3.7/site-packages/jax/numpy/linalg.py in solve(a, b)
247 x = b if a_ndims == b_ndims else b[..., None]
248
--> 249 permutation = lax_linalg.lu_pivots_to_permutation(pivots, m)
250 x = x[..., permutation, :]
251
~/.local/share/virtualenvs/research-OGGq2tNy/lib/python3.7/site-packages/jax/lax_linalg.py in lu_pivots_to_permutation(swaps, k)
462 return swaps, permutation
463
--> 464 n, = np.shape(swaps)
465 permutation = np.arange(k)
466 _, permutation = lax.fori_loop(
ValueError: too many values to unpack (expected 1)
|
ValueError
|
def body_fn(i, permutation):
j = swaps[..., i]
iotas = np.ix_(*(lax.iota(np.int32, b) for b in batch_dims))
x = permutation[..., i]
y = permutation[iotas + (j,)]
permutation = ops.index_update(permutation, ops.index[..., i], y)
return ops.index_update(permutation, ops.index[iotas + (j,)], x)
|
def body_fn(i, loop_carry):
swaps, permutation = loop_carry
j = swaps[i]
x, y = np.ravel(permutation[i]), np.ravel(permutation[j])
permutation = lax.dynamic_update_index_in_dim(permutation, y, i, axis=0)
permutation = lax.dynamic_update_index_in_dim(permutation, x, j, axis=0)
return swaps, permutation
|
https://github.com/google/jax/issues/826
|
(1, 2, 2) (3, 2)
[[1. 1.]
[1. 1.]
[1. 1.]]
/Users/skainswo/.local/share/virtualenvs/research-OGGq2tNy/lib/python3.7/site-packages/jax/lib/xla_bridge.py:130: UserWarning: No GPU/TPU found, falling back to CPU.
warnings.warn('No GPU/TPU found, falling back to CPU.')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~/nu/skainswo/research/gan_with_the_wind/mle_normal.py in <module>
31 print(A.shape, b.shape)
32 print(np.linalg.solve(A, b))
---> 33 print(jp.linalg.solve(A, b))
~/.local/share/virtualenvs/research-OGGq2tNy/lib/python3.7/site-packages/jax/numpy/linalg.py in solve(a, b)
247 x = b if a_ndims == b_ndims else b[..., None]
248
--> 249 permutation = lax_linalg.lu_pivots_to_permutation(pivots, m)
250 x = x[..., permutation, :]
251
~/.local/share/virtualenvs/research-OGGq2tNy/lib/python3.7/site-packages/jax/lax_linalg.py in lu_pivots_to_permutation(swaps, k)
462 return swaps, permutation
463
--> 464 n, = np.shape(swaps)
465 permutation = np.arange(k)
466 _, permutation = lax.fori_loop(
ValueError: too many values to unpack (expected 1)
|
ValueError
|
def solve(a, b):
a, b = _promote_arg_dtypes(np.asarray(a), np.asarray(b))
a_shape = np.shape(a)
b_shape = np.shape(b)
a_ndims = len(a_shape)
b_ndims = len(b_shape)
if not (a_ndims >= 2 and a_shape[-1] == a_shape[-2] and b_ndims >= 1):
msg = (
"The arguments to solve must have shapes a=[..., m, m] and "
"b=[..., m, k] or b=[..., m]; got a={} and b={}"
)
raise ValueError(msg.format(a_shape, b_shape))
lu, pivots = lax_linalg.lu(a)
dtype = lax.dtype(a)
m = a_shape[-1]
# Numpy treats the RHS as a (batched) vector if the number of dimensions
# differ by 1. Otherwise, broadcasting rules apply.
x = b[..., None] if a_ndims == b_ndims + 1 else b
batch_dims = lax.broadcast_shapes(lu.shape[:-2], x.shape[:-2])
x = np.broadcast_to(x, batch_dims + x.shape[-2:])
lu = np.broadcast_to(lu, batch_dims + lu.shape[-2:])
permutation = lax_linalg.lu_pivots_to_permutation(pivots, m)
permutation = np.broadcast_to(permutation, batch_dims + (m,))
iotas = np.ix_(*(lax.iota(np.int32, b) for b in batch_dims + (1,)))
x = x[iotas[:-1] + (permutation, slice(None))]
# TODO(phawkins): add unit_diagonal support to triangular_solve, use it here
# instead of explicit masking of l.
l = np.tril(lu, -1)[..., :, :m] + np.eye(m, m, dtype=dtype)
x = lax_linalg.triangular_solve(l, x, left_side=True, lower=True)
x = lax_linalg.triangular_solve(lu, x, left_side=True, lower=False)
return x[..., 0] if a_ndims == b_ndims + 1 else x
|
def solve(a, b):
a, b = _promote_arg_dtypes(np.asarray(a), np.asarray(b))
a_shape = np.shape(a)
b_shape = np.shape(b)
a_ndims = len(a_shape)
b_ndims = len(b_shape)
if not (
a_ndims >= 2
and a_shape[-1] == a_shape[-2]
and (a_ndims == b_ndims or a_ndims == b_ndims + 1)
):
msg = (
"The arguments to solve must have shapes a=[..., m, m] and "
"b=[..., m, k] or b=[..., m]; got a={} and b={}"
)
raise ValueError(msg.format(a_shape, b_shape))
lu, pivots = lax_linalg.lu(a)
dtype = lax.dtype(a)
# TODO(phawkins): add unit_diagonal support to solve_triangular, use it here
# instead of explicit masking of l.
m = a_shape[-1]
l = np.tril(lu, -1)[:, :m] + np.eye(m, m, dtype=dtype)
# TODO(phawkins): triangular_solve only supports matrices on the RHS, so we
# add a dummy dimension. Extend it to support vectors and simplify this.
x = b if a_ndims == b_ndims else b[..., None]
permutation = lax_linalg.lu_pivots_to_permutation(pivots, m)
x = x[..., permutation, :]
x = lax_linalg.triangular_solve(l, x, left_side=True, lower=True)
x = lax_linalg.triangular_solve(lu, x, left_side=True, lower=False)
return x[..., 0] if a_ndims != b_ndims else x
|
https://github.com/google/jax/issues/826
|
(1, 2, 2) (3, 2)
[[1. 1.]
[1. 1.]
[1. 1.]]
/Users/skainswo/.local/share/virtualenvs/research-OGGq2tNy/lib/python3.7/site-packages/jax/lib/xla_bridge.py:130: UserWarning: No GPU/TPU found, falling back to CPU.
warnings.warn('No GPU/TPU found, falling back to CPU.')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~/nu/skainswo/research/gan_with_the_wind/mle_normal.py in <module>
31 print(A.shape, b.shape)
32 print(np.linalg.solve(A, b))
---> 33 print(jp.linalg.solve(A, b))
~/.local/share/virtualenvs/research-OGGq2tNy/lib/python3.7/site-packages/jax/numpy/linalg.py in solve(a, b)
247 x = b if a_ndims == b_ndims else b[..., None]
248
--> 249 permutation = lax_linalg.lu_pivots_to_permutation(pivots, m)
250 x = x[..., permutation, :]
251
~/.local/share/virtualenvs/research-OGGq2tNy/lib/python3.7/site-packages/jax/lax_linalg.py in lu_pivots_to_permutation(swaps, k)
462 return swaps, permutation
463
--> 464 n, = np.shape(swaps)
465 permutation = np.arange(k)
466 _, permutation = lax.fori_loop(
ValueError: too many values to unpack (expected 1)
|
ValueError
|
def _solve(a, b):
_check_solve_shapes(a, b)
# Broadcast leading dimensions of b to the shape of a, as is required by
# custom_linear_solve.
out_shape = tuple(
d_a if d_b == 1 else d_b for d_a, d_b in zip(a.shape[:-1] + (1,), b.shape)
)
b = jnp.broadcast_to(b, out_shape)
# With custom_linear_solve, we can reuse the same factorization when
# computing sensitivities. This is considerably faster.
lu_, _, permutation = lu(lax.stop_gradient(a))
custom_solve = partial(
lax.custom_linear_solve,
lambda x: _matvec_multiply(a, x),
solve=lambda _, x: lu_solve(lu_, permutation, x, trans=0),
transpose_solve=lambda _, x: lu_solve(lu_, permutation, x, trans=1),
)
if a.ndim == b.ndim + 1:
# b.shape == [..., m]
return custom_solve(b)
else:
# b.shape == [..., m, k]
return api.vmap(custom_solve, b.ndim - 1, max(a.ndim, b.ndim) - 1)(b)
|
def _solve(a, b):
_check_solve_shapes(a, b)
# With custom_linear_solve, we can reuse the same factorization when
# computing sensitivities. This is considerably faster.
lu_, _, permutation = lu(lax.stop_gradient(a))
custom_solve = partial(
lax.custom_linear_solve,
lambda x: _matvec_multiply(a, x),
solve=lambda _, x: lu_solve(lu_, permutation, x, trans=0),
transpose_solve=lambda _, x: lu_solve(lu_, permutation, x, trans=1),
)
if a.ndim == b.ndim + 1:
# b.shape == [..., m]
return custom_solve(b)
else:
# b.shape == [..., m, k]
return api.vmap(custom_solve, b.ndim - 1, max(a.ndim, b.ndim) - 1)(b)
|
https://github.com/google/jax/issues/826
|
(1, 2, 2) (3, 2)
[[1. 1.]
[1. 1.]
[1. 1.]]
/Users/skainswo/.local/share/virtualenvs/research-OGGq2tNy/lib/python3.7/site-packages/jax/lib/xla_bridge.py:130: UserWarning: No GPU/TPU found, falling back to CPU.
warnings.warn('No GPU/TPU found, falling back to CPU.')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~/nu/skainswo/research/gan_with_the_wind/mle_normal.py in <module>
31 print(A.shape, b.shape)
32 print(np.linalg.solve(A, b))
---> 33 print(jp.linalg.solve(A, b))
~/.local/share/virtualenvs/research-OGGq2tNy/lib/python3.7/site-packages/jax/numpy/linalg.py in solve(a, b)
247 x = b if a_ndims == b_ndims else b[..., None]
248
--> 249 permutation = lax_linalg.lu_pivots_to_permutation(pivots, m)
250 x = x[..., permutation, :]
251
~/.local/share/virtualenvs/research-OGGq2tNy/lib/python3.7/site-packages/jax/lax_linalg.py in lu_pivots_to_permutation(swaps, k)
462 return swaps, permutation
463
--> 464 n, = np.shape(swaps)
465 permutation = np.arange(k)
466 _, permutation = lax.fori_loop(
ValueError: too many values to unpack (expected 1)
|
ValueError
|
def _check_solve_shapes(a, b):
if not (
a.ndim >= 2
and b.ndim in [a.ndim, a.ndim - 1]
and a.shape[-1] == a.shape[-2] == b.shape[a.ndim - 2]
):
raise ValueError(
"The arguments to solve must have shapes a=[..., m, m] and "
f"b=[..., m, k] or b=[..., m]; got a={a.shape} and b={b.shape}"
)
|
def _check_solve_shapes(a, b):
if not (a.ndim >= 2 and a.shape[-1] == a.shape[-2] and b.ndim >= 1):
msg = (
"The arguments to solve must have shapes a=[..., m, m] and "
"b=[..., m, k] or b=[..., m]; got a={} and b={}"
)
raise ValueError(msg.format(a.shape, b.shape))
|
https://github.com/google/jax/issues/5313
|
---------------------------------------------------------------------------
FilteredStackTrace Traceback (most recent call last)
<ipython-input-1-551ceea3fd37> in <module>
2
----> 3 jax.numpy.linalg.inv(jax.numpy.zeros((0, 0)))
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/linalg.py in inv(a)
334 .format(jnp.shape(a)))
--> 335 return solve(
336 a, lax.broadcast(jnp.eye(a.shape[-1], dtype=lax.dtype(a)), a.shape[:-2]))
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/linalg.py in solve(a, b)
449 a, b = _promote_arg_dtypes(jnp.asarray(a), jnp.asarray(b))
--> 450 return lax_linalg._solve(a, b)
451
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in _solve(a, b)
265 # b.shape == [..., m, k]
--> 266 return api.vmap(custom_solve, b.ndim - 1, max(a.ndim, b.ndim) - 1)(b)
267
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in custom_linear_solve(matvec, b, solve, transpose_solve, symmetric)
2182
-> 2183 solve_jaxpr, solve_consts, out_tree = _initial_style_jaxpr(
2184 _shape_checked(partial(solve, matvec), "solve"), in_args_tree, b_avals)
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in _initial_style_jaxpr(fun, in_tree, in_avals)
71 def _initial_style_jaxpr(fun: Callable, in_tree, in_avals):
---> 72 jaxpr, out_avals, consts, out_tree = _initial_style_open_jaxpr(fun, in_tree, in_avals)
73 closed_jaxpr = core.ClosedJaxpr(pe.convert_constvars_jaxpr(jaxpr), ())
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in _initial_style_open_jaxpr(fun, in_tree, in_avals)
66 wrapped_fun, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)
---> 67 jaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(wrapped_fun, in_avals)
68 return jaxpr, out_avals, consts, out_tree()
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in f(x)
2173 def f(x):
-> 2174 y = fun(x)
2175 _check_shapes(name, "b", y, b_flat)
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in <lambda>(_, x)
258 lambda x: _matvec_multiply(a, x),
--> 259 solve=lambda _, x: lu_solve(lu_, permutation, x, trans=0),
260 transpose_solve=lambda _, x: lu_solve(lu_, permutation, x, trans=1))
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in lu_solve(lu, permutation, b, trans)
987 """LU solve with broadcasting."""
--> 988 return _lu_solve(lu, permutation, b, trans)
989
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in _lu_solve(lu, permutation, b, trans)
981 .format(lu.shape, b.shape))
--> 982 x = _lu_solve_core(lu, permutation, b, trans)
983 return x[..., 0] if rhs_vector else x
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/vectorize.py in wrapped(*args)
303 vectorized_func = api.vmap(vectorized_func, in_axes)
--> 304 return vectorized_func(*vec_args)
305
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/vectorize.py in wrapped(*args)
134 def wrapped(*args):
--> 135 out = func(*args)
136 out_shapes = map(jnp.shape, out if isinstance(out, tuple) else [out])
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/vectorize.py in new_func(*args)
175 args.insert(i, arg)
--> 176 return func(*args)
177
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in _lu_solve_core(lu, permutation, b, trans)
938 m = lu.shape[0]
--> 939 x = jnp.reshape(b, (m, -1))
940 if trans == 0:
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in reshape(a, newshape, order)
1246 try:
-> 1247 return a.reshape(newshape, order=order) # forward to method for ndarrays
1248 except AttributeError:
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in _reshape_method(a, *newshape, **kwargs)
1291 newshape = newshape[0]
-> 1292 return _reshape(a, newshape, order=order)
1293
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in _reshape(a, newshape, order)
1267 def _reshape(a, newshape, order="C"):
-> 1268 computed_newshape = _compute_newshape(a, newshape)
1269 if order == "C":
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in _compute_newshape(a, newshape)
1261 if np.any(np.equal(newshape, -1)):
-> 1262 fix = -a.size // (newshape if type(newshape) is Poly else _prod(newshape))
1263 return [d if d != -1 else fix for d in newshape]
FilteredStackTrace: ZeroDivisionError: integer division or modulo by zero
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
ZeroDivisionError Traceback (most recent call last)
<ipython-input-1-551ceea3fd37> in <module>
1 import jax
2
----> 3 jax.numpy.linalg.inv(jax.numpy.zeros((0, 0)))
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/linalg.py in inv(a)
333 raise ValueError("Argument to inv must have shape [..., n, n], got {}."
334 .format(jnp.shape(a)))
--> 335 return solve(
336 a, lax.broadcast(jnp.eye(a.shape[-1], dtype=lax.dtype(a)), a.shape[:-2]))
337
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/traceback_util.py in reraise_with_filtered_traceback(*args, **kwargs)
137 def reraise_with_filtered_traceback(*args, **kwargs):
138 try:
--> 139 return fun(*args, **kwargs)
140 except Exception as e:
141 if not is_under_reraiser(e):
/opt/texat-venv/lib/python3.8/site-packages/jax/api.py in f_jitted(*args, **kwargs)
369 return cache_miss(*args, **kwargs)[0] # probably won't return
370 else:
--> 371 return cpp_jitted_f(*args, **kwargs)
372 f_jitted._cpp_jitted_f = cpp_jitted_f
373
/opt/texat-venv/lib/python3.8/site-packages/jax/api.py in cache_miss(*args, **kwargs)
276 _check_arg(arg)
277 flat_fun, out_tree = flatten_fun(f, in_tree)
--> 278 out_flat = xla.xla_call(
279 flat_fun,
280 *args_flat,
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in bind(self, fun, *args, **params)
1227
1228 def bind(self, fun, *args, **params):
-> 1229 return call_bind(self, fun, *args, **params)
1230
1231 def process(self, trace, fun, tracers, params):
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in call_bind(primitive, fun, *args, **params)
1218 tracers = map(top_trace.full_raise, args)
1219 with maybe_new_sublevel(top_trace):
-> 1220 outs = primitive.process(top_trace, fun, tracers, params)
1221 return map(full_lower, apply_todos(env_trace_todo(), outs))
1222
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in process(self, trace, fun, tracers, params)
1230
1231 def process(self, trace, fun, tracers, params):
-> 1232 return trace.process_call(self, fun, tracers, params)
1233
1234 def post_process(self, trace, out_tracers, params):
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in process_call(self, primitive, f, tracers, params)
596
597 def process_call(self, primitive, f, tracers, params):
--> 598 return primitive.impl(f, *tracers, **params)
599 process_map = process_call
600
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/xla.py in _xla_call_impl(fun, device, backend, name, donated_invars, *args)
567
568 def _xla_call_impl(fun: lu.WrappedFun, *args, device, backend, name, donated_invars):
--> 569 compiled_fun = _xla_callable(fun, device, backend, name, donated_invars,
570 *unsafe_map(arg_spec, args))
571 try:
/opt/texat-venv/lib/python3.8/site-packages/jax/linear_util.py in memoized_fun(fun, *args)
249 fun.populate_stores(stores)
250 else:
--> 251 ans = call(fun, *args)
252 cache[key] = (ans, fun.stores)
253
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/xla.py in _xla_callable(fun, device, backend, name, donated_invars, *arg_specs)
643 abstract_args, arg_devices = unzip2(arg_specs)
644 if config.omnistaging_enabled:
--> 645 jaxpr, out_avals, consts = pe.trace_to_jaxpr_final(fun, abstract_args)
646 if any(isinstance(c, core.Tracer) for c in consts):
647 raise core.UnexpectedTracerError("Encountered an unexpected tracer.")
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/partial_eval.py in trace_to_jaxpr_final(fun, in_avals)
1228 main.source_info = fun_sourceinfo(fun.f) # type: ignore
1229 main.jaxpr_stack = () # type: ignore
-> 1230 jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, main, in_avals)
1231 del main
1232 return jaxpr, out_avals, consts
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/partial_eval.py in trace_to_subjaxpr_dynamic(fun, main, in_avals)
1209 trace = DynamicJaxprTrace(main, core.cur_sublevel())
1210 in_tracers = map(trace.new_arg, in_avals)
-> 1211 ans = fun.call_wrapped(*in_tracers)
1212 out_tracers = map(trace.full_raise, ans)
1213 jaxpr, out_avals, consts = frame.to_jaxpr(in_tracers, out_tracers)
/opt/texat-venv/lib/python3.8/site-packages/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
158
159 try:
--> 160 ans = self.f(*args, **dict(self.params, **kwargs))
161 except:
162 # Some transformations yield from inside context managers, so we have to
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/linalg.py in solve(a, b)
448 def solve(a, b):
449 a, b = _promote_arg_dtypes(jnp.asarray(a), jnp.asarray(b))
--> 450 return lax_linalg._solve(a, b)
451
452
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in _solve(a, b)
264 else:
265 # b.shape == [..., m, k]
--> 266 return api.vmap(custom_solve, b.ndim - 1, max(a.ndim, b.ndim) - 1)(b)
267
268 def _T(x): return jnp.swapaxes(x, -1, -2)
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/traceback_util.py in reraise_with_filtered_traceback(*args, **kwargs)
137 def reraise_with_filtered_traceback(*args, **kwargs):
138 try:
--> 139 return fun(*args, **kwargs)
140 except Exception as e:
141 if not is_under_reraiser(e):
/opt/texat-venv/lib/python3.8/site-packages/jax/api.py in batched_fun(*args)
1184 in_axes_flat = flatten_axes("vmap in_axes", in_tree, in_axes)
1185 _ = _mapped_axis_size(in_tree, args_flat, in_axes_flat, "vmap")
-> 1186 out_flat = batching.batch(flat_fun, args_flat, in_axes_flat,
1187 lambda: flatten_axes("vmap out_axes", out_tree(),
1188 out_axes),
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/batching.py in batch(fun, in_vals, in_dims, out_dim_dests, axis_name)
33 # executes a batched version of `fun` following out_dim_dests
34 batched_fun = batch_fun(fun, in_dims, out_dim_dests, axis_name=axis_name)
---> 35 return batched_fun.call_wrapped(*in_vals)
36
37 @lu.transformation_with_aux
/opt/texat-venv/lib/python3.8/site-packages/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
158
159 try:
--> 160 ans = self.f(*args, **dict(self.params, **kwargs))
161 except:
162 # Some transformations yield from inside context managers, so we have to
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in custom_linear_solve(matvec, b, solve, transpose_solve, symmetric)
2181 _check_tree("matvec", "b", out_tree, tree)
2182
-> 2183 solve_jaxpr, solve_consts, out_tree = _initial_style_jaxpr(
2184 _shape_checked(partial(solve, matvec), "solve"), in_args_tree, b_avals)
2185 _check_tree("solve", "b", out_tree, tree)
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in _initial_style_jaxpr(fun, in_tree, in_avals)
70 @cache()
71 def _initial_style_jaxpr(fun: Callable, in_tree, in_avals):
---> 72 jaxpr, out_avals, consts, out_tree = _initial_style_open_jaxpr(fun, in_tree, in_avals)
73 closed_jaxpr = core.ClosedJaxpr(pe.convert_constvars_jaxpr(jaxpr), ())
74 return closed_jaxpr, consts, out_tree
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in _initial_style_open_jaxpr(fun, in_tree, in_avals)
65 def _initial_style_open_jaxpr(fun: Callable, in_tree, in_avals):
66 wrapped_fun, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)
---> 67 jaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(wrapped_fun, in_avals)
68 return jaxpr, out_avals, consts, out_tree()
69
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/partial_eval.py in trace_to_jaxpr_dynamic(fun, in_avals)
1199 main.source_info = fun_sourceinfo(fun.f) # type: ignore
1200 main.jaxpr_stack = () # type: ignore
-> 1201 jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, main, in_avals)
1202 del main
1203 return jaxpr, out_avals, consts
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/partial_eval.py in trace_to_subjaxpr_dynamic(fun, main, in_avals)
1209 trace = DynamicJaxprTrace(main, core.cur_sublevel())
1210 in_tracers = map(trace.new_arg, in_avals)
-> 1211 ans = fun.call_wrapped(*in_tracers)
1212 out_tracers = map(trace.full_raise, ans)
1213 jaxpr, out_avals, consts = frame.to_jaxpr(in_tracers, out_tracers)
/opt/texat-venv/lib/python3.8/site-packages/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
158
159 try:
--> 160 ans = self.f(*args, **dict(self.params, **kwargs))
161 except:
162 # Some transformations yield from inside context managers, so we have to
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in f(x)
2172 def _shape_checked(fun, name):
2173 def f(x):
-> 2174 y = fun(x)
2175 _check_shapes(name, "b", y, b_flat)
2176 return y
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in <lambda>(_, x)
257 lax.custom_linear_solve,
258 lambda x: _matvec_multiply(a, x),
--> 259 solve=lambda _, x: lu_solve(lu_, permutation, x, trans=0),
260 transpose_solve=lambda _, x: lu_solve(lu_, permutation, x, trans=1))
261 if a.ndim == b.ndim + 1:
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in lu_solve(lu, permutation, b, trans)
986 def lu_solve(lu, permutation, b, trans=0):
987 """LU solve with broadcasting."""
--> 988 return _lu_solve(lu, permutation, b, trans)
989
990
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/traceback_util.py in reraise_with_filtered_traceback(*args, **kwargs)
137 def reraise_with_filtered_traceback(*args, **kwargs):
138 try:
--> 139 return fun(*args, **kwargs)
140 except Exception as e:
141 if not is_under_reraiser(e):
/opt/texat-venv/lib/python3.8/site-packages/jax/api.py in f_jitted(*args, **kwargs)
369 return cache_miss(*args, **kwargs)[0] # probably won't return
370 else:
--> 371 return cpp_jitted_f(*args, **kwargs)
372 f_jitted._cpp_jitted_f = cpp_jitted_f
373
/opt/texat-venv/lib/python3.8/site-packages/jax/api.py in cache_miss(*args, **kwargs)
276 _check_arg(arg)
277 flat_fun, out_tree = flatten_fun(f, in_tree)
--> 278 out_flat = xla.xla_call(
279 flat_fun,
280 *args_flat,
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in bind(self, fun, *args, **params)
1227
1228 def bind(self, fun, *args, **params):
-> 1229 return call_bind(self, fun, *args, **params)
1230
1231 def process(self, trace, fun, tracers, params):
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in call_bind(primitive, fun, *args, **params)
1218 tracers = map(top_trace.full_raise, args)
1219 with maybe_new_sublevel(top_trace):
-> 1220 outs = primitive.process(top_trace, fun, tracers, params)
1221 return map(full_lower, apply_todos(env_trace_todo(), outs))
1222
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in process(self, trace, fun, tracers, params)
1230
1231 def process(self, trace, fun, tracers, params):
-> 1232 return trace.process_call(self, fun, tracers, params)
1233
1234 def post_process(self, trace, out_tracers, params):
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/partial_eval.py in process_call(self, call_primitive, f, tracers, params)
1083 def process_call(self, call_primitive, f, tracers, params):
1084 in_avals = [t.aval for t in tracers]
-> 1085 jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(f, self.main, in_avals)
1086 if not jaxpr.eqns:
1087 return core.eval_jaxpr(jaxpr, consts, *tracers)
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/partial_eval.py in trace_to_subjaxpr_dynamic(fun, main, in_avals)
1209 trace = DynamicJaxprTrace(main, core.cur_sublevel())
1210 in_tracers = map(trace.new_arg, in_avals)
-> 1211 ans = fun.call_wrapped(*in_tracers)
1212 out_tracers = map(trace.full_raise, ans)
1213 jaxpr, out_avals, consts = frame.to_jaxpr(in_tracers, out_tracers)
/opt/texat-venv/lib/python3.8/site-packages/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
158
159 try:
--> 160 ans = self.f(*args, **dict(self.params, **kwargs))
161 except:
162 # Some transformations yield from inside context managers, so we have to
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in _lu_solve(lu, permutation, b, trans)
980 "(shape {}) must match"
981 .format(lu.shape, b.shape))
--> 982 x = _lu_solve_core(lu, permutation, b, trans)
983 return x[..., 0] if rhs_vector else x
984
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/vectorize.py in wrapped(*args)
302 vmap_counts = [max(c - 1, 0) for c in vmap_counts]
303 vectorized_func = api.vmap(vectorized_func, in_axes)
--> 304 return vectorized_func(*vec_args)
305
306 return wrapped
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/vectorize.py in wrapped(*args)
133 """Check that output core dimensions match the signature."""
134 def wrapped(*args):
--> 135 out = func(*args)
136 out_shapes = map(jnp.shape, out if isinstance(out, tuple) else [out])
137
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/vectorize.py in new_func(*args)
174 for i, arg in static_args:
175 args.insert(i, arg)
--> 176 return func(*args)
177
178 return new_func, dynamic_args
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in _lu_solve_core(lu, permutation, b, trans)
937 def _lu_solve_core(lu, permutation, b, trans):
938 m = lu.shape[0]
--> 939 x = jnp.reshape(b, (m, -1))
940 if trans == 0:
941 x = x[permutation, :]
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in reshape(a, newshape, order)
1245 def reshape(a, newshape, order="C"):
1246 try:
-> 1247 return a.reshape(newshape, order=order) # forward to method for ndarrays
1248 except AttributeError:
1249 return _reshape(a, newshape, order=order)
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in _reshape_method(a, *newshape, **kwargs)
1290 type(newshape[0]) is not Poly):
1291 newshape = newshape[0]
-> 1292 return _reshape(a, newshape, order=order)
1293
1294
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in _reshape(a, newshape, order)
1266
1267 def _reshape(a, newshape, order="C"):
-> 1268 computed_newshape = _compute_newshape(a, newshape)
1269 if order == "C":
1270 return lax.reshape(a, computed_newshape, None)
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in _compute_newshape(a, newshape)
1260 newshape = [check(size) for size in newshape] if iterable else check(newshape)
1261 if np.any(np.equal(newshape, -1)):
-> 1262 fix = -a.size // (newshape if type(newshape) is Poly else _prod(newshape))
1263 return [d if d != -1 else fix for d in newshape]
1264 else:
ZeroDivisionError: integer division or modulo by zero
|
ZeroDivisionError
|
def _lu_solve_core(lu, permutation, b, trans):
m = lu.shape[0]
x = jnp.reshape(b, (m, np.prod(b.shape[1:])))
if trans == 0:
x = x[permutation, :]
x = triangular_solve(lu, x, left_side=True, lower=True, unit_diagonal=True)
x = triangular_solve(lu, x, left_side=True, lower=False)
elif trans == 1 or trans == 2:
conj = trans == 2
x = triangular_solve(
lu, x, left_side=True, lower=False, transpose_a=True, conjugate_a=conj
)
x = triangular_solve(
lu,
x,
left_side=True,
lower=True,
unit_diagonal=True,
transpose_a=True,
conjugate_a=conj,
)
x = x[jnp.argsort(permutation), :]
else:
raise ValueError("'trans' value must be 0, 1, or 2, got {}".format(trans))
return lax.reshape(x, b.shape)
|
def _lu_solve_core(lu, permutation, b, trans):
m = lu.shape[0]
x = jnp.reshape(b, (m, -1))
if trans == 0:
x = x[permutation, :]
x = triangular_solve(lu, x, left_side=True, lower=True, unit_diagonal=True)
x = triangular_solve(lu, x, left_side=True, lower=False)
elif trans == 1 or trans == 2:
conj = trans == 2
x = triangular_solve(
lu, x, left_side=True, lower=False, transpose_a=True, conjugate_a=conj
)
x = triangular_solve(
lu,
x,
left_side=True,
lower=True,
unit_diagonal=True,
transpose_a=True,
conjugate_a=conj,
)
x = x[jnp.argsort(permutation), :]
else:
raise ValueError("'trans' value must be 0, 1, or 2, got {}".format(trans))
return lax.reshape(x, b.shape)
|
https://github.com/google/jax/issues/5313
|
---------------------------------------------------------------------------
FilteredStackTrace Traceback (most recent call last)
<ipython-input-1-551ceea3fd37> in <module>
2
----> 3 jax.numpy.linalg.inv(jax.numpy.zeros((0, 0)))
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/linalg.py in inv(a)
334 .format(jnp.shape(a)))
--> 335 return solve(
336 a, lax.broadcast(jnp.eye(a.shape[-1], dtype=lax.dtype(a)), a.shape[:-2]))
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/linalg.py in solve(a, b)
449 a, b = _promote_arg_dtypes(jnp.asarray(a), jnp.asarray(b))
--> 450 return lax_linalg._solve(a, b)
451
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in _solve(a, b)
265 # b.shape == [..., m, k]
--> 266 return api.vmap(custom_solve, b.ndim - 1, max(a.ndim, b.ndim) - 1)(b)
267
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in custom_linear_solve(matvec, b, solve, transpose_solve, symmetric)
2182
-> 2183 solve_jaxpr, solve_consts, out_tree = _initial_style_jaxpr(
2184 _shape_checked(partial(solve, matvec), "solve"), in_args_tree, b_avals)
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in _initial_style_jaxpr(fun, in_tree, in_avals)
71 def _initial_style_jaxpr(fun: Callable, in_tree, in_avals):
---> 72 jaxpr, out_avals, consts, out_tree = _initial_style_open_jaxpr(fun, in_tree, in_avals)
73 closed_jaxpr = core.ClosedJaxpr(pe.convert_constvars_jaxpr(jaxpr), ())
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in _initial_style_open_jaxpr(fun, in_tree, in_avals)
66 wrapped_fun, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)
---> 67 jaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(wrapped_fun, in_avals)
68 return jaxpr, out_avals, consts, out_tree()
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in f(x)
2173 def f(x):
-> 2174 y = fun(x)
2175 _check_shapes(name, "b", y, b_flat)
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in <lambda>(_, x)
258 lambda x: _matvec_multiply(a, x),
--> 259 solve=lambda _, x: lu_solve(lu_, permutation, x, trans=0),
260 transpose_solve=lambda _, x: lu_solve(lu_, permutation, x, trans=1))
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in lu_solve(lu, permutation, b, trans)
987 """LU solve with broadcasting."""
--> 988 return _lu_solve(lu, permutation, b, trans)
989
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in _lu_solve(lu, permutation, b, trans)
981 .format(lu.shape, b.shape))
--> 982 x = _lu_solve_core(lu, permutation, b, trans)
983 return x[..., 0] if rhs_vector else x
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/vectorize.py in wrapped(*args)
303 vectorized_func = api.vmap(vectorized_func, in_axes)
--> 304 return vectorized_func(*vec_args)
305
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/vectorize.py in wrapped(*args)
134 def wrapped(*args):
--> 135 out = func(*args)
136 out_shapes = map(jnp.shape, out if isinstance(out, tuple) else [out])
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/vectorize.py in new_func(*args)
175 args.insert(i, arg)
--> 176 return func(*args)
177
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in _lu_solve_core(lu, permutation, b, trans)
938 m = lu.shape[0]
--> 939 x = jnp.reshape(b, (m, -1))
940 if trans == 0:
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in reshape(a, newshape, order)
1246 try:
-> 1247 return a.reshape(newshape, order=order) # forward to method for ndarrays
1248 except AttributeError:
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in _reshape_method(a, *newshape, **kwargs)
1291 newshape = newshape[0]
-> 1292 return _reshape(a, newshape, order=order)
1293
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in _reshape(a, newshape, order)
1267 def _reshape(a, newshape, order="C"):
-> 1268 computed_newshape = _compute_newshape(a, newshape)
1269 if order == "C":
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in _compute_newshape(a, newshape)
1261 if np.any(np.equal(newshape, -1)):
-> 1262 fix = -a.size // (newshape if type(newshape) is Poly else _prod(newshape))
1263 return [d if d != -1 else fix for d in newshape]
FilteredStackTrace: ZeroDivisionError: integer division or modulo by zero
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
ZeroDivisionError Traceback (most recent call last)
<ipython-input-1-551ceea3fd37> in <module>
1 import jax
2
----> 3 jax.numpy.linalg.inv(jax.numpy.zeros((0, 0)))
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/linalg.py in inv(a)
333 raise ValueError("Argument to inv must have shape [..., n, n], got {}."
334 .format(jnp.shape(a)))
--> 335 return solve(
336 a, lax.broadcast(jnp.eye(a.shape[-1], dtype=lax.dtype(a)), a.shape[:-2]))
337
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/traceback_util.py in reraise_with_filtered_traceback(*args, **kwargs)
137 def reraise_with_filtered_traceback(*args, **kwargs):
138 try:
--> 139 return fun(*args, **kwargs)
140 except Exception as e:
141 if not is_under_reraiser(e):
/opt/texat-venv/lib/python3.8/site-packages/jax/api.py in f_jitted(*args, **kwargs)
369 return cache_miss(*args, **kwargs)[0] # probably won't return
370 else:
--> 371 return cpp_jitted_f(*args, **kwargs)
372 f_jitted._cpp_jitted_f = cpp_jitted_f
373
/opt/texat-venv/lib/python3.8/site-packages/jax/api.py in cache_miss(*args, **kwargs)
276 _check_arg(arg)
277 flat_fun, out_tree = flatten_fun(f, in_tree)
--> 278 out_flat = xla.xla_call(
279 flat_fun,
280 *args_flat,
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in bind(self, fun, *args, **params)
1227
1228 def bind(self, fun, *args, **params):
-> 1229 return call_bind(self, fun, *args, **params)
1230
1231 def process(self, trace, fun, tracers, params):
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in call_bind(primitive, fun, *args, **params)
1218 tracers = map(top_trace.full_raise, args)
1219 with maybe_new_sublevel(top_trace):
-> 1220 outs = primitive.process(top_trace, fun, tracers, params)
1221 return map(full_lower, apply_todos(env_trace_todo(), outs))
1222
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in process(self, trace, fun, tracers, params)
1230
1231 def process(self, trace, fun, tracers, params):
-> 1232 return trace.process_call(self, fun, tracers, params)
1233
1234 def post_process(self, trace, out_tracers, params):
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in process_call(self, primitive, f, tracers, params)
596
597 def process_call(self, primitive, f, tracers, params):
--> 598 return primitive.impl(f, *tracers, **params)
599 process_map = process_call
600
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/xla.py in _xla_call_impl(fun, device, backend, name, donated_invars, *args)
567
568 def _xla_call_impl(fun: lu.WrappedFun, *args, device, backend, name, donated_invars):
--> 569 compiled_fun = _xla_callable(fun, device, backend, name, donated_invars,
570 *unsafe_map(arg_spec, args))
571 try:
/opt/texat-venv/lib/python3.8/site-packages/jax/linear_util.py in memoized_fun(fun, *args)
249 fun.populate_stores(stores)
250 else:
--> 251 ans = call(fun, *args)
252 cache[key] = (ans, fun.stores)
253
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/xla.py in _xla_callable(fun, device, backend, name, donated_invars, *arg_specs)
643 abstract_args, arg_devices = unzip2(arg_specs)
644 if config.omnistaging_enabled:
--> 645 jaxpr, out_avals, consts = pe.trace_to_jaxpr_final(fun, abstract_args)
646 if any(isinstance(c, core.Tracer) for c in consts):
647 raise core.UnexpectedTracerError("Encountered an unexpected tracer.")
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/partial_eval.py in trace_to_jaxpr_final(fun, in_avals)
1228 main.source_info = fun_sourceinfo(fun.f) # type: ignore
1229 main.jaxpr_stack = () # type: ignore
-> 1230 jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, main, in_avals)
1231 del main
1232 return jaxpr, out_avals, consts
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/partial_eval.py in trace_to_subjaxpr_dynamic(fun, main, in_avals)
1209 trace = DynamicJaxprTrace(main, core.cur_sublevel())
1210 in_tracers = map(trace.new_arg, in_avals)
-> 1211 ans = fun.call_wrapped(*in_tracers)
1212 out_tracers = map(trace.full_raise, ans)
1213 jaxpr, out_avals, consts = frame.to_jaxpr(in_tracers, out_tracers)
/opt/texat-venv/lib/python3.8/site-packages/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
158
159 try:
--> 160 ans = self.f(*args, **dict(self.params, **kwargs))
161 except:
162 # Some transformations yield from inside context managers, so we have to
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/linalg.py in solve(a, b)
448 def solve(a, b):
449 a, b = _promote_arg_dtypes(jnp.asarray(a), jnp.asarray(b))
--> 450 return lax_linalg._solve(a, b)
451
452
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in _solve(a, b)
264 else:
265 # b.shape == [..., m, k]
--> 266 return api.vmap(custom_solve, b.ndim - 1, max(a.ndim, b.ndim) - 1)(b)
267
268 def _T(x): return jnp.swapaxes(x, -1, -2)
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/traceback_util.py in reraise_with_filtered_traceback(*args, **kwargs)
137 def reraise_with_filtered_traceback(*args, **kwargs):
138 try:
--> 139 return fun(*args, **kwargs)
140 except Exception as e:
141 if not is_under_reraiser(e):
/opt/texat-venv/lib/python3.8/site-packages/jax/api.py in batched_fun(*args)
1184 in_axes_flat = flatten_axes("vmap in_axes", in_tree, in_axes)
1185 _ = _mapped_axis_size(in_tree, args_flat, in_axes_flat, "vmap")
-> 1186 out_flat = batching.batch(flat_fun, args_flat, in_axes_flat,
1187 lambda: flatten_axes("vmap out_axes", out_tree(),
1188 out_axes),
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/batching.py in batch(fun, in_vals, in_dims, out_dim_dests, axis_name)
33 # executes a batched version of `fun` following out_dim_dests
34 batched_fun = batch_fun(fun, in_dims, out_dim_dests, axis_name=axis_name)
---> 35 return batched_fun.call_wrapped(*in_vals)
36
37 @lu.transformation_with_aux
/opt/texat-venv/lib/python3.8/site-packages/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
158
159 try:
--> 160 ans = self.f(*args, **dict(self.params, **kwargs))
161 except:
162 # Some transformations yield from inside context managers, so we have to
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in custom_linear_solve(matvec, b, solve, transpose_solve, symmetric)
2181 _check_tree("matvec", "b", out_tree, tree)
2182
-> 2183 solve_jaxpr, solve_consts, out_tree = _initial_style_jaxpr(
2184 _shape_checked(partial(solve, matvec), "solve"), in_args_tree, b_avals)
2185 _check_tree("solve", "b", out_tree, tree)
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in _initial_style_jaxpr(fun, in_tree, in_avals)
70 @cache()
71 def _initial_style_jaxpr(fun: Callable, in_tree, in_avals):
---> 72 jaxpr, out_avals, consts, out_tree = _initial_style_open_jaxpr(fun, in_tree, in_avals)
73 closed_jaxpr = core.ClosedJaxpr(pe.convert_constvars_jaxpr(jaxpr), ())
74 return closed_jaxpr, consts, out_tree
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in _initial_style_open_jaxpr(fun, in_tree, in_avals)
65 def _initial_style_open_jaxpr(fun: Callable, in_tree, in_avals):
66 wrapped_fun, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)
---> 67 jaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(wrapped_fun, in_avals)
68 return jaxpr, out_avals, consts, out_tree()
69
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/partial_eval.py in trace_to_jaxpr_dynamic(fun, in_avals)
1199 main.source_info = fun_sourceinfo(fun.f) # type: ignore
1200 main.jaxpr_stack = () # type: ignore
-> 1201 jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, main, in_avals)
1202 del main
1203 return jaxpr, out_avals, consts
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/partial_eval.py in trace_to_subjaxpr_dynamic(fun, main, in_avals)
1209 trace = DynamicJaxprTrace(main, core.cur_sublevel())
1210 in_tracers = map(trace.new_arg, in_avals)
-> 1211 ans = fun.call_wrapped(*in_tracers)
1212 out_tracers = map(trace.full_raise, ans)
1213 jaxpr, out_avals, consts = frame.to_jaxpr(in_tracers, out_tracers)
/opt/texat-venv/lib/python3.8/site-packages/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
158
159 try:
--> 160 ans = self.f(*args, **dict(self.params, **kwargs))
161 except:
162 # Some transformations yield from inside context managers, so we have to
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in f(x)
2172 def _shape_checked(fun, name):
2173 def f(x):
-> 2174 y = fun(x)
2175 _check_shapes(name, "b", y, b_flat)
2176 return y
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in <lambda>(_, x)
257 lax.custom_linear_solve,
258 lambda x: _matvec_multiply(a, x),
--> 259 solve=lambda _, x: lu_solve(lu_, permutation, x, trans=0),
260 transpose_solve=lambda _, x: lu_solve(lu_, permutation, x, trans=1))
261 if a.ndim == b.ndim + 1:
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in lu_solve(lu, permutation, b, trans)
986 def lu_solve(lu, permutation, b, trans=0):
987 """LU solve with broadcasting."""
--> 988 return _lu_solve(lu, permutation, b, trans)
989
990
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/traceback_util.py in reraise_with_filtered_traceback(*args, **kwargs)
137 def reraise_with_filtered_traceback(*args, **kwargs):
138 try:
--> 139 return fun(*args, **kwargs)
140 except Exception as e:
141 if not is_under_reraiser(e):
/opt/texat-venv/lib/python3.8/site-packages/jax/api.py in f_jitted(*args, **kwargs)
369 return cache_miss(*args, **kwargs)[0] # probably won't return
370 else:
--> 371 return cpp_jitted_f(*args, **kwargs)
372 f_jitted._cpp_jitted_f = cpp_jitted_f
373
/opt/texat-venv/lib/python3.8/site-packages/jax/api.py in cache_miss(*args, **kwargs)
276 _check_arg(arg)
277 flat_fun, out_tree = flatten_fun(f, in_tree)
--> 278 out_flat = xla.xla_call(
279 flat_fun,
280 *args_flat,
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in bind(self, fun, *args, **params)
1227
1228 def bind(self, fun, *args, **params):
-> 1229 return call_bind(self, fun, *args, **params)
1230
1231 def process(self, trace, fun, tracers, params):
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in call_bind(primitive, fun, *args, **params)
1218 tracers = map(top_trace.full_raise, args)
1219 with maybe_new_sublevel(top_trace):
-> 1220 outs = primitive.process(top_trace, fun, tracers, params)
1221 return map(full_lower, apply_todos(env_trace_todo(), outs))
1222
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in process(self, trace, fun, tracers, params)
1230
1231 def process(self, trace, fun, tracers, params):
-> 1232 return trace.process_call(self, fun, tracers, params)
1233
1234 def post_process(self, trace, out_tracers, params):
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/partial_eval.py in process_call(self, call_primitive, f, tracers, params)
1083 def process_call(self, call_primitive, f, tracers, params):
1084 in_avals = [t.aval for t in tracers]
-> 1085 jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(f, self.main, in_avals)
1086 if not jaxpr.eqns:
1087 return core.eval_jaxpr(jaxpr, consts, *tracers)
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/partial_eval.py in trace_to_subjaxpr_dynamic(fun, main, in_avals)
1209 trace = DynamicJaxprTrace(main, core.cur_sublevel())
1210 in_tracers = map(trace.new_arg, in_avals)
-> 1211 ans = fun.call_wrapped(*in_tracers)
1212 out_tracers = map(trace.full_raise, ans)
1213 jaxpr, out_avals, consts = frame.to_jaxpr(in_tracers, out_tracers)
/opt/texat-venv/lib/python3.8/site-packages/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
158
159 try:
--> 160 ans = self.f(*args, **dict(self.params, **kwargs))
161 except:
162 # Some transformations yield from inside context managers, so we have to
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in _lu_solve(lu, permutation, b, trans)
980 "(shape {}) must match"
981 .format(lu.shape, b.shape))
--> 982 x = _lu_solve_core(lu, permutation, b, trans)
983 return x[..., 0] if rhs_vector else x
984
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/vectorize.py in wrapped(*args)
302 vmap_counts = [max(c - 1, 0) for c in vmap_counts]
303 vectorized_func = api.vmap(vectorized_func, in_axes)
--> 304 return vectorized_func(*vec_args)
305
306 return wrapped
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/vectorize.py in wrapped(*args)
133 """Check that output core dimensions match the signature."""
134 def wrapped(*args):
--> 135 out = func(*args)
136 out_shapes = map(jnp.shape, out if isinstance(out, tuple) else [out])
137
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/vectorize.py in new_func(*args)
174 for i, arg in static_args:
175 args.insert(i, arg)
--> 176 return func(*args)
177
178 return new_func, dynamic_args
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in _lu_solve_core(lu, permutation, b, trans)
937 def _lu_solve_core(lu, permutation, b, trans):
938 m = lu.shape[0]
--> 939 x = jnp.reshape(b, (m, -1))
940 if trans == 0:
941 x = x[permutation, :]
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in reshape(a, newshape, order)
1245 def reshape(a, newshape, order="C"):
1246 try:
-> 1247 return a.reshape(newshape, order=order) # forward to method for ndarrays
1248 except AttributeError:
1249 return _reshape(a, newshape, order=order)
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in _reshape_method(a, *newshape, **kwargs)
1290 type(newshape[0]) is not Poly):
1291 newshape = newshape[0]
-> 1292 return _reshape(a, newshape, order=order)
1293
1294
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in _reshape(a, newshape, order)
1266
1267 def _reshape(a, newshape, order="C"):
-> 1268 computed_newshape = _compute_newshape(a, newshape)
1269 if order == "C":
1270 return lax.reshape(a, computed_newshape, None)
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in _compute_newshape(a, newshape)
1260 newshape = [check(size) for size in newshape] if iterable else check(newshape)
1261 if np.any(np.equal(newshape, -1)):
-> 1262 fix = -a.size // (newshape if type(newshape) is Poly else _prod(newshape))
1263 return [d if d != -1 else fix for d in newshape]
1264 else:
ZeroDivisionError: integer division or modulo by zero
|
ZeroDivisionError
|
def inv(a):
if jnp.ndim(a) < 2 or a.shape[-1] != a.shape[-2]:
raise ValueError(f"Argument to inv must have shape [..., n, n], got {a.shape}.")
return solve(
a, lax.broadcast(jnp.eye(a.shape[-1], dtype=lax.dtype(a)), a.shape[:-2])
)
|
def inv(a):
if jnp.ndim(a) < 2 or a.shape[-1] != a.shape[-2]:
raise ValueError(
"Argument to inv must have shape [..., n, n], got {}.".format(jnp.shape(a))
)
return solve(
a, lax.broadcast(jnp.eye(a.shape[-1], dtype=lax.dtype(a)), a.shape[:-2])
)
|
https://github.com/google/jax/issues/5313
|
---------------------------------------------------------------------------
FilteredStackTrace Traceback (most recent call last)
<ipython-input-1-551ceea3fd37> in <module>
2
----> 3 jax.numpy.linalg.inv(jax.numpy.zeros((0, 0)))
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/linalg.py in inv(a)
334 .format(jnp.shape(a)))
--> 335 return solve(
336 a, lax.broadcast(jnp.eye(a.shape[-1], dtype=lax.dtype(a)), a.shape[:-2]))
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/linalg.py in solve(a, b)
449 a, b = _promote_arg_dtypes(jnp.asarray(a), jnp.asarray(b))
--> 450 return lax_linalg._solve(a, b)
451
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in _solve(a, b)
265 # b.shape == [..., m, k]
--> 266 return api.vmap(custom_solve, b.ndim - 1, max(a.ndim, b.ndim) - 1)(b)
267
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in custom_linear_solve(matvec, b, solve, transpose_solve, symmetric)
2182
-> 2183 solve_jaxpr, solve_consts, out_tree = _initial_style_jaxpr(
2184 _shape_checked(partial(solve, matvec), "solve"), in_args_tree, b_avals)
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in _initial_style_jaxpr(fun, in_tree, in_avals)
71 def _initial_style_jaxpr(fun: Callable, in_tree, in_avals):
---> 72 jaxpr, out_avals, consts, out_tree = _initial_style_open_jaxpr(fun, in_tree, in_avals)
73 closed_jaxpr = core.ClosedJaxpr(pe.convert_constvars_jaxpr(jaxpr), ())
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in _initial_style_open_jaxpr(fun, in_tree, in_avals)
66 wrapped_fun, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)
---> 67 jaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(wrapped_fun, in_avals)
68 return jaxpr, out_avals, consts, out_tree()
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in f(x)
2173 def f(x):
-> 2174 y = fun(x)
2175 _check_shapes(name, "b", y, b_flat)
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in <lambda>(_, x)
258 lambda x: _matvec_multiply(a, x),
--> 259 solve=lambda _, x: lu_solve(lu_, permutation, x, trans=0),
260 transpose_solve=lambda _, x: lu_solve(lu_, permutation, x, trans=1))
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in lu_solve(lu, permutation, b, trans)
987 """LU solve with broadcasting."""
--> 988 return _lu_solve(lu, permutation, b, trans)
989
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in _lu_solve(lu, permutation, b, trans)
981 .format(lu.shape, b.shape))
--> 982 x = _lu_solve_core(lu, permutation, b, trans)
983 return x[..., 0] if rhs_vector else x
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/vectorize.py in wrapped(*args)
303 vectorized_func = api.vmap(vectorized_func, in_axes)
--> 304 return vectorized_func(*vec_args)
305
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/vectorize.py in wrapped(*args)
134 def wrapped(*args):
--> 135 out = func(*args)
136 out_shapes = map(jnp.shape, out if isinstance(out, tuple) else [out])
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/vectorize.py in new_func(*args)
175 args.insert(i, arg)
--> 176 return func(*args)
177
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in _lu_solve_core(lu, permutation, b, trans)
938 m = lu.shape[0]
--> 939 x = jnp.reshape(b, (m, -1))
940 if trans == 0:
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in reshape(a, newshape, order)
1246 try:
-> 1247 return a.reshape(newshape, order=order) # forward to method for ndarrays
1248 except AttributeError:
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in _reshape_method(a, *newshape, **kwargs)
1291 newshape = newshape[0]
-> 1292 return _reshape(a, newshape, order=order)
1293
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in _reshape(a, newshape, order)
1267 def _reshape(a, newshape, order="C"):
-> 1268 computed_newshape = _compute_newshape(a, newshape)
1269 if order == "C":
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in _compute_newshape(a, newshape)
1261 if np.any(np.equal(newshape, -1)):
-> 1262 fix = -a.size // (newshape if type(newshape) is Poly else _prod(newshape))
1263 return [d if d != -1 else fix for d in newshape]
FilteredStackTrace: ZeroDivisionError: integer division or modulo by zero
The stack trace above excludes JAX-internal frames.
The following is the original exception that occurred, unmodified.
--------------------
The above exception was the direct cause of the following exception:
ZeroDivisionError Traceback (most recent call last)
<ipython-input-1-551ceea3fd37> in <module>
1 import jax
2
----> 3 jax.numpy.linalg.inv(jax.numpy.zeros((0, 0)))
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/linalg.py in inv(a)
333 raise ValueError("Argument to inv must have shape [..., n, n], got {}."
334 .format(jnp.shape(a)))
--> 335 return solve(
336 a, lax.broadcast(jnp.eye(a.shape[-1], dtype=lax.dtype(a)), a.shape[:-2]))
337
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/traceback_util.py in reraise_with_filtered_traceback(*args, **kwargs)
137 def reraise_with_filtered_traceback(*args, **kwargs):
138 try:
--> 139 return fun(*args, **kwargs)
140 except Exception as e:
141 if not is_under_reraiser(e):
/opt/texat-venv/lib/python3.8/site-packages/jax/api.py in f_jitted(*args, **kwargs)
369 return cache_miss(*args, **kwargs)[0] # probably won't return
370 else:
--> 371 return cpp_jitted_f(*args, **kwargs)
372 f_jitted._cpp_jitted_f = cpp_jitted_f
373
/opt/texat-venv/lib/python3.8/site-packages/jax/api.py in cache_miss(*args, **kwargs)
276 _check_arg(arg)
277 flat_fun, out_tree = flatten_fun(f, in_tree)
--> 278 out_flat = xla.xla_call(
279 flat_fun,
280 *args_flat,
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in bind(self, fun, *args, **params)
1227
1228 def bind(self, fun, *args, **params):
-> 1229 return call_bind(self, fun, *args, **params)
1230
1231 def process(self, trace, fun, tracers, params):
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in call_bind(primitive, fun, *args, **params)
1218 tracers = map(top_trace.full_raise, args)
1219 with maybe_new_sublevel(top_trace):
-> 1220 outs = primitive.process(top_trace, fun, tracers, params)
1221 return map(full_lower, apply_todos(env_trace_todo(), outs))
1222
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in process(self, trace, fun, tracers, params)
1230
1231 def process(self, trace, fun, tracers, params):
-> 1232 return trace.process_call(self, fun, tracers, params)
1233
1234 def post_process(self, trace, out_tracers, params):
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in process_call(self, primitive, f, tracers, params)
596
597 def process_call(self, primitive, f, tracers, params):
--> 598 return primitive.impl(f, *tracers, **params)
599 process_map = process_call
600
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/xla.py in _xla_call_impl(fun, device, backend, name, donated_invars, *args)
567
568 def _xla_call_impl(fun: lu.WrappedFun, *args, device, backend, name, donated_invars):
--> 569 compiled_fun = _xla_callable(fun, device, backend, name, donated_invars,
570 *unsafe_map(arg_spec, args))
571 try:
/opt/texat-venv/lib/python3.8/site-packages/jax/linear_util.py in memoized_fun(fun, *args)
249 fun.populate_stores(stores)
250 else:
--> 251 ans = call(fun, *args)
252 cache[key] = (ans, fun.stores)
253
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/xla.py in _xla_callable(fun, device, backend, name, donated_invars, *arg_specs)
643 abstract_args, arg_devices = unzip2(arg_specs)
644 if config.omnistaging_enabled:
--> 645 jaxpr, out_avals, consts = pe.trace_to_jaxpr_final(fun, abstract_args)
646 if any(isinstance(c, core.Tracer) for c in consts):
647 raise core.UnexpectedTracerError("Encountered an unexpected tracer.")
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/partial_eval.py in trace_to_jaxpr_final(fun, in_avals)
1228 main.source_info = fun_sourceinfo(fun.f) # type: ignore
1229 main.jaxpr_stack = () # type: ignore
-> 1230 jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, main, in_avals)
1231 del main
1232 return jaxpr, out_avals, consts
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/partial_eval.py in trace_to_subjaxpr_dynamic(fun, main, in_avals)
1209 trace = DynamicJaxprTrace(main, core.cur_sublevel())
1210 in_tracers = map(trace.new_arg, in_avals)
-> 1211 ans = fun.call_wrapped(*in_tracers)
1212 out_tracers = map(trace.full_raise, ans)
1213 jaxpr, out_avals, consts = frame.to_jaxpr(in_tracers, out_tracers)
/opt/texat-venv/lib/python3.8/site-packages/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
158
159 try:
--> 160 ans = self.f(*args, **dict(self.params, **kwargs))
161 except:
162 # Some transformations yield from inside context managers, so we have to
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/linalg.py in solve(a, b)
448 def solve(a, b):
449 a, b = _promote_arg_dtypes(jnp.asarray(a), jnp.asarray(b))
--> 450 return lax_linalg._solve(a, b)
451
452
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in _solve(a, b)
264 else:
265 # b.shape == [..., m, k]
--> 266 return api.vmap(custom_solve, b.ndim - 1, max(a.ndim, b.ndim) - 1)(b)
267
268 def _T(x): return jnp.swapaxes(x, -1, -2)
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/traceback_util.py in reraise_with_filtered_traceback(*args, **kwargs)
137 def reraise_with_filtered_traceback(*args, **kwargs):
138 try:
--> 139 return fun(*args, **kwargs)
140 except Exception as e:
141 if not is_under_reraiser(e):
/opt/texat-venv/lib/python3.8/site-packages/jax/api.py in batched_fun(*args)
1184 in_axes_flat = flatten_axes("vmap in_axes", in_tree, in_axes)
1185 _ = _mapped_axis_size(in_tree, args_flat, in_axes_flat, "vmap")
-> 1186 out_flat = batching.batch(flat_fun, args_flat, in_axes_flat,
1187 lambda: flatten_axes("vmap out_axes", out_tree(),
1188 out_axes),
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/batching.py in batch(fun, in_vals, in_dims, out_dim_dests, axis_name)
33 # executes a batched version of `fun` following out_dim_dests
34 batched_fun = batch_fun(fun, in_dims, out_dim_dests, axis_name=axis_name)
---> 35 return batched_fun.call_wrapped(*in_vals)
36
37 @lu.transformation_with_aux
/opt/texat-venv/lib/python3.8/site-packages/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
158
159 try:
--> 160 ans = self.f(*args, **dict(self.params, **kwargs))
161 except:
162 # Some transformations yield from inside context managers, so we have to
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in custom_linear_solve(matvec, b, solve, transpose_solve, symmetric)
2181 _check_tree("matvec", "b", out_tree, tree)
2182
-> 2183 solve_jaxpr, solve_consts, out_tree = _initial_style_jaxpr(
2184 _shape_checked(partial(solve, matvec), "solve"), in_args_tree, b_avals)
2185 _check_tree("solve", "b", out_tree, tree)
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in _initial_style_jaxpr(fun, in_tree, in_avals)
70 @cache()
71 def _initial_style_jaxpr(fun: Callable, in_tree, in_avals):
---> 72 jaxpr, out_avals, consts, out_tree = _initial_style_open_jaxpr(fun, in_tree, in_avals)
73 closed_jaxpr = core.ClosedJaxpr(pe.convert_constvars_jaxpr(jaxpr), ())
74 return closed_jaxpr, consts, out_tree
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in _initial_style_open_jaxpr(fun, in_tree, in_avals)
65 def _initial_style_open_jaxpr(fun: Callable, in_tree, in_avals):
66 wrapped_fun, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)
---> 67 jaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(wrapped_fun, in_avals)
68 return jaxpr, out_avals, consts, out_tree()
69
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/partial_eval.py in trace_to_jaxpr_dynamic(fun, in_avals)
1199 main.source_info = fun_sourceinfo(fun.f) # type: ignore
1200 main.jaxpr_stack = () # type: ignore
-> 1201 jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, main, in_avals)
1202 del main
1203 return jaxpr, out_avals, consts
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/partial_eval.py in trace_to_subjaxpr_dynamic(fun, main, in_avals)
1209 trace = DynamicJaxprTrace(main, core.cur_sublevel())
1210 in_tracers = map(trace.new_arg, in_avals)
-> 1211 ans = fun.call_wrapped(*in_tracers)
1212 out_tracers = map(trace.full_raise, ans)
1213 jaxpr, out_avals, consts = frame.to_jaxpr(in_tracers, out_tracers)
/opt/texat-venv/lib/python3.8/site-packages/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
158
159 try:
--> 160 ans = self.f(*args, **dict(self.params, **kwargs))
161 except:
162 # Some transformations yield from inside context managers, so we have to
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/control_flow.py in f(x)
2172 def _shape_checked(fun, name):
2173 def f(x):
-> 2174 y = fun(x)
2175 _check_shapes(name, "b", y, b_flat)
2176 return y
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in <lambda>(_, x)
257 lax.custom_linear_solve,
258 lambda x: _matvec_multiply(a, x),
--> 259 solve=lambda _, x: lu_solve(lu_, permutation, x, trans=0),
260 transpose_solve=lambda _, x: lu_solve(lu_, permutation, x, trans=1))
261 if a.ndim == b.ndim + 1:
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in lu_solve(lu, permutation, b, trans)
986 def lu_solve(lu, permutation, b, trans=0):
987 """LU solve with broadcasting."""
--> 988 return _lu_solve(lu, permutation, b, trans)
989
990
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/traceback_util.py in reraise_with_filtered_traceback(*args, **kwargs)
137 def reraise_with_filtered_traceback(*args, **kwargs):
138 try:
--> 139 return fun(*args, **kwargs)
140 except Exception as e:
141 if not is_under_reraiser(e):
/opt/texat-venv/lib/python3.8/site-packages/jax/api.py in f_jitted(*args, **kwargs)
369 return cache_miss(*args, **kwargs)[0] # probably won't return
370 else:
--> 371 return cpp_jitted_f(*args, **kwargs)
372 f_jitted._cpp_jitted_f = cpp_jitted_f
373
/opt/texat-venv/lib/python3.8/site-packages/jax/api.py in cache_miss(*args, **kwargs)
276 _check_arg(arg)
277 flat_fun, out_tree = flatten_fun(f, in_tree)
--> 278 out_flat = xla.xla_call(
279 flat_fun,
280 *args_flat,
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in bind(self, fun, *args, **params)
1227
1228 def bind(self, fun, *args, **params):
-> 1229 return call_bind(self, fun, *args, **params)
1230
1231 def process(self, trace, fun, tracers, params):
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in call_bind(primitive, fun, *args, **params)
1218 tracers = map(top_trace.full_raise, args)
1219 with maybe_new_sublevel(top_trace):
-> 1220 outs = primitive.process(top_trace, fun, tracers, params)
1221 return map(full_lower, apply_todos(env_trace_todo(), outs))
1222
/opt/texat-venv/lib/python3.8/site-packages/jax/core.py in process(self, trace, fun, tracers, params)
1230
1231 def process(self, trace, fun, tracers, params):
-> 1232 return trace.process_call(self, fun, tracers, params)
1233
1234 def post_process(self, trace, out_tracers, params):
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/partial_eval.py in process_call(self, call_primitive, f, tracers, params)
1083 def process_call(self, call_primitive, f, tracers, params):
1084 in_avals = [t.aval for t in tracers]
-> 1085 jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(f, self.main, in_avals)
1086 if not jaxpr.eqns:
1087 return core.eval_jaxpr(jaxpr, consts, *tracers)
/opt/texat-venv/lib/python3.8/site-packages/jax/interpreters/partial_eval.py in trace_to_subjaxpr_dynamic(fun, main, in_avals)
1209 trace = DynamicJaxprTrace(main, core.cur_sublevel())
1210 in_tracers = map(trace.new_arg, in_avals)
-> 1211 ans = fun.call_wrapped(*in_tracers)
1212 out_tracers = map(trace.full_raise, ans)
1213 jaxpr, out_avals, consts = frame.to_jaxpr(in_tracers, out_tracers)
/opt/texat-venv/lib/python3.8/site-packages/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
158
159 try:
--> 160 ans = self.f(*args, **dict(self.params, **kwargs))
161 except:
162 # Some transformations yield from inside context managers, so we have to
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in _lu_solve(lu, permutation, b, trans)
980 "(shape {}) must match"
981 .format(lu.shape, b.shape))
--> 982 x = _lu_solve_core(lu, permutation, b, trans)
983 return x[..., 0] if rhs_vector else x
984
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/vectorize.py in wrapped(*args)
302 vmap_counts = [max(c - 1, 0) for c in vmap_counts]
303 vectorized_func = api.vmap(vectorized_func, in_axes)
--> 304 return vectorized_func(*vec_args)
305
306 return wrapped
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/vectorize.py in wrapped(*args)
133 """Check that output core dimensions match the signature."""
134 def wrapped(*args):
--> 135 out = func(*args)
136 out_shapes = map(jnp.shape, out if isinstance(out, tuple) else [out])
137
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/vectorize.py in new_func(*args)
174 for i, arg in static_args:
175 args.insert(i, arg)
--> 176 return func(*args)
177
178 return new_func, dynamic_args
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/lax/linalg.py in _lu_solve_core(lu, permutation, b, trans)
937 def _lu_solve_core(lu, permutation, b, trans):
938 m = lu.shape[0]
--> 939 x = jnp.reshape(b, (m, -1))
940 if trans == 0:
941 x = x[permutation, :]
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in reshape(a, newshape, order)
1245 def reshape(a, newshape, order="C"):
1246 try:
-> 1247 return a.reshape(newshape, order=order) # forward to method for ndarrays
1248 except AttributeError:
1249 return _reshape(a, newshape, order=order)
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in _reshape_method(a, *newshape, **kwargs)
1290 type(newshape[0]) is not Poly):
1291 newshape = newshape[0]
-> 1292 return _reshape(a, newshape, order=order)
1293
1294
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in _reshape(a, newshape, order)
1266
1267 def _reshape(a, newshape, order="C"):
-> 1268 computed_newshape = _compute_newshape(a, newshape)
1269 if order == "C":
1270 return lax.reshape(a, computed_newshape, None)
/opt/texat-venv/lib/python3.8/site-packages/jax/_src/numpy/lax_numpy.py in _compute_newshape(a, newshape)
1260 newshape = [check(size) for size in newshape] if iterable else check(newshape)
1261 if np.any(np.equal(newshape, -1)):
-> 1262 fix = -a.size // (newshape if type(newshape) is Poly else _prod(newshape))
1263 return [d if d != -1 else fix for d in newshape]
1264 else:
ZeroDivisionError: integer division or modulo by zero
|
ZeroDivisionError
|
def _cpp_jit(
fun: F,
static_argnums: Union[int, Iterable[int]] = (),
device: Optional[xc.Device] = None,
backend: Optional[str] = None,
donate_argnums: Union[int, Iterable[int]] = (),
) -> F:
"""An implementation of `jit` that tries to do as much as possible in C++.
The goal of this function is to speed up the time it takes to process the
arguments, find the correct C++ executable, start the transfer of arguments
and schedule the computation.
As long as it does not support all features of the Python implementation
the C++ code will fallback to `_python_jit` when it faces some unsupported
feature.
"""
_check_callable(fun)
static_argnums = _ensure_index_tuple(static_argnums)
donate_argnums = _ensure_index_tuple(donate_argnums)
donate_argnums = rebase_donate_argnums(donate_argnums, static_argnums)
if device is not None and backend is not None:
raise ValueError(
"can't specify both a device and a backend for jit, "
f"got device={device} and backend={backend}."
)
def cache_miss(_, *args, **kwargs):
### This first part is basically the same code as in _python_jit.
# An alternative would be for cache_miss to accept from C++ the arguments
# (dyn_args, donated_invars, args_flat, in_tree), since otherwise we have
# work/code that is redundant between C++ and Python. We can try that later.
if max(static_argnums + donate_argnums, default=-1) >= len(args):
msg = (
"jitted function has static_argnums={}, donate_argnums={} but "
"was called with only {} positional arguments."
)
raise ValueError(msg.format(static_argnums, donate_argnums, len(args)))
f = lu.wrap_init(fun)
if static_argnums:
f, dyn_args = argnums_partial_except(f, static_argnums, args)
else:
dyn_args = args
args_flat, in_tree = tree_flatten((dyn_args, kwargs))
if donate_argnums:
donated_invars = donation_vector(donate_argnums, dyn_args, kwargs)
else:
donated_invars = (False,) * len(args_flat)
for arg in args_flat:
_check_arg(arg)
flat_fun, out_tree = flatten_fun(f, in_tree)
out_flat = xla.xla_call(
flat_fun,
*args_flat,
device=device,
backend=backend,
name=flat_fun.__name__,
donated_invars=donated_invars,
)
out_pytree_def = out_tree()
out = tree_unflatten(out_pytree_def, out_flat)
### Decide whether we can support the C++ fast path
# High level note: The Python tracing mechanism is complex; in particular
# to know whether `jax.jit(f)(x)` will execute or trace, it's not enough to
# inspect the argument x, we actually do need to execute it and look at the
# outputs that could be tracers (if f is capturing `Tracer` by closure).
execute: Optional[functools.partial] = xla._xla_callable.most_recent_entry()
use_fastpath = (
# This is if we have already executed this code-path (most-recent entry
# has been reset to None). Thus, we do not support the fast-path.
execute is not None
and execute.func is xla._execute_compiled # not trivial, not pmap
and
# Not supported: ShardedDeviceArray, DeviceConstant.
all(xla.type_is_device_array(x) for x in out_flat)
and
# TODO(mattjj): Add support for lazy-expression.
# If the input is a DeviceArray, then it should have a trivial LazyExpr.
all(
type(x) is not xla.DeviceArray or xla.lazy.is_trivial(x._lazy_expr)
for x in args_flat
)
)
### If we can use the fastpath, we return required info to the caller.
if use_fastpath:
xla_executable, _, result_handlers = execute.args
sticky_device = None
avals = []
lazy_exprs = []
for result_handler in result_handlers:
aval, sticky_device, lazy_expr = result_handler.args
avals.append(aval)
lazy_exprs.append(None if xla.lazy.is_trivial(lazy_expr) else lazy_expr)
assert len(avals) == len(out_flat)
if version >= (0, 1, 58):
fastpath_data = (
xla_executable,
out_pytree_def,
sticky_device,
avals,
lazy_exprs,
)
else:
fastpath_data = (xla_executable, result_handlers, out_pytree_def)
else:
fastpath_data = None
return out, fastpath_data
def get_device_info():
"""Backends do not exist before __main__ is being executed."""
committed_to_device = device is not None or backend is not None
if device is not None:
default_device = device
else:
backend_ = xb.get_backend(backend)
default_device = backend_.get_default_device_assignment(1)[0]
return _BackendAndDeviceInfo(default_device, committed_to_device)
def get_jax_enable_x64():
"""Returns the value of the flag after GoogleInit.
We must wait until flags have been parsed (in particular for top-level
functions decorated with jax.jit), so we delay inspecting the value
of the jax_enable_x64 flag until JIT time.
"""
return FLAGS.jax_enable_x64
def get_jax_disable_jit_flag():
"""Returns the value of the `jax_disable_jit` flag.
Both a flag and the `disable_jit` context manager can disable jit. We access
the flag only once, when jitting the function, and the context manager
modifies a C++ thread-local value.
"""
return config.read("jax_disable_jit")
static_argnums_ = (0,) + tuple(i + 1 for i in static_argnums)
cpp_jitted_f = jax_jit.jit(
fun,
cache_miss,
get_device_info,
get_jax_enable_x64,
get_jax_disable_jit_flag,
static_argnums_,
)
# TODO(mattjj): make cpp callable follow descriptor protocol for bound methods
@wraps(fun)
@api_boundary
def f_jitted(*args, **kwargs):
context = getattr(
core.thread_local_state.trace_state.trace_stack, "dynamic", None
)
# TODO(jblespiau): Move this to C++.
if FLAGS.jax_debug_nans and not _jit_is_disabled():
device_arrays = cpp_jitted_f(context, *args, **kwargs)
try:
xla.check_nans(
xla.xla_call_p,
[
da.device_buffer
for da in tree_leaves(device_arrays)
if hasattr(da, "device_buffer")
],
)
return device_arrays
except FloatingPointError:
assert FLAGS.jax_debug_nans # compiled_fun can only raise in this case
print(
"Invalid nan value encountered in the output of a C++-jit "
"function. Calling the de-optimized version."
)
return cache_miss(context, *args, **kwargs)[0] # probably won't return
elif _jit_is_disabled():
return cpp_jitted_f(*args, **kwargs)
else:
return cpp_jitted_f(context, *args, **kwargs)
f_jitted._cpp_jitted_f = cpp_jitted_f
return f_jitted
|
def _cpp_jit(
fun: F,
static_argnums: Union[int, Iterable[int]] = (),
device: Optional[xc.Device] = None,
backend: Optional[str] = None,
donate_argnums: Union[int, Iterable[int]] = (),
) -> F:
"""An implementation of `jit` that tries to do as much as possible in C++.
The goal of this function is to speed up the time it takes to process the
arguments, find the correct C++ executable, start the transfer of arguments
and schedule the computation.
As long as it does not support all features of the Python implementation
the C++ code will fallback to `_python_jit` when it faces some unsupported
feature.
"""
_check_callable(fun)
static_argnums = _ensure_index_tuple(static_argnums)
donate_argnums = _ensure_index_tuple(donate_argnums)
donate_argnums = rebase_donate_argnums(donate_argnums, static_argnums)
if device is not None and backend is not None:
raise ValueError(
"can't specify both a device and a backend for jit, "
f"got device={device} and backend={backend}."
)
def cache_miss(_, *args, **kwargs):
### This first part is basically the same code as in _python_jit.
# An alternative would be for cache_miss to accept from C++ the arguments
# (dyn_args, donated_invars, args_flat, in_tree), since otherwise we have
# work/code that is redundant between C++ and Python. We can try that later.
if max(static_argnums + donate_argnums, default=-1) >= len(args):
raise ValueError(
f"jitted function has static_argnums={static_argnums}, "
f"donate_argnums={donate_argnums} but "
f"was called with only {len(args)} positional arguments."
)
f = lu.wrap_init(fun)
if static_argnums:
f, dyn_args = argnums_partial_except(f, static_argnums, args)
else:
dyn_args = args
args_flat, in_tree = tree_flatten((dyn_args, kwargs))
if donate_argnums:
donated_invars = donation_vector(donate_argnums, dyn_args, kwargs)
else:
donated_invars = (False,) * len(args_flat)
for arg in args_flat:
_check_arg(arg)
flat_fun, out_tree = flatten_fun(f, in_tree)
out_flat = xla.xla_call(
flat_fun,
*args_flat,
device=device,
backend=backend,
name=flat_fun.__name__,
donated_invars=donated_invars,
)
out_pytree_def = out_tree()
out = tree_unflatten(out_pytree_def, out_flat)
### Decide whether we can support the C++ fast path
# High level note: The Python tracing mechanism is complex; in particular
# to know whether `jax.jit(f)(x)` will execute or trace, it's not enough to
# inspect the argument x, we actually do need to execute it and look at the
# outputs that could be tracers (if f is capturing `Tracer` by closure).
execute: Optional[functools.partial] = xla._xla_callable.most_recent_entry()
use_fastpath = (
# This is if we have already executed this code-path (most-recent entry
# has been reset to None). Thus, we do not support the fast-path.
execute is not None
and execute.func is xla._execute_compiled # not trivial, not pmap
and
# Not supported: ShardedDeviceArray, DeviceConstant.
all(xla.type_is_device_array(x) for x in out_flat)
and
# TODO(mattjj): Add support for lazy-expression.
# If the input is a DeviceArray, then it should have a trivial LazyExpr.
all(
type(x) is not xla.DeviceArray or xla.lazy.is_trivial(x._lazy_expr)
for x in args_flat
)
)
### If we can use the fastpath, we return required info to the caller.
if use_fastpath:
xla_executable, _, result_handlers = execute.args
sticky_device = None
avals = []
lazy_exprs = []
for result_handler in result_handlers:
aval, sticky_device, lazy_expr = result_handler.args
avals.append(aval)
lazy_exprs.append(None if xla.lazy.is_trivial(lazy_expr) else lazy_expr)
assert len(avals) == len(out_flat)
if version >= (0, 1, 58):
fastpath_data = (
xla_executable,
out_pytree_def,
sticky_device,
avals,
lazy_exprs,
)
else:
fastpath_data = (xla_executable, result_handlers, out_pytree_def)
else:
fastpath_data = None
return out, fastpath_data
def get_device_info():
"""Backends do not exist before __main__ is being executed."""
committed_to_device = device is not None or backend is not None
if device is not None:
default_device = device
else:
backend_ = xb.get_backend(backend)
default_device = backend_.get_default_device_assignment(1)[0]
return _BackendAndDeviceInfo(default_device, committed_to_device)
def get_jax_enable_x64():
"""Returns the value of the flag after GoogleInit.
We must wait until flags have been parsed (in particular for top-level
functions decorated with jax.jit), so we delay inspecting the value
of the jax_enable_x64 flag until JIT time.
"""
return FLAGS.jax_enable_x64
def get_jax_disable_jit_flag():
"""Returns the value of the `jax_disable_jit` flag.
Both a flag and the `disable_jit` context manager can disable jit. We access
the flag only once, when jitting the function, and the context manager
modifies a C++ thread-local value.
"""
return config.read("jax_disable_jit")
static_argnums_ = (0,) + tuple(i + 1 for i in static_argnums)
cpp_jitted_f = jax_jit.jit(
fun,
cache_miss,
get_device_info,
get_jax_enable_x64,
get_jax_disable_jit_flag,
static_argnums_,
)
# TODO(mattjj): make cpp callable follow descriptor protocol for bound methods
@wraps(fun)
@api_boundary
def f_jitted(*args, **kwargs):
context = getattr(
core.thread_local_state.trace_state.trace_stack, "dynamic", None
)
# TODO(jblespiau): Move this to C++.
if FLAGS.jax_debug_nans and not _jit_is_disabled():
device_arrays = cpp_jitted_f(context, *args, **kwargs)
try:
xla.check_nans(
xla.xla_call_p,
[
da.device_buffer
for da in tree_leaves(device_arrays)
if hasattr(da, "device_buffer")
],
)
return device_arrays
except FloatingPointError:
assert FLAGS.jax_debug_nans # compiled_fun can only raise in this case
print(
"Invalid nan value encountered in the output of a C++-jit "
"function. Calling the de-optimized version."
)
return cache_miss(context, *args, **kwargs)[0] # probably won't return
elif _jit_is_disabled():
return cpp_jitted_f(*args, **kwargs)
else:
return cpp_jitted_f(context, *args, **kwargs)
f_jitted._cpp_jitted_f = cpp_jitted_f
return f_jitted
|
https://github.com/google/jax/issues/5190
|
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-42-f8e638fc2bb6> in <module>
----> 1 _get_pairwise_frequencies(data)
<ipython-input-30-43adeb39c76c> in _get_pairwise_frequencies(data, crosstab)
25 label_map[each] = lbl
26 if not crosstab:
---> 27 freq = coocurrence_helper(pairs = pair.values, label_map=label_map)
28 return csr_matrix((freq / freq.sum(1).ravel()).astype(np.float32))
29 else:
~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/jax/api.py in f_jitted(*args, **kwargs)
369 return cache_miss(*args, **kwargs)[0] # probably won't return
370 else:
--> 371 return cpp_jitted_f(*args, **kwargs)
372 f_jitted._cpp_jitted_f = cpp_jitted_f
373
ValueError: vector::reserve
|
ValueError
|
def cache_miss(_, *args, **kwargs):
### This first part is basically the same code as in _python_jit.
# An alternative would be for cache_miss to accept from C++ the arguments
# (dyn_args, donated_invars, args_flat, in_tree), since otherwise we have
# work/code that is redundant between C++ and Python. We can try that later.
if max(static_argnums + donate_argnums, default=-1) >= len(args):
msg = (
"jitted function has static_argnums={}, donate_argnums={} but "
"was called with only {} positional arguments."
)
raise ValueError(msg.format(static_argnums, donate_argnums, len(args)))
f = lu.wrap_init(fun)
if static_argnums:
f, dyn_args = argnums_partial_except(f, static_argnums, args)
else:
dyn_args = args
args_flat, in_tree = tree_flatten((dyn_args, kwargs))
if donate_argnums:
donated_invars = donation_vector(donate_argnums, dyn_args, kwargs)
else:
donated_invars = (False,) * len(args_flat)
for arg in args_flat:
_check_arg(arg)
flat_fun, out_tree = flatten_fun(f, in_tree)
out_flat = xla.xla_call(
flat_fun,
*args_flat,
device=device,
backend=backend,
name=flat_fun.__name__,
donated_invars=donated_invars,
)
out_pytree_def = out_tree()
out = tree_unflatten(out_pytree_def, out_flat)
### Decide whether we can support the C++ fast path
# High level note: The Python tracing mechanism is complex; in particular
# to know whether `jax.jit(f)(x)` will execute or trace, it's not enough to
# inspect the argument x, we actually do need to execute it and look at the
# outputs that could be tracers (if f is capturing `Tracer` by closure).
execute: Optional[functools.partial] = xla._xla_callable.most_recent_entry()
use_fastpath = (
# This is if we have already executed this code-path (most-recent entry
# has been reset to None). Thus, we do not support the fast-path.
execute is not None
and execute.func is xla._execute_compiled # not trivial, not pmap
and
# Not supported: ShardedDeviceArray, DeviceConstant.
all(xla.type_is_device_array(x) for x in out_flat)
and
# TODO(mattjj): Add support for lazy-expression.
# If the input is a DeviceArray, then it should have a trivial LazyExpr.
all(
type(x) is not xla.DeviceArray or xla.lazy.is_trivial(x._lazy_expr)
for x in args_flat
)
)
### If we can use the fastpath, we return required info to the caller.
if use_fastpath:
xla_executable, _, result_handlers = execute.args
sticky_device = None
avals = []
lazy_exprs = []
for result_handler in result_handlers:
aval, sticky_device, lazy_expr = result_handler.args
avals.append(aval)
lazy_exprs.append(None if xla.lazy.is_trivial(lazy_expr) else lazy_expr)
assert len(avals) == len(out_flat)
if version >= (0, 1, 58):
fastpath_data = (
xla_executable,
out_pytree_def,
sticky_device,
avals,
lazy_exprs,
)
else:
fastpath_data = (xla_executable, result_handlers, out_pytree_def)
else:
fastpath_data = None
return out, fastpath_data
|
def cache_miss(_, *args, **kwargs):
### This first part is basically the same code as in _python_jit.
# An alternative would be for cache_miss to accept from C++ the arguments
# (dyn_args, donated_invars, args_flat, in_tree), since otherwise we have
# work/code that is redundant between C++ and Python. We can try that later.
if max(static_argnums + donate_argnums, default=-1) >= len(args):
raise ValueError(
f"jitted function has static_argnums={static_argnums}, "
f"donate_argnums={donate_argnums} but "
f"was called with only {len(args)} positional arguments."
)
f = lu.wrap_init(fun)
if static_argnums:
f, dyn_args = argnums_partial_except(f, static_argnums, args)
else:
dyn_args = args
args_flat, in_tree = tree_flatten((dyn_args, kwargs))
if donate_argnums:
donated_invars = donation_vector(donate_argnums, dyn_args, kwargs)
else:
donated_invars = (False,) * len(args_flat)
for arg in args_flat:
_check_arg(arg)
flat_fun, out_tree = flatten_fun(f, in_tree)
out_flat = xla.xla_call(
flat_fun,
*args_flat,
device=device,
backend=backend,
name=flat_fun.__name__,
donated_invars=donated_invars,
)
out_pytree_def = out_tree()
out = tree_unflatten(out_pytree_def, out_flat)
### Decide whether we can support the C++ fast path
# High level note: The Python tracing mechanism is complex; in particular
# to know whether `jax.jit(f)(x)` will execute or trace, it's not enough to
# inspect the argument x, we actually do need to execute it and look at the
# outputs that could be tracers (if f is capturing `Tracer` by closure).
execute: Optional[functools.partial] = xla._xla_callable.most_recent_entry()
use_fastpath = (
# This is if we have already executed this code-path (most-recent entry
# has been reset to None). Thus, we do not support the fast-path.
execute is not None
and execute.func is xla._execute_compiled # not trivial, not pmap
and
# Not supported: ShardedDeviceArray, DeviceConstant.
all(xla.type_is_device_array(x) for x in out_flat)
and
# TODO(mattjj): Add support for lazy-expression.
# If the input is a DeviceArray, then it should have a trivial LazyExpr.
all(
type(x) is not xla.DeviceArray or xla.lazy.is_trivial(x._lazy_expr)
for x in args_flat
)
)
### If we can use the fastpath, we return required info to the caller.
if use_fastpath:
xla_executable, _, result_handlers = execute.args
sticky_device = None
avals = []
lazy_exprs = []
for result_handler in result_handlers:
aval, sticky_device, lazy_expr = result_handler.args
avals.append(aval)
lazy_exprs.append(None if xla.lazy.is_trivial(lazy_expr) else lazy_expr)
assert len(avals) == len(out_flat)
if version >= (0, 1, 58):
fastpath_data = (
xla_executable,
out_pytree_def,
sticky_device,
avals,
lazy_exprs,
)
else:
fastpath_data = (xla_executable, result_handlers, out_pytree_def)
else:
fastpath_data = None
return out, fastpath_data
|
https://github.com/google/jax/issues/5190
|
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-42-f8e638fc2bb6> in <module>
----> 1 _get_pairwise_frequencies(data)
<ipython-input-30-43adeb39c76c> in _get_pairwise_frequencies(data, crosstab)
25 label_map[each] = lbl
26 if not crosstab:
---> 27 freq = coocurrence_helper(pairs = pair.values, label_map=label_map)
28 return csr_matrix((freq / freq.sum(1).ravel()).astype(np.float32))
29 else:
~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/jax/api.py in f_jitted(*args, **kwargs)
369 return cache_miss(*args, **kwargs)[0] # probably won't return
370 else:
--> 371 return cpp_jitted_f(*args, **kwargs)
372 f_jitted._cpp_jitted_f = cpp_jitted_f
373
ValueError: vector::reserve
|
ValueError
|
def _cpp_jit(
fun: Callable,
static_argnums: Union[int, Iterable[int]] = (),
device=None,
backend: Optional[str] = None,
donate_argnums: Union[int, Iterable[int]] = (),
) -> Callable:
"""An implementation of `jit` that tries to do as much as possible in C++.
The goal of this function is to speed up the time it takes to process the
arguments, find the correct C++ executable, start the transfer of arguments
and schedule the computation.
As long as it does not support all features of the Python implementation
the C++ code will fallback to `_python_jit` when it faces some unsupported
feature.
"""
_check_callable(fun)
static_argnums = _ensure_index_tuple(static_argnums)
donate_argnums = _ensure_index_tuple(donate_argnums)
donate_argnums = rebase_donate_argnums(donate_argnums, static_argnums)
if device is not None and backend is not None:
raise ValueError(
"can't specify both a device and a backend for jit, "
"got device={} and backend={}".format(device, backend)
)
def cache_miss(*args, **kwargs):
### This first part is basically the same code as in _python_jit.
# An alternative would be for cache_miss to accept from C++ the arguments
# (dyn_args, donated_invars, args_flat, in_tree), since otherwise we have
# work/code that is redundant between C++ and Python. We can try that later.
if max(static_argnums + donate_argnums, default=-1) >= len(args):
msg = (
"jitted function has static_argnums={}, donate_argnums={} but "
"was called with only {} positional arguments."
)
raise ValueError(msg.format(static_argnums, donate_argnums, len(args)))
f = lu.wrap_init(fun)
if static_argnums:
f, dyn_args = argnums_partial_except(f, static_argnums, args)
else:
dyn_args = args
args_flat, in_tree = tree_flatten((dyn_args, kwargs))
if donate_argnums:
donated_invars = donation_vector(donate_argnums, dyn_args, kwargs)
else:
donated_invars = (False,) * len(args_flat)
for arg in args_flat:
_check_arg(arg)
flat_fun, out_tree = flatten_fun(f, in_tree)
out_flat = xla.xla_call(
flat_fun,
*args_flat,
device=device,
backend=backend,
name=flat_fun.__name__,
donated_invars=donated_invars,
)
out_pytree_def = out_tree()
out = tree_unflatten(out_pytree_def, out_flat)
### Decide whether we can support the C++ fast path
# High level note: The Python tracing mechanism is complex; in particular
# to know whether `jax.jit(f)(x)` will execute or trace, it's not enough to
# inspect the argument x, we actually do need to execute it and look at the
# outputs that could be tracers (if f is capturing `Tracer` by closure).
execute: Optional[functools.partial] = xla._xla_callable.most_recent_entry()
use_fastpath = (
# This is if we have already executed this code-path (most-recent entry
# has been reset to None). Thus, we do not support the fast-path.
execute is not None
and execute.func is xla._execute_compiled # not trivial, not pmap
and
# Not supported: ShardedDeviceArray, DeviceConstant.
all(xla.type_is_device_array(x) for x in out_flat)
and
# TODO(mattjj): Add support for lazy-expression.
# If the input is a DeviceArray, then it should have a trivial LazyExpr.
all(
type(x) is not xla.DeviceArray or xla.lazy.is_trivial(x._lazy_expr)
for x in args_flat
)
)
### If we can use the fastpath, we return required info to the caller.
if use_fastpath:
xla_executable, _, result_handlers = execute.args
sticky_device = None
avals = []
lazy_exprs = []
for result_handler in result_handlers:
aval, sticky_device, lazy_expr = result_handler.args
avals.append(aval)
lazy_exprs.append(None if xla.lazy.is_trivial(lazy_expr) else lazy_expr)
assert len(avals) == len(out_flat)
if version >= (0, 1, 58):
fastpath_data = (
xla_executable,
out_pytree_def,
sticky_device,
avals,
lazy_exprs,
)
else:
fastpath_data = (xla_executable, result_handlers, out_pytree_def)
else:
fastpath_data = None
return out, fastpath_data
def get_device_info():
"""Backends do not exist before __main__ is being executed."""
committed_to_device = device is not None or backend is not None
if device is not None:
default_device = device
else:
backend_ = xb.get_backend(backend)
default_device = backend_.get_default_device_assignment(1)[0]
return _BackendAndDeviceInfo(default_device, committed_to_device)
def get_jax_enable_x64():
"""Returns the value of the flag after GoogleInit.
We must wait until flags have been parsed (in particular for top-level
functions decorated with jax.jit), so we delay inspecting the value
of the jax_enable_x64 flag until JIT time.
"""
return FLAGS.jax_enable_x64
def get_jax_disable_jit_flag():
"""Returns the value of the `jax_disable_jit` flag.
Both a flag and the `disable_jit` context manager can disable jit. We access
the flag only once, when jitting the function, and the context manager
modifies a C++ thread-local value.
"""
return config.read("jax_disable_jit")
cpp_jitted_f = jax_jit.jit(
fun,
cache_miss,
get_device_info,
get_jax_enable_x64,
get_jax_disable_jit_flag,
static_argnums,
)
# TODO(mattjj): make cpp callable follow descriptor protocol for bound methods
@wraps(fun)
@api_boundary
def f_jitted(*args, **kwargs):
# TODO(jblespiau): Move this to C++.
if FLAGS.jax_debug_nans and not _jit_is_disabled():
device_arrays = cpp_jitted_f(*args, **kwargs)
try:
xla.check_nans(
xla.xla_call_p,
[
da.device_buffer
for da in tree_leaves(device_arrays)
if hasattr(da, "device_buffer")
],
)
return device_arrays
except FloatingPointError:
assert FLAGS.jax_debug_nans # compiled_fun can only raise in this case
print(
"Invalid nan value encountered in the output of a C++-jit "
"function. Calling the de-optimized version."
)
return cache_miss(*args, **kwargs)[0] # probably won't return
else:
return cpp_jitted_f(*args, **kwargs)
f_jitted._cpp_jitted_f = cpp_jitted_f
return f_jitted
|
def _cpp_jit(
fun: Callable,
static_argnums: Union[int, Iterable[int]] = (),
device=None,
backend: Optional[str] = None,
donate_argnums: Union[int, Iterable[int]] = (),
) -> Callable:
"""An implementation of `jit` that tries to do as much as possible in C++.
The goal of this function is to speed up the time it takes to process the
arguments, find the correct C++ executable, start the transfer of arguments
and schedule the computation.
As long as it does not support all features of the Python implementation
the C++ code will fallback to `_python_jit` when it faces some unsupported
feature.
"""
_check_callable(fun)
static_argnums = _ensure_index_tuple(static_argnums)
donate_argnums = _ensure_index_tuple(donate_argnums)
donate_argnums = rebase_donate_argnums(donate_argnums, static_argnums)
if device is not None and backend is not None:
raise ValueError(
"can't specify both a device and a backend for jit, "
"got device={} and backend={}".format(device, backend)
)
def cache_miss(*args, **kwargs):
### This first part is basically the same code as in _python_jit.
# An alternative would be for cache_miss to accept from C++ the arguments
# (dyn_args, donated_invars, args_flat, in_tree), since otherwise we have
# work/code that is redundant between C++ and Python. We can try that later.
f = lu.wrap_init(fun)
if static_argnums:
f, dyn_args = argnums_partial_except(f, static_argnums, args)
else:
dyn_args = args
args_flat, in_tree = tree_flatten((dyn_args, kwargs))
if donate_argnums:
donated_invars = donation_vector(donate_argnums, dyn_args, kwargs)
else:
donated_invars = (False,) * len(args_flat)
for arg in args_flat:
_check_arg(arg)
flat_fun, out_tree = flatten_fun(f, in_tree)
out_flat = xla.xla_call(
flat_fun,
*args_flat,
device=device,
backend=backend,
name=flat_fun.__name__,
donated_invars=donated_invars,
)
out_pytree_def = out_tree()
out = tree_unflatten(out_pytree_def, out_flat)
### Decide whether we can support the C++ fast path
# High level note: The Python tracing mechanism is complex; in particular
# to know whether `jax.jit(f)(x)` will execute or trace, it's not enough to
# inspect the argument x, we actually do need to execute it and look at the
# outputs that could be tracers (if f is capturing `Tracer` by closure).
execute: Optional[functools.partial] = xla._xla_callable.most_recent_entry()
use_fastpath = (
# This is if we have already executed this code-path (most-recent entry
# has been reset to None). Thus, we do not support the fast-path.
execute is not None
and execute.func is xla._execute_compiled # not trivial, not pmap
and
# Not supported: ShardedDeviceArray, DeviceConstant.
all(xla.type_is_device_array(x) for x in out_flat)
and
# TODO(mattjj): Add support for lazy-expression.
# If the input is a DeviceArray, then it should have a trivial LazyExpr.
all(
type(x) is not xla.DeviceArray or xla.lazy.is_trivial(x._lazy_expr)
for x in args_flat
)
)
### If we can use the fastpath, we return required info to the caller.
if use_fastpath:
xla_executable, _, result_handlers = execute.args
sticky_device = None
avals = []
lazy_exprs = []
for result_handler in result_handlers:
aval, sticky_device, lazy_expr = result_handler.args
avals.append(aval)
lazy_exprs.append(None if xla.lazy.is_trivial(lazy_expr) else lazy_expr)
assert len(avals) == len(out_flat)
if version >= (0, 1, 58):
fastpath_data = (
xla_executable,
out_pytree_def,
sticky_device,
avals,
lazy_exprs,
)
else:
fastpath_data = (xla_executable, result_handlers, out_pytree_def)
else:
fastpath_data = None
return out, fastpath_data
def get_device_info():
"""Backends do not exist before __main__ is being executed."""
committed_to_device = device is not None or backend is not None
if device is not None:
default_device = device
else:
backend_ = xb.get_backend(backend)
default_device = backend_.get_default_device_assignment(1)[0]
return _BackendAndDeviceInfo(default_device, committed_to_device)
def get_jax_enable_x64():
"""Returns the value of the flag after GoogleInit.
We must wait until flags have been parsed (in particular for top-level
functions decorated with jax.jit), so we delay inspecting the value
of the jax_enable_x64 flag until JIT time.
"""
return FLAGS.jax_enable_x64
def get_jax_disable_jit_flag():
"""Returns the value of the `jax_disable_jit` flag.
Both a flag and the `disable_jit` context manager can disable jit. We access
the flag only once, when jitting the function, and the context manager
modifies a C++ thread-local value.
"""
return config.read("jax_disable_jit")
cpp_jitted_f = jax_jit.jit(
fun,
cache_miss,
get_device_info,
get_jax_enable_x64,
get_jax_disable_jit_flag,
static_argnums,
)
# TODO(mattjj): make cpp callable follow descriptor protocol for bound methods
@wraps(fun)
@api_boundary
def f_jitted(*args, **kwargs):
# TODO(jblespiau): Move this to C++.
if FLAGS.jax_debug_nans and not _jit_is_disabled():
device_arrays = cpp_jitted_f(*args, **kwargs)
try:
xla.check_nans(
xla.xla_call_p,
[
da.device_buffer
for da in tree_leaves(device_arrays)
if hasattr(da, "device_buffer")
],
)
return device_arrays
except FloatingPointError:
assert FLAGS.jax_debug_nans # compiled_fun can only raise in this case
print(
"Invalid nan value encountered in the output of a C++-jit "
"function. Calling the de-optimized version."
)
return cache_miss(*args, **kwargs)[0] # probably won't return
else:
return cpp_jitted_f(*args, **kwargs)
f_jitted._cpp_jitted_f = cpp_jitted_f
return f_jitted
|
https://github.com/google/jax/issues/5190
|
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-42-f8e638fc2bb6> in <module>
----> 1 _get_pairwise_frequencies(data)
<ipython-input-30-43adeb39c76c> in _get_pairwise_frequencies(data, crosstab)
25 label_map[each] = lbl
26 if not crosstab:
---> 27 freq = coocurrence_helper(pairs = pair.values, label_map=label_map)
28 return csr_matrix((freq / freq.sum(1).ravel()).astype(np.float32))
29 else:
~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/jax/api.py in f_jitted(*args, **kwargs)
369 return cache_miss(*args, **kwargs)[0] # probably won't return
370 else:
--> 371 return cpp_jitted_f(*args, **kwargs)
372 f_jitted._cpp_jitted_f = cpp_jitted_f
373
ValueError: vector::reserve
|
ValueError
|
def cache_miss(*args, **kwargs):
### This first part is basically the same code as in _python_jit.
# An alternative would be for cache_miss to accept from C++ the arguments
# (dyn_args, donated_invars, args_flat, in_tree), since otherwise we have
# work/code that is redundant between C++ and Python. We can try that later.
if max(static_argnums + donate_argnums, default=-1) >= len(args):
msg = (
"jitted function has static_argnums={}, donate_argnums={} but "
"was called with only {} positional arguments."
)
raise ValueError(msg.format(static_argnums, donate_argnums, len(args)))
f = lu.wrap_init(fun)
if static_argnums:
f, dyn_args = argnums_partial_except(f, static_argnums, args)
else:
dyn_args = args
args_flat, in_tree = tree_flatten((dyn_args, kwargs))
if donate_argnums:
donated_invars = donation_vector(donate_argnums, dyn_args, kwargs)
else:
donated_invars = (False,) * len(args_flat)
for arg in args_flat:
_check_arg(arg)
flat_fun, out_tree = flatten_fun(f, in_tree)
out_flat = xla.xla_call(
flat_fun,
*args_flat,
device=device,
backend=backend,
name=flat_fun.__name__,
donated_invars=donated_invars,
)
out_pytree_def = out_tree()
out = tree_unflatten(out_pytree_def, out_flat)
### Decide whether we can support the C++ fast path
# High level note: The Python tracing mechanism is complex; in particular
# to know whether `jax.jit(f)(x)` will execute or trace, it's not enough to
# inspect the argument x, we actually do need to execute it and look at the
# outputs that could be tracers (if f is capturing `Tracer` by closure).
execute: Optional[functools.partial] = xla._xla_callable.most_recent_entry()
use_fastpath = (
# This is if we have already executed this code-path (most-recent entry
# has been reset to None). Thus, we do not support the fast-path.
execute is not None
and execute.func is xla._execute_compiled # not trivial, not pmap
and
# Not supported: ShardedDeviceArray, DeviceConstant.
all(xla.type_is_device_array(x) for x in out_flat)
and
# TODO(mattjj): Add support for lazy-expression.
# If the input is a DeviceArray, then it should have a trivial LazyExpr.
all(
type(x) is not xla.DeviceArray or xla.lazy.is_trivial(x._lazy_expr)
for x in args_flat
)
)
### If we can use the fastpath, we return required info to the caller.
if use_fastpath:
xla_executable, _, result_handlers = execute.args
sticky_device = None
avals = []
lazy_exprs = []
for result_handler in result_handlers:
aval, sticky_device, lazy_expr = result_handler.args
avals.append(aval)
lazy_exprs.append(None if xla.lazy.is_trivial(lazy_expr) else lazy_expr)
assert len(avals) == len(out_flat)
if version >= (0, 1, 58):
fastpath_data = (
xla_executable,
out_pytree_def,
sticky_device,
avals,
lazy_exprs,
)
else:
fastpath_data = (xla_executable, result_handlers, out_pytree_def)
else:
fastpath_data = None
return out, fastpath_data
|
def cache_miss(*args, **kwargs):
### This first part is basically the same code as in _python_jit.
# An alternative would be for cache_miss to accept from C++ the arguments
# (dyn_args, donated_invars, args_flat, in_tree), since otherwise we have
# work/code that is redundant between C++ and Python. We can try that later.
f = lu.wrap_init(fun)
if static_argnums:
f, dyn_args = argnums_partial_except(f, static_argnums, args)
else:
dyn_args = args
args_flat, in_tree = tree_flatten((dyn_args, kwargs))
if donate_argnums:
donated_invars = donation_vector(donate_argnums, dyn_args, kwargs)
else:
donated_invars = (False,) * len(args_flat)
for arg in args_flat:
_check_arg(arg)
flat_fun, out_tree = flatten_fun(f, in_tree)
out_flat = xla.xla_call(
flat_fun,
*args_flat,
device=device,
backend=backend,
name=flat_fun.__name__,
donated_invars=donated_invars,
)
out_pytree_def = out_tree()
out = tree_unflatten(out_pytree_def, out_flat)
### Decide whether we can support the C++ fast path
# High level note: The Python tracing mechanism is complex; in particular
# to know whether `jax.jit(f)(x)` will execute or trace, it's not enough to
# inspect the argument x, we actually do need to execute it and look at the
# outputs that could be tracers (if f is capturing `Tracer` by closure).
execute: Optional[functools.partial] = xla._xla_callable.most_recent_entry()
use_fastpath = (
# This is if we have already executed this code-path (most-recent entry
# has been reset to None). Thus, we do not support the fast-path.
execute is not None
and execute.func is xla._execute_compiled # not trivial, not pmap
and
# Not supported: ShardedDeviceArray, DeviceConstant.
all(xla.type_is_device_array(x) for x in out_flat)
and
# TODO(mattjj): Add support for lazy-expression.
# If the input is a DeviceArray, then it should have a trivial LazyExpr.
all(
type(x) is not xla.DeviceArray or xla.lazy.is_trivial(x._lazy_expr)
for x in args_flat
)
)
### If we can use the fastpath, we return required info to the caller.
if use_fastpath:
xla_executable, _, result_handlers = execute.args
sticky_device = None
avals = []
lazy_exprs = []
for result_handler in result_handlers:
aval, sticky_device, lazy_expr = result_handler.args
avals.append(aval)
lazy_exprs.append(None if xla.lazy.is_trivial(lazy_expr) else lazy_expr)
assert len(avals) == len(out_flat)
if version >= (0, 1, 58):
fastpath_data = (
xla_executable,
out_pytree_def,
sticky_device,
avals,
lazy_exprs,
)
else:
fastpath_data = (xla_executable, result_handlers, out_pytree_def)
else:
fastpath_data = None
return out, fastpath_data
|
https://github.com/google/jax/issues/5190
|
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-42-f8e638fc2bb6> in <module>
----> 1 _get_pairwise_frequencies(data)
<ipython-input-30-43adeb39c76c> in _get_pairwise_frequencies(data, crosstab)
25 label_map[each] = lbl
26 if not crosstab:
---> 27 freq = coocurrence_helper(pairs = pair.values, label_map=label_map)
28 return csr_matrix((freq / freq.sum(1).ravel()).astype(np.float32))
29 else:
~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/jax/api.py in f_jitted(*args, **kwargs)
369 return cache_miss(*args, **kwargs)[0] # probably won't return
370 else:
--> 371 return cpp_jitted_f(*args, **kwargs)
372 f_jitted._cpp_jitted_f = cpp_jitted_f
373
ValueError: vector::reserve
|
ValueError
|
def reduce(
operands: Array,
init_values: Array,
computation: Callable,
dimensions: Sequence[int],
) -> Array:
"""Wraps XLA's `Reduce
<https://www.tensorflow.org/xla/operation_semantics#reduce>`_
operator.
"""
flat_operands, operand_tree = tree_util.tree_flatten(operands)
flat_init_values, init_value_tree = tree_util.tree_flatten(init_values)
if operand_tree != init_value_tree:
raise ValueError(
"Operands must have the same tree structure as init_values:"
f" {operand_tree} vs. {init_value_tree}"
)
if len(flat_operands) != len(flat_init_values):
raise ValueError(
"Must have same total number of operands as init_values: "
f" {len(flat_operands)} vs. {len(flat_init_values)}"
)
monoid_reducer = _get_monoid_reducer(computation, flat_init_values)
if monoid_reducer:
# monoid reducers bypass the weak_type_rule, so we set it explicitly.
weak_type = dtypes.is_weakly_typed(*flat_operands) and dtypes.is_weakly_typed(
*flat_init_values
)
return convert_element_type(
monoid_reducer(*flat_operands, dimensions), weak_type=weak_type
)
else:
flat_init_avals = safe_map(_abstractify, flat_init_values)
jaxpr, consts, out_tree = _variadic_reduction_jaxpr(
computation, tuple(flat_init_avals), init_value_tree
)
out = reduce_p.bind(
*(flat_operands + flat_init_values),
computation=computation,
jaxpr=jaxpr,
consts=consts,
dimensions=tuple(dimensions),
)
return tree_util.tree_unflatten(out_tree, out)
|
def reduce(
operands: Array,
init_values: Array,
computation: Callable,
dimensions: Sequence[int],
) -> Array:
"""Wraps XLA's `Reduce
<https://www.tensorflow.org/xla/operation_semantics#reduce>`_
operator.
"""
flat_operands, operand_tree = tree_util.tree_flatten(operands)
flat_init_values, init_value_tree = tree_util.tree_flatten(init_values)
if operand_tree != init_value_tree:
raise ValueError(
"Operands must have the same tree structure as init_values:"
f" {operand_tree} vs. {init_value_tree}"
)
if len(flat_operands) != len(flat_init_values):
raise ValueError(
"Must have same total number of operands as init_values: "
f" {len(flat_operands)} vs. {len(flat_init_values)}"
)
monoid_reducer = _get_monoid_reducer(computation, flat_init_values)
if monoid_reducer:
# monoid reducers bypass the weak_type_rule, so we set it explicitly.
weak_type = dtypes.is_weakly_typed(*flat_operands) and dtypes.is_weakly_typed(
*flat_init_values
)
return convert_element_type(
monoid_reducer(*flat_operands, dimensions), weak_type=weak_type
)
else:
flat_init_avals = safe_map(_abstractify, flat_init_values)
# breakpoint()
jaxpr, consts, out_tree = _variadic_reduction_jaxpr(
computation, tuple(flat_init_avals), init_value_tree
)
out = reduce_p.bind(
*(flat_operands + flat_init_values),
computation=computation,
jaxpr=jaxpr,
consts=consts,
dimensions=tuple(dimensions),
)
return tree_util.tree_unflatten(out_tree, out)
|
https://github.com/google/jax/issues/4672
|
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-88-7216fb989347> in <module>()
4
5 with jax.disable_jit():
----> 6 jnp.repeat(jnp.zeros((1, 2)), repeats=2, axis=0, total_repeat_length=2)
7
8 def run_tests():
11 frames
google3/third_party/py/jax/_src/numpy/lax_numpy.py in repeat(a, repeats, axis, total_repeat_length)
2921 x=zeros([total_repeat_length], dtype=int32),
2922 idx=scatter_indices,
-> 2923 y=1)
2924 # Cumsum again to get scatter indices for repeat, e.g. [0,1,1,3,3,3,3,3]
2925 gather_indices = cumsum(block_split_indicators) - 1
google3/third_party/py/jax/_src/ops/scatter.py in index_add(x, idx, y, indices_are_sorted, unique_indices)
141 """
142 return _scatter_update(
--> 143 x, idx, y, lax.scatter_add, indices_are_sorted, unique_indices)
144
145
google3/third_party/py/jax/_src/ops/scatter.py in _scatter_update(x, idx, y, scatter_op, indices_are_sorted, unique_indices)
50 treedef, static_idx, dynamic_idx = jnp._split_index_for_jit(idx)
51 return _scatter_impl(x, y, scatter_op, treedef, static_idx, dynamic_idx,
---> 52 indices_are_sorted, unique_indices)
53
54
google3/third_party/py/jax/_src/ops/scatter.py in _scatter_impl(x, y, scatter_op, treedef, static_idx, dynamic_idx, indices_are_sorted, unique_indices)
62
63 idx = jnp._merge_static_and_dynamic_indices(treedef, static_idx, dynamic_idx)
---> 64 indexer = jnp._index_to_gather(jnp.shape(x), idx)
65
66 # Broadcast `y` to the slice output shape.
google3/third_party/py/jax/_src/numpy/lax_numpy.py in _index_to_gather(x_shape, idx)
4057 advanced_pairs = ((_normalize_index(e, x_shape[j]), i, j)
4058 for e, i, j in advanced_pairs)
-> 4059 advanced_indexes, idx_advanced_axes, x_advanced_axes = zip(*advanced_pairs)
4060 advanced_axes_are_contiguous = np.all(np.diff(idx_advanced_axes) == 1)
4061
google3/third_party/py/jax/_src/numpy/lax_numpy.py in <genexpr>(.0)
4056 if isscalar(e) or isinstance(e, (Sequence, ndarray)))
4057 advanced_pairs = ((_normalize_index(e, x_shape[j]), i, j)
-> 4058 for e, i, j in advanced_pairs)
4059 advanced_indexes, idx_advanced_axes, x_advanced_axes = zip(*advanced_pairs)
4060 advanced_axes_are_contiguous = np.all(np.diff(idx_advanced_axes) == 1)
google3/third_party/py/jax/_src/numpy/lax_numpy.py in _normalize_index(index, axis_size)
3785
3786 return lax.select(
-> 3787 lax.lt(index, _constant_like(index, 0)),
3788 lax.add(index, _constant_like(index, axis_size)),
3789 index)
google3/third_party/py/jax/_src/lax/lax.py in lt(x, y)
379 def lt(x: Array, y: Array) -> Array:
380 r"""Elementwise less-than: :math:`x < y`."""
--> 381 return lt_p.bind(x, y)
382
383 def convert_element_type(operand: Array, new_dtype: DType) -> Array:
google3/third_party/py/jax/core.py in bind(self, *args, **params)
261 top_trace = find_top_trace(args)
262 tracers = map(top_trace.full_raise, args)
--> 263 out = top_trace.process_primitive(self, tracers, params)
264 return map(full_lower, out) if self.multiple_results else full_lower(out)
265
google3/third_party/py/jax/core.py in process_primitive(self, primitive, tracers, params)
571
572 def process_primitive(self, primitive, tracers, params):
--> 573 return primitive.impl(*tracers, **params)
574
575 def process_call(self, primitive, f, tracers, params):
google3/third_party/py/jax/interpreters/xla.py in apply_primitive(prim, *args, **params)
232 """Impl rule that compiles and runs a single primitive 'prim' using XLA."""
233 compiled_fun = xla_primitive_callable(prim, *unsafe_map(arg_spec, args), **params)
--> 234 return compiled_fun(*args)
235
236
google3/third_party/py/jax/interpreters/xla.py in _execute_compiled_primitive(prim, compiled, result_handler, *args)
347 device, = compiled.local_devices()
348 input_bufs = list(it.chain.from_iterable(device_put(x, device) for x in args if x is not token))
--> 349 out_bufs = compiled.execute(input_bufs)
350 if FLAGS.jax_debug_nans: check_nans(prim, out_bufs)
351 return result_handler(*out_bufs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 0: want s32[1]{0}, got pred[]
|
RuntimeError
|
def primitive_computation(prim, axis_env, backend, tuple_args, *avals, **params):
c = xb.make_computation_builder(f"primitive_computation_{prim.name}")
c.set_op_metadata(
xc.OpMetadata(op_type=prim.name, op_name=str(pp_eqn_compact(prim.name, params)))
)
platform = xb.get_backend(backend).platform
xla_args, _ = _xla_callable_args(c, avals, tuple_args)
# return val always set as a side-effect on c
if prim in backend_specific_translations[platform]:
rule = backend_specific_translations[platform][prim]
ans = rule(c, *xla_args, **params)
elif prim in translations:
rule = translations[prim]
ans = rule(c, *xla_args, **params)
elif prim in initial_style_translations:
rule = initial_style_translations[prim]
ans = rule(
c,
axis_env,
extend_name_stack(prim.name),
avals,
backend,
*xla_args,
**params,
)
else:
raise NotImplementedError(f"XLA translation rule for {prim} not found")
assert isinstance(ans, xe.XlaOp)
c.clear_op_metadata()
try:
return c.build(ans)
except RuntimeError as e:
msg = (
" ".join(map(str, e.args)) + "\n"
"This is a bug in JAX's shape-checking rules; please report it!\n"
"https://github.com/google/jax/issues\n"
)
raise RuntimeError(msg) from e
|
def primitive_computation(prim, axis_env, backend, tuple_args, *avals, **params):
c = xb.make_computation_builder(f"primitive_computation_{prim.name}")
c.set_op_metadata(
xc.OpMetadata(op_type=prim.name, op_name=str(pp_eqn_compact(prim.name, params)))
)
platform = xb.get_backend(backend).platform
xla_args, _ = _xla_callable_args(c, avals, tuple_args)
# return val always set as a side-effect on c
if prim in backend_specific_translations[platform]:
rule = backend_specific_translations[platform][prim]
ans = rule(c, *xla_args, **params)
elif prim in translations:
rule = translations[prim]
ans = rule(c, *xla_args, **params)
elif prim in initial_style_translations:
rule = initial_style_translations[prim]
ans = rule(
c,
axis_env,
extend_name_stack(prim.name),
avals,
backend,
*xla_args,
**params,
)
else:
raise NotImplementedError(f"XLA translation rule for {prim} not found")
assert isinstance(ans, xe.XlaOp)
c.clear_op_metadata()
try:
return c.build()
except RuntimeError as e:
msg = (
" ".join(map(str, e.args)) + "\n"
"This is a bug in JAX's shape-checking rules; please report it!\n"
"https://github.com/google/jax/issues\n"
)
raise RuntimeError(msg) from e
|
https://github.com/google/jax/issues/4672
|
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-88-7216fb989347> in <module>()
4
5 with jax.disable_jit():
----> 6 jnp.repeat(jnp.zeros((1, 2)), repeats=2, axis=0, total_repeat_length=2)
7
8 def run_tests():
11 frames
google3/third_party/py/jax/_src/numpy/lax_numpy.py in repeat(a, repeats, axis, total_repeat_length)
2921 x=zeros([total_repeat_length], dtype=int32),
2922 idx=scatter_indices,
-> 2923 y=1)
2924 # Cumsum again to get scatter indices for repeat, e.g. [0,1,1,3,3,3,3,3]
2925 gather_indices = cumsum(block_split_indicators) - 1
google3/third_party/py/jax/_src/ops/scatter.py in index_add(x, idx, y, indices_are_sorted, unique_indices)
141 """
142 return _scatter_update(
--> 143 x, idx, y, lax.scatter_add, indices_are_sorted, unique_indices)
144
145
google3/third_party/py/jax/_src/ops/scatter.py in _scatter_update(x, idx, y, scatter_op, indices_are_sorted, unique_indices)
50 treedef, static_idx, dynamic_idx = jnp._split_index_for_jit(idx)
51 return _scatter_impl(x, y, scatter_op, treedef, static_idx, dynamic_idx,
---> 52 indices_are_sorted, unique_indices)
53
54
google3/third_party/py/jax/_src/ops/scatter.py in _scatter_impl(x, y, scatter_op, treedef, static_idx, dynamic_idx, indices_are_sorted, unique_indices)
62
63 idx = jnp._merge_static_and_dynamic_indices(treedef, static_idx, dynamic_idx)
---> 64 indexer = jnp._index_to_gather(jnp.shape(x), idx)
65
66 # Broadcast `y` to the slice output shape.
google3/third_party/py/jax/_src/numpy/lax_numpy.py in _index_to_gather(x_shape, idx)
4057 advanced_pairs = ((_normalize_index(e, x_shape[j]), i, j)
4058 for e, i, j in advanced_pairs)
-> 4059 advanced_indexes, idx_advanced_axes, x_advanced_axes = zip(*advanced_pairs)
4060 advanced_axes_are_contiguous = np.all(np.diff(idx_advanced_axes) == 1)
4061
google3/third_party/py/jax/_src/numpy/lax_numpy.py in <genexpr>(.0)
4056 if isscalar(e) or isinstance(e, (Sequence, ndarray)))
4057 advanced_pairs = ((_normalize_index(e, x_shape[j]), i, j)
-> 4058 for e, i, j in advanced_pairs)
4059 advanced_indexes, idx_advanced_axes, x_advanced_axes = zip(*advanced_pairs)
4060 advanced_axes_are_contiguous = np.all(np.diff(idx_advanced_axes) == 1)
google3/third_party/py/jax/_src/numpy/lax_numpy.py in _normalize_index(index, axis_size)
3785
3786 return lax.select(
-> 3787 lax.lt(index, _constant_like(index, 0)),
3788 lax.add(index, _constant_like(index, axis_size)),
3789 index)
google3/third_party/py/jax/_src/lax/lax.py in lt(x, y)
379 def lt(x: Array, y: Array) -> Array:
380 r"""Elementwise less-than: :math:`x < y`."""
--> 381 return lt_p.bind(x, y)
382
383 def convert_element_type(operand: Array, new_dtype: DType) -> Array:
google3/third_party/py/jax/core.py in bind(self, *args, **params)
261 top_trace = find_top_trace(args)
262 tracers = map(top_trace.full_raise, args)
--> 263 out = top_trace.process_primitive(self, tracers, params)
264 return map(full_lower, out) if self.multiple_results else full_lower(out)
265
google3/third_party/py/jax/core.py in process_primitive(self, primitive, tracers, params)
571
572 def process_primitive(self, primitive, tracers, params):
--> 573 return primitive.impl(*tracers, **params)
574
575 def process_call(self, primitive, f, tracers, params):
google3/third_party/py/jax/interpreters/xla.py in apply_primitive(prim, *args, **params)
232 """Impl rule that compiles and runs a single primitive 'prim' using XLA."""
233 compiled_fun = xla_primitive_callable(prim, *unsafe_map(arg_spec, args), **params)
--> 234 return compiled_fun(*args)
235
236
google3/third_party/py/jax/interpreters/xla.py in _execute_compiled_primitive(prim, compiled, result_handler, *args)
347 device, = compiled.local_devices()
348 input_bufs = list(it.chain.from_iterable(device_put(x, device) for x in args if x is not token))
--> 349 out_bufs = compiled.execute(input_bufs)
350 if FLAGS.jax_debug_nans: check_nans(prim, out_bufs)
351 return result_handler(*out_bufs)
RuntimeError: Invalid argument: Argument does not match host shape or layout of computation parameter 0: want s32[1]{0}, got pred[]
|
RuntimeError
|
def _lift_linearized(jaxpr, primal_avals, consts, io_tree, out_pvals, *py_args):
def fun(*tangents):
tangent_avals = list(map(core.get_aval, tangents))
for primal_aval, tangent_aval in zip(primal_avals, tangent_avals):
try:
core.lattice_join(primal_aval.at_least_vspace(), tangent_aval)
except TypeError as e:
msg = (
"linearized function called on tangent values inconsistent with "
"the original primal values: "
f"got {tangent_aval} for primal aval {primal_aval}"
)
raise ValueError(msg)
tangents_out = eval_jaxpr(jaxpr, consts, *tangents)
return tuple(
map(
lambda out_pv, tan_out: out_pv.merge_with_known(tan_out),
out_pvals,
tangents_out,
)
)
return apply_flat_fun(fun, io_tree, *py_args)
|
def _lift_linearized(jaxpr, primal_avals, consts, io_tree, out_pvals, *py_args):
def fun(*tangents):
tangent_avals = list(map(core.get_aval, tangents))
for primal_aval, tangent_aval in zip(primal_avals, tangent_avals):
try:
core.lattice_join(primal_aval, tangent_aval)
except TypeError as e:
msg = (
"linearized function called on tangent values inconsistent with "
"the original primal values."
)
raise ValueError(msg) from e
tangents_out = eval_jaxpr(jaxpr, consts, *tangents)
return tuple(
map(
lambda out_pv, tan_out: out_pv.merge_with_known(tan_out),
out_pvals,
tangents_out,
)
)
return apply_flat_fun(fun, io_tree, *py_args)
|
https://github.com/google/jax/issues/4622
|
/usr/local/lib/python3.6/dist-packages/jax/lib/xla_bridge.py:130: UserWarning: No GPU/TPU found, falling back to CPU.
warnings.warn('No GPU/TPU found, falling back to CPU.')
---------------------------------------------------------------------------
ConcretizationTypeError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/jax/api.py in fun(*tangents)
1762 try:
-> 1763 core.lattice_join(primal_aval, tangent_aval)
1764 except TypeError as e:
17 frames
/usr/local/lib/python3.6/dist-packages/jax/core.py in lattice_join(x, y)
787 elif isinstance(x, type(y)):
--> 788 return y.join(x)
789 elif isinstance(y, type(x)):
/usr/local/lib/python3.6/dist-packages/jax/core.py in join(self, other)
1019 def join(self, other) -> UnshapedArray:
-> 1020 if self == other:
1021 return self
/usr/local/lib/python3.6/dist-packages/jax/core.py in __bool__(self)
506 def __nonzero__(self): return self.aval._nonzero(self)
--> 507 def __bool__(self): return self.aval._bool(self)
508 def __int__(self): return self.aval._int(self)
/usr/local/lib/python3.6/dist-packages/jax/core.py in error(self, arg)
863 def error(self, arg):
--> 864 raise_concretization_error(arg, fname_context)
865 return error
/usr/local/lib/python3.6/dist-packages/jax/core.py in raise_concretization_error(val, context)
852 f"Encountered tracer value: {val}")
--> 853 raise ConcretizationTypeError(msg)
854
ConcretizationTypeError: Abstract tracer value encountered where concrete value is expected.
The problem arose with the `bool` function.
While tracing the function f at /usr/local/lib/python3.6/dist-packages/jax/lax/lax_control_flow.py:2085, this value became a tracer due to JAX operations on these lines:
operation m:bool[2] = eq k:float32[2] l:float32[2]
from line <ipython-input-1-fdc0af3e82fa>:12 (<module>)
You can use transformation parameters such as `static_argnums` for `jit` to avoid tracing particular arguments of transformed functions.
See https://jax.readthedocs.io/en/latest/faq.html#abstract-tracer-value-encountered-where-concrete-value-is-expected-error for more information.
Encountered tracer value: Traced<ShapedArray(bool[])>with<DynamicJaxprTrace(level=1/0)>
The above exception was the direct cause of the following exception:
ValueError Traceback (most recent call last)
<ipython-input-1-fdc0af3e82fa> in <module>()
10
11 val, func_jvp = jax.linearize(func, x)
---> 12 print(cg(func_jvp, val))
/usr/local/lib/python3.6/dist-packages/jax/scipy/sparse/linalg.py in cg(A, b, x0, tol, atol, maxiter, M)
172 symmetric = all(map(real_valued, tree_leaves(b)))
173 x = lax.custom_linear_solve(
--> 174 A, b, solve=cg_solve, transpose_solve=cg_solve, symmetric=symmetric)
175 info = None # TODO(shoyer): return the real iteration count here
176 return x, info
/usr/local/lib/python3.6/dist-packages/jax/lax/lax_control_flow.py in custom_linear_solve(matvec, b, solve, transpose_solve, symmetric)
2094
2095 solve_jaxpr, solve_consts, out_tree = _initial_style_jaxpr(
-> 2096 _shape_checked(partial(solve, matvec), "solve"), in_args_tree, b_avals)
2097 _check_tree("solve", "b", out_tree, tree)
2098
/usr/local/lib/python3.6/dist-packages/jax/lax/lax_control_flow.py in _initial_style_jaxpr(fun, in_tree, in_avals)
70 @cache()
71 def _initial_style_jaxpr(fun: Callable, in_tree, in_avals):
---> 72 jaxpr, out_avals, consts, out_tree = _initial_style_open_jaxpr(fun, in_tree, in_avals)
73 closed_jaxpr = core.ClosedJaxpr(pe.convert_constvars_jaxpr(jaxpr), ())
74 return closed_jaxpr, consts, out_tree
/usr/local/lib/python3.6/dist-packages/jax/lax/lax_control_flow.py in _initial_style_open_jaxpr(fun, in_tree, in_avals)
65 def _initial_style_open_jaxpr(fun: Callable, in_tree, in_avals):
66 wrapped_fun, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)
---> 67 jaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(wrapped_fun, in_avals)
68 return jaxpr, out_avals, consts, out_tree()
69
/usr/local/lib/python3.6/dist-packages/jax/interpreters/partial_eval.py in trace_to_jaxpr_dynamic(fun, in_avals)
992 main.source_info = fun_sourceinfo(fun.f) # type: ignore
993 main.jaxpr_stack = () # type: ignore
--> 994 jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, main, in_avals)
995 del main
996 return jaxpr, out_avals, consts
/usr/local/lib/python3.6/dist-packages/jax/interpreters/partial_eval.py in trace_to_subjaxpr_dynamic(fun, main, in_avals)
1002 trace = DynamicJaxprTrace(main, core.cur_sublevel())
1003 in_tracers = map(trace.new_arg, in_avals)
-> 1004 ans = fun.call_wrapped(*in_tracers)
1005 out_tracers = map(trace.full_raise, ans)
1006 jaxpr, out_avals, consts = frame.to_jaxpr(in_tracers, out_tracers)
/usr/local/lib/python3.6/dist-packages/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
149
150 try:
--> 151 ans = self.f(*args, **dict(self.params, **kwargs))
152 except:
153 # Some transformations yield from inside context managers, so we have to
/usr/local/lib/python3.6/dist-packages/jax/lax/lax_control_flow.py in f(x)
2084 def _shape_checked(fun, name):
2085 def f(x):
-> 2086 y = fun(x)
2087 _check_shapes(name, "b", y, b_flat)
2088 return y
/usr/local/lib/python3.6/dist-packages/jax/scipy/sparse/linalg.py in _cg_solve(A, b, x0, maxiter, tol, atol, M)
77 return x_, r_, gamma_, p_, k + 1
78
---> 79 r0 = _sub(b, A(x0))
80 p0 = z0 = M(r0)
81 gamma0 = _vdot_tree(r0, z0)
/usr/local/lib/python3.6/dist-packages/jax/api.py in _lift_linearized(jaxpr, primal_avals, consts, io_tree, out_pvals, *py_args)
1770 out_pvals, tangents_out))
1771
-> 1772 return apply_flat_fun(fun, io_tree, *py_args)
1773
1774 def _check_inexact_input_vjp(x):
/usr/local/lib/python3.6/dist-packages/jax/api_util.py in apply_flat_fun(fun, io_tree, *py_args)
50 if in_tree != in_tree_expected:
51 raise TypeError("Expected {}, got {}".format(in_tree_expected, in_tree))
---> 52 ans = fun(*args)
53 return tree_unflatten(out_tree, ans)
54
/usr/local/lib/python3.6/dist-packages/jax/api.py in fun(*tangents)
1765 msg = ("linearized function called on tangent values inconsistent with "
1766 "the original primal values.")
-> 1767 raise ValueError(msg) from e
1768 tangents_out = eval_jaxpr(jaxpr, consts, *tangents)
1769 return tuple(map(lambda out_pv, tan_out: out_pv.merge_with_known(tan_out),
ValueError: linearized function called on tangent values inconsistent with the original primal values.
|
ConcretizationTypeError
|
def fun(*tangents):
tangent_avals = list(map(core.get_aval, tangents))
for primal_aval, tangent_aval in zip(primal_avals, tangent_avals):
try:
core.lattice_join(primal_aval.at_least_vspace(), tangent_aval)
except TypeError as e:
msg = (
"linearized function called on tangent values inconsistent with "
"the original primal values: "
f"got {tangent_aval} for primal aval {primal_aval}"
)
raise ValueError(msg)
tangents_out = eval_jaxpr(jaxpr, consts, *tangents)
return tuple(
map(
lambda out_pv, tan_out: out_pv.merge_with_known(tan_out),
out_pvals,
tangents_out,
)
)
|
def fun(*tangents):
tangent_avals = list(map(core.get_aval, tangents))
for primal_aval, tangent_aval in zip(primal_avals, tangent_avals):
try:
core.lattice_join(primal_aval, tangent_aval)
except TypeError as e:
msg = (
"linearized function called on tangent values inconsistent with "
"the original primal values."
)
raise ValueError(msg) from e
tangents_out = eval_jaxpr(jaxpr, consts, *tangents)
return tuple(
map(
lambda out_pv, tan_out: out_pv.merge_with_known(tan_out),
out_pvals,
tangents_out,
)
)
|
https://github.com/google/jax/issues/4622
|
/usr/local/lib/python3.6/dist-packages/jax/lib/xla_bridge.py:130: UserWarning: No GPU/TPU found, falling back to CPU.
warnings.warn('No GPU/TPU found, falling back to CPU.')
---------------------------------------------------------------------------
ConcretizationTypeError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/jax/api.py in fun(*tangents)
1762 try:
-> 1763 core.lattice_join(primal_aval, tangent_aval)
1764 except TypeError as e:
17 frames
/usr/local/lib/python3.6/dist-packages/jax/core.py in lattice_join(x, y)
787 elif isinstance(x, type(y)):
--> 788 return y.join(x)
789 elif isinstance(y, type(x)):
/usr/local/lib/python3.6/dist-packages/jax/core.py in join(self, other)
1019 def join(self, other) -> UnshapedArray:
-> 1020 if self == other:
1021 return self
/usr/local/lib/python3.6/dist-packages/jax/core.py in __bool__(self)
506 def __nonzero__(self): return self.aval._nonzero(self)
--> 507 def __bool__(self): return self.aval._bool(self)
508 def __int__(self): return self.aval._int(self)
/usr/local/lib/python3.6/dist-packages/jax/core.py in error(self, arg)
863 def error(self, arg):
--> 864 raise_concretization_error(arg, fname_context)
865 return error
/usr/local/lib/python3.6/dist-packages/jax/core.py in raise_concretization_error(val, context)
852 f"Encountered tracer value: {val}")
--> 853 raise ConcretizationTypeError(msg)
854
ConcretizationTypeError: Abstract tracer value encountered where concrete value is expected.
The problem arose with the `bool` function.
While tracing the function f at /usr/local/lib/python3.6/dist-packages/jax/lax/lax_control_flow.py:2085, this value became a tracer due to JAX operations on these lines:
operation m:bool[2] = eq k:float32[2] l:float32[2]
from line <ipython-input-1-fdc0af3e82fa>:12 (<module>)
You can use transformation parameters such as `static_argnums` for `jit` to avoid tracing particular arguments of transformed functions.
See https://jax.readthedocs.io/en/latest/faq.html#abstract-tracer-value-encountered-where-concrete-value-is-expected-error for more information.
Encountered tracer value: Traced<ShapedArray(bool[])>with<DynamicJaxprTrace(level=1/0)>
The above exception was the direct cause of the following exception:
ValueError Traceback (most recent call last)
<ipython-input-1-fdc0af3e82fa> in <module>()
10
11 val, func_jvp = jax.linearize(func, x)
---> 12 print(cg(func_jvp, val))
/usr/local/lib/python3.6/dist-packages/jax/scipy/sparse/linalg.py in cg(A, b, x0, tol, atol, maxiter, M)
172 symmetric = all(map(real_valued, tree_leaves(b)))
173 x = lax.custom_linear_solve(
--> 174 A, b, solve=cg_solve, transpose_solve=cg_solve, symmetric=symmetric)
175 info = None # TODO(shoyer): return the real iteration count here
176 return x, info
/usr/local/lib/python3.6/dist-packages/jax/lax/lax_control_flow.py in custom_linear_solve(matvec, b, solve, transpose_solve, symmetric)
2094
2095 solve_jaxpr, solve_consts, out_tree = _initial_style_jaxpr(
-> 2096 _shape_checked(partial(solve, matvec), "solve"), in_args_tree, b_avals)
2097 _check_tree("solve", "b", out_tree, tree)
2098
/usr/local/lib/python3.6/dist-packages/jax/lax/lax_control_flow.py in _initial_style_jaxpr(fun, in_tree, in_avals)
70 @cache()
71 def _initial_style_jaxpr(fun: Callable, in_tree, in_avals):
---> 72 jaxpr, out_avals, consts, out_tree = _initial_style_open_jaxpr(fun, in_tree, in_avals)
73 closed_jaxpr = core.ClosedJaxpr(pe.convert_constvars_jaxpr(jaxpr), ())
74 return closed_jaxpr, consts, out_tree
/usr/local/lib/python3.6/dist-packages/jax/lax/lax_control_flow.py in _initial_style_open_jaxpr(fun, in_tree, in_avals)
65 def _initial_style_open_jaxpr(fun: Callable, in_tree, in_avals):
66 wrapped_fun, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)
---> 67 jaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(wrapped_fun, in_avals)
68 return jaxpr, out_avals, consts, out_tree()
69
/usr/local/lib/python3.6/dist-packages/jax/interpreters/partial_eval.py in trace_to_jaxpr_dynamic(fun, in_avals)
992 main.source_info = fun_sourceinfo(fun.f) # type: ignore
993 main.jaxpr_stack = () # type: ignore
--> 994 jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, main, in_avals)
995 del main
996 return jaxpr, out_avals, consts
/usr/local/lib/python3.6/dist-packages/jax/interpreters/partial_eval.py in trace_to_subjaxpr_dynamic(fun, main, in_avals)
1002 trace = DynamicJaxprTrace(main, core.cur_sublevel())
1003 in_tracers = map(trace.new_arg, in_avals)
-> 1004 ans = fun.call_wrapped(*in_tracers)
1005 out_tracers = map(trace.full_raise, ans)
1006 jaxpr, out_avals, consts = frame.to_jaxpr(in_tracers, out_tracers)
/usr/local/lib/python3.6/dist-packages/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
149
150 try:
--> 151 ans = self.f(*args, **dict(self.params, **kwargs))
152 except:
153 # Some transformations yield from inside context managers, so we have to
/usr/local/lib/python3.6/dist-packages/jax/lax/lax_control_flow.py in f(x)
2084 def _shape_checked(fun, name):
2085 def f(x):
-> 2086 y = fun(x)
2087 _check_shapes(name, "b", y, b_flat)
2088 return y
/usr/local/lib/python3.6/dist-packages/jax/scipy/sparse/linalg.py in _cg_solve(A, b, x0, maxiter, tol, atol, M)
77 return x_, r_, gamma_, p_, k + 1
78
---> 79 r0 = _sub(b, A(x0))
80 p0 = z0 = M(r0)
81 gamma0 = _vdot_tree(r0, z0)
/usr/local/lib/python3.6/dist-packages/jax/api.py in _lift_linearized(jaxpr, primal_avals, consts, io_tree, out_pvals, *py_args)
1770 out_pvals, tangents_out))
1771
-> 1772 return apply_flat_fun(fun, io_tree, *py_args)
1773
1774 def _check_inexact_input_vjp(x):
/usr/local/lib/python3.6/dist-packages/jax/api_util.py in apply_flat_fun(fun, io_tree, *py_args)
50 if in_tree != in_tree_expected:
51 raise TypeError("Expected {}, got {}".format(in_tree_expected, in_tree))
---> 52 ans = fun(*args)
53 return tree_unflatten(out_tree, ans)
54
/usr/local/lib/python3.6/dist-packages/jax/api.py in fun(*tangents)
1765 msg = ("linearized function called on tangent values inconsistent with "
1766 "the original primal values.")
-> 1767 raise ValueError(msg) from e
1768 tangents_out = eval_jaxpr(jaxpr, consts, *tangents)
1769 return tuple(map(lambda out_pv, tan_out: out_pv.merge_with_known(tan_out),
ValueError: linearized function called on tangent values inconsistent with the original primal values.
|
ConcretizationTypeError
|
def __eq__(self, other):
if (
type(self) is type(other)
and self.dtype == other.dtype
and self.shape == other.shape
and self.weak_type == other.weak_type
):
with eval_context(): # in case self.val is a DeviceArray
return (self.val == other.val).all()
else:
return False
|
def __eq__(self, other):
return (
type(self) is type(other)
and self.dtype == other.dtype
and self.shape == other.shape
and self.weak_type == other.weak_type
and np.all(self.val == other.val)
)
|
https://github.com/google/jax/issues/4622
|
/usr/local/lib/python3.6/dist-packages/jax/lib/xla_bridge.py:130: UserWarning: No GPU/TPU found, falling back to CPU.
warnings.warn('No GPU/TPU found, falling back to CPU.')
---------------------------------------------------------------------------
ConcretizationTypeError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/jax/api.py in fun(*tangents)
1762 try:
-> 1763 core.lattice_join(primal_aval, tangent_aval)
1764 except TypeError as e:
17 frames
/usr/local/lib/python3.6/dist-packages/jax/core.py in lattice_join(x, y)
787 elif isinstance(x, type(y)):
--> 788 return y.join(x)
789 elif isinstance(y, type(x)):
/usr/local/lib/python3.6/dist-packages/jax/core.py in join(self, other)
1019 def join(self, other) -> UnshapedArray:
-> 1020 if self == other:
1021 return self
/usr/local/lib/python3.6/dist-packages/jax/core.py in __bool__(self)
506 def __nonzero__(self): return self.aval._nonzero(self)
--> 507 def __bool__(self): return self.aval._bool(self)
508 def __int__(self): return self.aval._int(self)
/usr/local/lib/python3.6/dist-packages/jax/core.py in error(self, arg)
863 def error(self, arg):
--> 864 raise_concretization_error(arg, fname_context)
865 return error
/usr/local/lib/python3.6/dist-packages/jax/core.py in raise_concretization_error(val, context)
852 f"Encountered tracer value: {val}")
--> 853 raise ConcretizationTypeError(msg)
854
ConcretizationTypeError: Abstract tracer value encountered where concrete value is expected.
The problem arose with the `bool` function.
While tracing the function f at /usr/local/lib/python3.6/dist-packages/jax/lax/lax_control_flow.py:2085, this value became a tracer due to JAX operations on these lines:
operation m:bool[2] = eq k:float32[2] l:float32[2]
from line <ipython-input-1-fdc0af3e82fa>:12 (<module>)
You can use transformation parameters such as `static_argnums` for `jit` to avoid tracing particular arguments of transformed functions.
See https://jax.readthedocs.io/en/latest/faq.html#abstract-tracer-value-encountered-where-concrete-value-is-expected-error for more information.
Encountered tracer value: Traced<ShapedArray(bool[])>with<DynamicJaxprTrace(level=1/0)>
The above exception was the direct cause of the following exception:
ValueError Traceback (most recent call last)
<ipython-input-1-fdc0af3e82fa> in <module>()
10
11 val, func_jvp = jax.linearize(func, x)
---> 12 print(cg(func_jvp, val))
/usr/local/lib/python3.6/dist-packages/jax/scipy/sparse/linalg.py in cg(A, b, x0, tol, atol, maxiter, M)
172 symmetric = all(map(real_valued, tree_leaves(b)))
173 x = lax.custom_linear_solve(
--> 174 A, b, solve=cg_solve, transpose_solve=cg_solve, symmetric=symmetric)
175 info = None # TODO(shoyer): return the real iteration count here
176 return x, info
/usr/local/lib/python3.6/dist-packages/jax/lax/lax_control_flow.py in custom_linear_solve(matvec, b, solve, transpose_solve, symmetric)
2094
2095 solve_jaxpr, solve_consts, out_tree = _initial_style_jaxpr(
-> 2096 _shape_checked(partial(solve, matvec), "solve"), in_args_tree, b_avals)
2097 _check_tree("solve", "b", out_tree, tree)
2098
/usr/local/lib/python3.6/dist-packages/jax/lax/lax_control_flow.py in _initial_style_jaxpr(fun, in_tree, in_avals)
70 @cache()
71 def _initial_style_jaxpr(fun: Callable, in_tree, in_avals):
---> 72 jaxpr, out_avals, consts, out_tree = _initial_style_open_jaxpr(fun, in_tree, in_avals)
73 closed_jaxpr = core.ClosedJaxpr(pe.convert_constvars_jaxpr(jaxpr), ())
74 return closed_jaxpr, consts, out_tree
/usr/local/lib/python3.6/dist-packages/jax/lax/lax_control_flow.py in _initial_style_open_jaxpr(fun, in_tree, in_avals)
65 def _initial_style_open_jaxpr(fun: Callable, in_tree, in_avals):
66 wrapped_fun, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)
---> 67 jaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(wrapped_fun, in_avals)
68 return jaxpr, out_avals, consts, out_tree()
69
/usr/local/lib/python3.6/dist-packages/jax/interpreters/partial_eval.py in trace_to_jaxpr_dynamic(fun, in_avals)
992 main.source_info = fun_sourceinfo(fun.f) # type: ignore
993 main.jaxpr_stack = () # type: ignore
--> 994 jaxpr, out_avals, consts = trace_to_subjaxpr_dynamic(fun, main, in_avals)
995 del main
996 return jaxpr, out_avals, consts
/usr/local/lib/python3.6/dist-packages/jax/interpreters/partial_eval.py in trace_to_subjaxpr_dynamic(fun, main, in_avals)
1002 trace = DynamicJaxprTrace(main, core.cur_sublevel())
1003 in_tracers = map(trace.new_arg, in_avals)
-> 1004 ans = fun.call_wrapped(*in_tracers)
1005 out_tracers = map(trace.full_raise, ans)
1006 jaxpr, out_avals, consts = frame.to_jaxpr(in_tracers, out_tracers)
/usr/local/lib/python3.6/dist-packages/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
149
150 try:
--> 151 ans = self.f(*args, **dict(self.params, **kwargs))
152 except:
153 # Some transformations yield from inside context managers, so we have to
/usr/local/lib/python3.6/dist-packages/jax/lax/lax_control_flow.py in f(x)
2084 def _shape_checked(fun, name):
2085 def f(x):
-> 2086 y = fun(x)
2087 _check_shapes(name, "b", y, b_flat)
2088 return y
/usr/local/lib/python3.6/dist-packages/jax/scipy/sparse/linalg.py in _cg_solve(A, b, x0, maxiter, tol, atol, M)
77 return x_, r_, gamma_, p_, k + 1
78
---> 79 r0 = _sub(b, A(x0))
80 p0 = z0 = M(r0)
81 gamma0 = _vdot_tree(r0, z0)
/usr/local/lib/python3.6/dist-packages/jax/api.py in _lift_linearized(jaxpr, primal_avals, consts, io_tree, out_pvals, *py_args)
1770 out_pvals, tangents_out))
1771
-> 1772 return apply_flat_fun(fun, io_tree, *py_args)
1773
1774 def _check_inexact_input_vjp(x):
/usr/local/lib/python3.6/dist-packages/jax/api_util.py in apply_flat_fun(fun, io_tree, *py_args)
50 if in_tree != in_tree_expected:
51 raise TypeError("Expected {}, got {}".format(in_tree_expected, in_tree))
---> 52 ans = fun(*args)
53 return tree_unflatten(out_tree, ans)
54
/usr/local/lib/python3.6/dist-packages/jax/api.py in fun(*tangents)
1765 msg = ("linearized function called on tangent values inconsistent with "
1766 "the original primal values.")
-> 1767 raise ValueError(msg) from e
1768 tangents_out = eval_jaxpr(jaxpr, consts, *tangents)
1769 return tuple(map(lambda out_pv, tan_out: out_pv.merge_with_known(tan_out),
ValueError: linearized function called on tangent values inconsistent with the original primal values.
|
ConcretizationTypeError
|
def _threefry2x32_gpu_translation_rule(c, k1, k2, x1, x2):
shape = lax.broadcast_shapes(
c.get_shape(k1).dimensions(),
c.get_shape(k2).dimensions(),
c.get_shape(x1).dimensions(),
c.get_shape(x2).dimensions(),
)
rank = len(shape)
if 0 in shape:
zeros = xla_client.ops.Broadcast(
xla_bridge.constant(c, np.array(0, np.uint32)), shape
)
return xla_client.ops.Tuple(c, [zeros, zeros])
def _broadcast(x):
ndims = c.get_shape(x).rank()
return xla_client.ops.BroadcastInDim(x, shape, tuple(range(rank - ndims, rank)))
return cuda_prng.threefry2x32(
c, (_broadcast(k1), _broadcast(k2)), (_broadcast(x1), _broadcast(x2))
)
|
def _threefry2x32_gpu_translation_rule(c, k1, k2, x1, x2):
shape = lax.broadcast_shapes(
c.get_shape(k1).dimensions(),
c.get_shape(k2).dimensions(),
c.get_shape(x1).dimensions(),
c.get_shape(x2).dimensions(),
)
rank = len(shape)
def _broadcast(x):
ndims = c.get_shape(x).rank()
return xla_client.ops.BroadcastInDim(x, shape, tuple(range(rank - ndims, rank)))
return cuda_prng.threefry2x32(
c, (_broadcast(k1), _broadcast(k2)), (_broadcast(x1), _broadcast(x2))
)
|
https://github.com/google/jax/issues/4565
|
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-2-1d1849d1c41c> in <module>()
5 jax.random.uniform(key, shape) # ok
6 with jax.disable_jit():
----> 7 jax.random.uniform(key, shape) # CUDA operation failed: invalid configuration argument
9 frames
google3/third_party/py/jax/random.py in uniform(key, shape, dtype, minval, maxval)
380 dtype = dtypes.canonicalize_dtype(dtype)
381 shape = abstract_arrays.canonicalize_shape(shape)
--> 382 return _uniform(key, shape, dtype, minval, maxval) # type: ignore
383
384 @partial(jit, static_argnums=(1, 2))
google3/third_party/py/jax/api.py in f_jitted(*args, **kwargs)
190 def f_jitted(*args, **kwargs):
191 if _jit_is_disabled():
--> 192 return fun(*args, **kwargs)
193 if max(static_argnums + donate_argnums, default=-1) >= len(args):
194 msg = ("jitted function has static_argnums={}, donate_argnums={} but "
google3/third_party/py/jax/random.py in _uniform(key, shape, dtype, minval, maxval)
399 raise TypeError("uniform only accepts 32- or 64-bit dtypes.")
400
--> 401 bits = _random_bits(key, nbits, shape)
402
403 # The strategy here is to randomize only the mantissa bits with an exponent of
google3/third_party/py/jax/random.py in _random_bits(key, bit_width, shape)
312 nblocks, rem = divmod(max_count, jnp.iinfo(np.uint32).max)
313 if not nblocks:
--> 314 bits = threefry_2x32(key, lax.iota(np.uint32, rem))
315 else:
316 *subkeys, last_key = split(key, nblocks + 1)
google3/third_party/py/jax/api.py in f_jitted(*args, **kwargs)
190 def f_jitted(*args, **kwargs):
191 if _jit_is_disabled():
--> 192 return fun(*args, **kwargs)
193 if max(static_argnums + donate_argnums, default=-1) >= len(args):
194 msg = ("jitted function has static_argnums={}, donate_argnums={} but "
google3/third_party/py/jax/random.py in threefry_2x32(keypair, count)
258 x = list(jnp.split(count.ravel(), 2))
259
--> 260 x = threefry2x32_p.bind(key1, key2, x[0], x[1])
261 out = jnp.concatenate(x)
262 assert out.dtype == np.uint32
google3/third_party/py/jax/core.py in bind(self, *args, **params)
261 top_trace = find_top_trace(args)
262 tracers = map(top_trace.full_raise, args)
--> 263 out = top_trace.process_primitive(self, tracers, params)
264 return map(full_lower, out) if self.multiple_results else full_lower(out)
265
google3/third_party/py/jax/core.py in process_primitive(self, primitive, tracers, params)
570
571 def process_primitive(self, primitive, tracers, params):
--> 572 return primitive.impl(*tracers, **params)
573
574 def process_call(self, primitive, f, tracers, params):
google3/third_party/py/jax/interpreters/xla.py in apply_primitive(prim, *args, **params)
232 """Impl rule that compiles and runs a single primitive 'prim' using XLA."""
233 compiled_fun = xla_primitive_callable(prim, *unsafe_map(arg_spec, args), **params)
--> 234 return compiled_fun(*args)
235
236
google3/third_party/py/jax/interpreters/xla.py in _execute_compiled_primitive(prim, compiled, result_handler, *args)
347 device, = compiled.local_devices()
348 input_bufs = list(it.chain.from_iterable(device_put(x, device) for x in args if x is not token))
--> 349 out_bufs = compiled.execute(input_bufs)
350 if FLAGS.jax_debug_nans: check_nans(prim, out_bufs)
351 return result_handler(*out_bufs)
RuntimeError: CUDA operation failed: invalid configuration argument
|
RuntimeError
|
def _is_sorted(dims, op_name, name):
for i in range(1, len(dims)):
if dims[i] < dims[i - 1]:
raise TypeError(f"{name} in {op_name} op must be sorted; got {dims}")
|
def _is_sorted(dims, name):
for i in range(1, len(dims)):
if dims[i] < dims[i - 1]:
raise TypeError(f"{name} in scatter op must be sorted; got {dims}")
|
https://github.com/google/jax/issues/3905
|
LayerError Traceback (most recent call last)
<ipython-input-91-cc4d1abeffd2> in <module>
----> 1 embed_out = embed(x)
/opt/conda/lib/python3.7/site-packages/trax/layers/base.py in __call__(self, x, weights, state, rng)
165 self.state = state # Needed if the model wasn't fully initialized.
166 state = self.state
--> 167 outputs, new_state = self.pure_fn(x, weights, state, rng)
168 self.state = new_state
169 self.weights = weights
/opt/conda/lib/python3.7/site-packages/trax/layers/base.py in pure_fn(self, x, weights, state, rng, use_cache)
448 name, trace = self._name, _short_traceback(skip=3)
449 raise LayerError(name, 'pure_fn',
--> 450 self._caller, signature(x), trace) from None
451
452 def output_signature(self, input_signature):
LayerError: Exception passing through layer Embedding_9088_256 (in pure_fn):
layer created in file [...]/<ipython-input-89-4dbaf3019a8b>, line 1
layer input shapes: ShapeDtype{shape:(16, 18), dtype:int32}
File [...]/trax/layers/core.py, line 150, in forward
return jnp.take(self.weights, x, axis=0)
File [...]/jax/numpy/lax_numpy.py, line 3298, in take
slice_sizes=tuple(slice_sizes))
File [...]/jax/lax/lax.py, line 835, in gather
slice_sizes=canonicalize_shape(slice_sizes))
File [...]/site-packages/jax/core.py, line 273, in bind
return self.impl(*args, **kwargs)
File [...]/jax/interpreters/xla.py, line 228, in apply_primitive
compiled_fun = xla_primitive_callable(prim, *unsafe_map(arg_spec, args), **params)
File [...]/jax/interpreters/xla.py, line 262, in xla_primitive_callable
*avals, **params)
File [...]/jax/interpreters/xla.py, line 320, in primitive_computation
raise RuntimeError(msg) from e
RuntimeError: Invalid argument: Slice size at index 0 in gather op is out of range, must be within [0, 1), got 1.:
This is a bug in JAX's shape-checking rules; please report it!
|
LayerError
|
def _sorted_dims_in_range(dims, rank, op_name, name):
if len(dims) == 0:
return
invalid_dim = None
if dims[0] < 0:
invalid_dim = dims[0]
elif dims[-1] >= rank:
invalid_dim = dims[-1]
if invalid_dim:
raise TypeError(
f"Invalid {name} set in {op_name} op; valid range is "
f"[0, {rank}); got: {invalid_dim}."
)
|
def _sorted_dims_in_range(dims, rank, name):
if len(dims) == 0:
return
invalid_dim = None
if dims[0] < 0:
invalid_dim = dims[0]
elif dims[-1] >= rank:
invalid_dim = dims[-1]
if invalid_dim:
raise TypeError(
f"Invalid {name} set in scatter op; valid range is "
f"[0, {rank}); got: {invalid_dim}."
)
|
https://github.com/google/jax/issues/3905
|
LayerError Traceback (most recent call last)
<ipython-input-91-cc4d1abeffd2> in <module>
----> 1 embed_out = embed(x)
/opt/conda/lib/python3.7/site-packages/trax/layers/base.py in __call__(self, x, weights, state, rng)
165 self.state = state # Needed if the model wasn't fully initialized.
166 state = self.state
--> 167 outputs, new_state = self.pure_fn(x, weights, state, rng)
168 self.state = new_state
169 self.weights = weights
/opt/conda/lib/python3.7/site-packages/trax/layers/base.py in pure_fn(self, x, weights, state, rng, use_cache)
448 name, trace = self._name, _short_traceback(skip=3)
449 raise LayerError(name, 'pure_fn',
--> 450 self._caller, signature(x), trace) from None
451
452 def output_signature(self, input_signature):
LayerError: Exception passing through layer Embedding_9088_256 (in pure_fn):
layer created in file [...]/<ipython-input-89-4dbaf3019a8b>, line 1
layer input shapes: ShapeDtype{shape:(16, 18), dtype:int32}
File [...]/trax/layers/core.py, line 150, in forward
return jnp.take(self.weights, x, axis=0)
File [...]/jax/numpy/lax_numpy.py, line 3298, in take
slice_sizes=tuple(slice_sizes))
File [...]/jax/lax/lax.py, line 835, in gather
slice_sizes=canonicalize_shape(slice_sizes))
File [...]/site-packages/jax/core.py, line 273, in bind
return self.impl(*args, **kwargs)
File [...]/jax/interpreters/xla.py, line 228, in apply_primitive
compiled_fun = xla_primitive_callable(prim, *unsafe_map(arg_spec, args), **params)
File [...]/jax/interpreters/xla.py, line 262, in xla_primitive_callable
*avals, **params)
File [...]/jax/interpreters/xla.py, line 320, in primitive_computation
raise RuntimeError(msg) from e
RuntimeError: Invalid argument: Slice size at index 0 in gather op is out of range, must be within [0, 1), got 1.:
This is a bug in JAX's shape-checking rules; please report it!
|
LayerError
|
def _no_duplicate_dims(dims, op_name, name):
if len(set(dims)) != len(dims):
raise TypeError(f"{name} in {op_name} op must not repeat; got: {dims}.")
|
def _no_duplicate_dims(dims, name):
if len(set(dims)) != len(dims):
raise TypeError(f"{name} in scatter op must not repeat; got: {dims}.")
|
https://github.com/google/jax/issues/3905
|
LayerError Traceback (most recent call last)
<ipython-input-91-cc4d1abeffd2> in <module>
----> 1 embed_out = embed(x)
/opt/conda/lib/python3.7/site-packages/trax/layers/base.py in __call__(self, x, weights, state, rng)
165 self.state = state # Needed if the model wasn't fully initialized.
166 state = self.state
--> 167 outputs, new_state = self.pure_fn(x, weights, state, rng)
168 self.state = new_state
169 self.weights = weights
/opt/conda/lib/python3.7/site-packages/trax/layers/base.py in pure_fn(self, x, weights, state, rng, use_cache)
448 name, trace = self._name, _short_traceback(skip=3)
449 raise LayerError(name, 'pure_fn',
--> 450 self._caller, signature(x), trace) from None
451
452 def output_signature(self, input_signature):
LayerError: Exception passing through layer Embedding_9088_256 (in pure_fn):
layer created in file [...]/<ipython-input-89-4dbaf3019a8b>, line 1
layer input shapes: ShapeDtype{shape:(16, 18), dtype:int32}
File [...]/trax/layers/core.py, line 150, in forward
return jnp.take(self.weights, x, axis=0)
File [...]/jax/numpy/lax_numpy.py, line 3298, in take
slice_sizes=tuple(slice_sizes))
File [...]/jax/lax/lax.py, line 835, in gather
slice_sizes=canonicalize_shape(slice_sizes))
File [...]/site-packages/jax/core.py, line 273, in bind
return self.impl(*args, **kwargs)
File [...]/jax/interpreters/xla.py, line 228, in apply_primitive
compiled_fun = xla_primitive_callable(prim, *unsafe_map(arg_spec, args), **params)
File [...]/jax/interpreters/xla.py, line 262, in xla_primitive_callable
*avals, **params)
File [...]/jax/interpreters/xla.py, line 320, in primitive_computation
raise RuntimeError(msg) from e
RuntimeError: Invalid argument: Slice size at index 0 in gather op is out of range, must be within [0, 1), got 1.:
This is a bug in JAX's shape-checking rules; please report it!
|
LayerError
|
def _gather_shape_rule(operand, start_indices, *, dimension_numbers, slice_sizes):
"""Validates the well-formedness of the arguments to Gather.
The code implements the checks based on the detailed operation semantics of
XLA's `Gather <https://www.tensorflow.org/xla/operation_semantics#gather>`_
operator and following the outline of the implementation of
ShapeInference::InferGatherShape in TensorFlow.
"""
offset_dims = dimension_numbers.offset_dims
collapsed_slice_dims = dimension_numbers.collapsed_slice_dims
start_index_map = dimension_numbers.start_index_map
# Note: in JAX, index_vector_dim is always computed as below, cf. the
# documentation of the GatherDimensionNumbers class.
index_vector_dim = _rank(start_indices) - 1
# This case should never happen in JAX, due to the implicit construction of
# index_vector_dim, but is included for completeness.
if _rank(start_indices) < index_vector_dim or index_vector_dim < 0:
raise TypeError(
f"Gather index leaf dimension must be within [0, rank("
f"start_indices) + 1). rank(start_indices) is "
f"{_rank(start_indices)} and gather index leaf dimension "
f"is {index_vector_dim}."
)
expanded_start_indices_shape = list(start_indices.shape)
# This case should never happen in JAX, due to the implicit construction of
# index_vector_dim, but is included for completeness.
if len(expanded_start_indices_shape) == index_vector_dim:
expanded_start_indices_shape.append(1)
# Start ValidateGatherDimensions
# In the error messages output by XLA, "offset_dims" is called "Output window
# dimensions" in error messages. For consistency's sake, our error messages
# stick to "offset_dims".
_is_sorted(offset_dims, "gather", "offset_dims")
_no_duplicate_dims(offset_dims, "gather", "offset_dims")
output_offset_dim_count = len(offset_dims)
output_shape_rank = len(offset_dims) + _rank(start_indices) - 1
for i in range(output_offset_dim_count):
offset_dim = offset_dims[i]
if offset_dim < 0 or offset_dim >= output_shape_rank:
raise TypeError(
f"Offset dimension {i} in gather op is out of bounds; "
f"got {offset_dim}, but should have been in "
f"[0, {output_shape_rank})"
)
if len(start_index_map) != start_indices.shape[index_vector_dim]:
raise TypeError(
f"Gather op has {len(start_index_map)} elements in "
f"start_index_map and the bound of dimension "
f"index_vector_dim={index_vector_dim} of start_indices is "
f"{start_indices.shape[index_vector_dim]}. These two "
f"numbers must be equal."
)
for i in range(len(start_index_map)):
operand_dim_for_start_index_i = start_index_map[i]
if operand_dim_for_start_index_i < 0 or operand_dim_for_start_index_i >= _rank(
operand
):
raise TypeError(
f"Invalid start_index_map; domain is "
f"[0, {_rank(operand)}), got: "
f"{i}->{operand_dim_for_start_index_i}."
)
_no_duplicate_dims(start_index_map, "gather", "start_index_map")
# _is_sorted and _sorted_dims_in_range are checked in the opposite order
# compared to the XLA implementation. In cases when the input is not sorted
# AND there are problematic collapsed_slice_dims, the error message will thus
# be different.
_is_sorted(collapsed_slice_dims, "gather", "collapsed_slice_dims")
_sorted_dims_in_range(
collapsed_slice_dims, _rank(operand), "gather", "collapsed_slice_dims"
)
_no_duplicate_dims(collapsed_slice_dims, "gather", "collapsed_slice_dims")
# End ValidateGatherDimensions
if _rank(operand) != len(slice_sizes):
raise TypeError(
f"Gather op must have one slice size for every input "
f"dimension; got: len(slice_sizes)={len(slice_sizes)}, "
f"input_shape.rank={_rank(operand)}"
)
if len(slice_sizes) != len(offset_dims) + len(collapsed_slice_dims):
raise TypeError(
f"All components of the offset index in a gather op must "
f"either be a offset dimension or explicitly collapsed; "
f"got len(slice_sizes)={len(slice_sizes)}, "
f"output_slice_sizes={offset_dims}, collapsed_slice_dims="
f"{collapsed_slice_dims}."
)
for i in range(len(slice_sizes)):
slice_size = slice_sizes[i]
corresponding_input_size = operand.shape[i]
if slice_size < 0 or slice_size > corresponding_input_size:
raise TypeError(
f"Slice size at index {i} in gather op is out of range, "
f"must be within [0, {corresponding_input_size + 1}), "
f"got {slice_size}."
)
for i in range(len(collapsed_slice_dims)):
bound = slice_sizes[collapsed_slice_dims[i]]
if bound > 1:
raise TypeError(
f"Gather op can only collapse slice dims with bound 1 "
f"or 0, but bound is {bound} for index "
f"{collapsed_slice_dims[i]} at position {i}."
)
expanded_start_indices_shape.pop(index_vector_dim)
start_indices_shape = iter(expanded_start_indices_shape)
slice_sizes = iter(np.delete(slice_sizes, collapsed_slice_dims))
return tuple(
next(slice_sizes) if i in offset_dims else next(start_indices_shape)
for i in range(output_shape_rank)
)
|
def _gather_shape_rule(operand, start_indices, *, dimension_numbers, slice_sizes):
if len(operand.shape) != len(slice_sizes):
msg = (
"slice_sizes must have rank equal to the gather operand; "
"operand.shape={}, slice_sizes={}".format(operand.shape, slice_sizes)
)
raise ValueError(msg)
result_rank = len(dimension_numbers.offset_dims) + start_indices.ndim - 1
start_indices_shape = iter(start_indices.shape[:-1])
slice_sizes = iter(np.delete(slice_sizes, dimension_numbers.collapsed_slice_dims))
return tuple(
next(slice_sizes)
if i in dimension_numbers.offset_dims
else next(start_indices_shape)
for i in range(result_rank)
)
|
https://github.com/google/jax/issues/3905
|
LayerError Traceback (most recent call last)
<ipython-input-91-cc4d1abeffd2> in <module>
----> 1 embed_out = embed(x)
/opt/conda/lib/python3.7/site-packages/trax/layers/base.py in __call__(self, x, weights, state, rng)
165 self.state = state # Needed if the model wasn't fully initialized.
166 state = self.state
--> 167 outputs, new_state = self.pure_fn(x, weights, state, rng)
168 self.state = new_state
169 self.weights = weights
/opt/conda/lib/python3.7/site-packages/trax/layers/base.py in pure_fn(self, x, weights, state, rng, use_cache)
448 name, trace = self._name, _short_traceback(skip=3)
449 raise LayerError(name, 'pure_fn',
--> 450 self._caller, signature(x), trace) from None
451
452 def output_signature(self, input_signature):
LayerError: Exception passing through layer Embedding_9088_256 (in pure_fn):
layer created in file [...]/<ipython-input-89-4dbaf3019a8b>, line 1
layer input shapes: ShapeDtype{shape:(16, 18), dtype:int32}
File [...]/trax/layers/core.py, line 150, in forward
return jnp.take(self.weights, x, axis=0)
File [...]/jax/numpy/lax_numpy.py, line 3298, in take
slice_sizes=tuple(slice_sizes))
File [...]/jax/lax/lax.py, line 835, in gather
slice_sizes=canonicalize_shape(slice_sizes))
File [...]/site-packages/jax/core.py, line 273, in bind
return self.impl(*args, **kwargs)
File [...]/jax/interpreters/xla.py, line 228, in apply_primitive
compiled_fun = xla_primitive_callable(prim, *unsafe_map(arg_spec, args), **params)
File [...]/jax/interpreters/xla.py, line 262, in xla_primitive_callable
*avals, **params)
File [...]/jax/interpreters/xla.py, line 320, in primitive_computation
raise RuntimeError(msg) from e
RuntimeError: Invalid argument: Slice size at index 0 in gather op is out of range, must be within [0, 1), got 1.:
This is a bug in JAX's shape-checking rules; please report it!
|
LayerError
|
def _scatter_shape_rule(
operand,
scatter_indices,
updates,
*,
update_jaxpr,
update_consts,
dimension_numbers,
indices_are_sorted,
unique_indices,
):
"""Validates the well-formedness of the ``dimension_numbers`` argument to
Scatter.
The code implements the checks based on the detailed operation semantics of
XLA's `Scatter <https://www.tensorflow.org/xla/operation_semantics#scatter>`_
operator and following the outline of the implementation of
ShapeInference::InferScatterShape in TensorFlow.
"""
update_window_dims = dimension_numbers.update_window_dims
inserted_window_dims = dimension_numbers.inserted_window_dims
scatter_dims_to_operand_dims = dimension_numbers.scatter_dims_to_operand_dims
# Note: in JAX, index_vector_dim is always computed as below, cf. the
# documentation of the ScatterDimensionNumbers class.
index_vector_dim = _rank(scatter_indices) - 1
# This case should never happen in JAX, due to the implicit construction of
# index_vector_dim, but is included for completeness.
if _rank(scatter_indices) < index_vector_dim or index_vector_dim < 0:
raise TypeError(
f"Scatter index leaf dimension must be within [0, "
f"rank(scatter_indices) + 1). rank(scatter_indices) is "
f"{_rank(scatter_indices)} and scatter index leaf "
f"dimension is {index_vector_dim}."
)
expanded_scatter_indices_shape = list(scatter_indices.shape)
# This case should never happen in JAX, due to the implicit construction of
# index_vector_dim, but is included for completeness.
if len(expanded_scatter_indices_shape) == index_vector_dim:
expanded_scatter_indices_shape.append(1)
expected_updates_rank = (
len(expanded_scatter_indices_shape) - 1 + len(update_window_dims)
)
if _rank(updates) != expected_updates_rank:
raise TypeError(
f"Updates tensor must be of rank {expected_updates_rank}; "
f"got {_rank(updates)}."
)
# Validate update_window_dims
_is_sorted(update_window_dims, "scatter", "update_window_dims")
_no_duplicate_dims(update_window_dims, "scatter", "update_window_dims")
_sorted_dims_in_range(
update_window_dims, _rank(updates), "scatter", "update_window_dims"
)
# Validate inserted_window_dims
_is_sorted(inserted_window_dims, "scatter", "inserted_window_dims")
_no_duplicate_dims(inserted_window_dims, "scatter", "inserted_window_dims")
_sorted_dims_in_range(
inserted_window_dims, _rank(operand), "scatter", "inserted_window_dims"
)
# Validate window_size
window_size = len(update_window_dims) + len(inserted_window_dims)
if _rank(operand) != window_size:
raise TypeError(
f"Scatter op has window of size {window_size}; doesn't "
f"match operand of rank {_rank(operand)}."
)
# Validate scatter_dims_to_operand_dims
if len(scatter_dims_to_operand_dims) != scatter_indices.shape[index_vector_dim]:
raise TypeError(
f"Scatter op has {len(scatter_dims_to_operand_dims)} "
f"elements in scatter_dims_to_operand_dims and the bound "
f"of dimension index_vector_dim={index_vector_dim} of "
f"scatter_indices is "
f"{scatter_indices.shape[index_vector_dim]}. These two "
f"numbers must be equal"
)
for i in range(len(scatter_dims_to_operand_dims)):
dim = scatter_dims_to_operand_dims[i]
if dim < 0 or dim >= _rank(operand):
raise TypeError(
f"Invalid scatter_dims_to_operand_dims mapping; domain "
f"is [0, {_rank(operand)}), got: {i}->{dim}."
)
_no_duplicate_dims(
scatter_dims_to_operand_dims, "scatter", "scatter_dims_to_operand_dims"
)
max_update_slice_sizes = [
operand.shape[i]
for i in range(len(operand.shape))
if not i in set(inserted_window_dims)
]
for i in range(len(update_window_dims)):
update_window_dim = update_window_dims[i]
if updates.shape[update_window_dim] > max_update_slice_sizes[i]:
raise TypeError(
f"Bounds of the window dimensions of updates must not "
f"exceed the bounds of the corresponding dimensions of "
f"operand. For dimension {update_window_dim}, updates "
f"bound is {updates.shape[update_window_dim]}, operand "
f"bound is {max_update_slice_sizes[i]}."
)
update_scatter_dims = [
dim for dim in range(_rank(updates)) if dim not in set(update_window_dims)
]
scatter_dims_seen = 0
for i in update_scatter_dims:
if scatter_dims_seen == index_vector_dim:
scatter_dims_seen += 1
if updates.shape[i] != expanded_scatter_indices_shape[scatter_dims_seen]:
raise TypeError(
f"Bounds of the scatter dimensions of updates must be "
f"the same as the bounds of the corresponding dimensions "
f"of scatter indices. For scatter dimension {i}, updates "
f"bound is {updates.shape[i]}, scatter_indices bound is "
f"{expanded_scatter_indices_shape[scatter_dims_seen]}."
)
scatter_dims_seen += 1
return operand.shape
|
def _scatter_shape_rule(
operand,
scatter_indices,
updates,
*,
update_jaxpr,
update_consts,
dimension_numbers,
indices_are_sorted,
unique_indices,
):
"""Validates the well-formedness of the ``dimension_numbers`` argument to
Scatter.
The code implements the checks based on the detailed operation semantics of
XLA's `Scatter <https://www.tensorflow.org/xla/operation_semantics#scatter>`_
operator and following the outline of the implementation of
ShapeInference::InferScatterShape in TensorFlow.
"""
rank = lambda arr: len(arr.shape)
def _is_sorted(dims, name):
for i in range(1, len(dims)):
if dims[i] < dims[i - 1]:
raise TypeError(f"{name} in scatter op must be sorted; got {dims}")
def _sorted_dims_in_range(dims, rank, name):
if len(dims) == 0:
return
invalid_dim = None
if dims[0] < 0:
invalid_dim = dims[0]
elif dims[-1] >= rank:
invalid_dim = dims[-1]
if invalid_dim:
raise TypeError(
f"Invalid {name} set in scatter op; valid range is "
f"[0, {rank}); got: {invalid_dim}."
)
def _no_duplicate_dims(dims, name):
if len(set(dims)) != len(dims):
raise TypeError(f"{name} in scatter op must not repeat; got: {dims}.")
update_window_dims = dimension_numbers.update_window_dims
inserted_window_dims = dimension_numbers.inserted_window_dims
scatter_dims_to_operand_dims = dimension_numbers.scatter_dims_to_operand_dims
# Note: in JAX, index_vector_dim is always computed as below, cf. the
# documentation of the ScatterDimensionNumbers class.
index_vector_dim = rank(scatter_indices) - 1
# This case should never happen in JAX, due to the implicit construction of
# index_vector_dim, but is included for completeness.
if rank(scatter_indices) < index_vector_dim or index_vector_dim < 0:
raise TypeError(
f"Scatter index leaf dimension must be within [0, "
f"rank(scatter_indices) + 1). rank(scatter_indices) is "
f"{rank(scatter_indices)} and scatter index leaf "
f"dimension is {index_vector_dim}."
)
expanded_scatter_indices_shape = list(scatter_indices.shape)
# This case should never happen in JAX, due to the implicit construction of
# index_vector_dim, but is included for completeness.
if len(expanded_scatter_indices_shape) == index_vector_dim:
expanded_scatter_indices_shape.append(1)
expected_updates_rank = (
len(expanded_scatter_indices_shape) - 1 + len(update_window_dims)
)
if rank(updates) != expected_updates_rank:
raise TypeError(
f"Updates tensor must be of rank {expected_updates_rank}; "
f"got {rank(updates)}."
)
# Validate update_window_dims
_is_sorted(update_window_dims, "update_window_dims")
_no_duplicate_dims(update_window_dims, "update_window_dims")
_sorted_dims_in_range(update_window_dims, rank(updates), "update_window_dims")
# Validate inserted_window_dims
_is_sorted(inserted_window_dims, "inserted_window_dims")
_no_duplicate_dims(inserted_window_dims, "inserted_window_dims")
_sorted_dims_in_range(inserted_window_dims, rank(operand), "inserted_window_dims")
# Validate window_size
window_size = len(update_window_dims) + len(inserted_window_dims)
if rank(operand) != window_size:
raise TypeError(
f"Scatter op has window of size {window_size}; doesn't "
f"match operand of rank {rank(operand)}."
)
# Validate scatter_dims_to_operand_dims
if len(scatter_dims_to_operand_dims) != scatter_indices.shape[index_vector_dim]:
raise TypeError(
f"Scatter op has {len(scatter_dims_to_operand_dims)} "
f"elements in scatter_dims_to_operand_dims and the bound "
f"of dimension index_vector_dim={index_vector_dim} of "
f"scatter_indices is "
f"{scatter_indices.shape[index_vector_dim]}. These two "
f"numbers must be equal"
)
for i in range(len(scatter_dims_to_operand_dims)):
dim = scatter_dims_to_operand_dims[i]
if dim < 0 or dim >= rank(operand):
raise TypeError(
f"Invalid scatter_dims_to_operand_dims mapping; domain "
f"is [0, {rank(operand)}), got: {i}->{dim}."
)
_no_duplicate_dims(scatter_dims_to_operand_dims, "scatter_dims_to_operand_dims")
max_update_slice_sizes = [
operand.shape[i]
for i in range(len(operand.shape))
if not i in set(inserted_window_dims)
]
for i in range(len(update_window_dims)):
update_window_dim = update_window_dims[i]
if updates.shape[update_window_dim] > max_update_slice_sizes[i]:
raise TypeError(
f"Bounds of the window dimensions of updates must not "
f"exceed the bounds of the corresponding dimensions of "
f"operand. For dimension {update_window_dim}, updates "
f"bound is {updates.shape[update_window_dim]}, operand "
f"bound is {max_update_slice_sizes[i]}."
)
update_scatter_dims = [
dim for dim in range(rank(updates)) if dim not in set(update_window_dims)
]
scatter_dims_seen = 0
for i in update_scatter_dims:
if scatter_dims_seen == index_vector_dim:
scatter_dims_seen += 1
if updates.shape[i] != expanded_scatter_indices_shape[scatter_dims_seen]:
raise TypeError(
f"Bounds of the scatter dimensions of updates must be "
f"the same as the bounds of the corresponding dimensions "
f"of scatter indices. For scatter dimension {i}, updates "
f"bound is {updates.shape[i]}, scatter_indices bound is "
f"{expanded_scatter_indices_shape[scatter_dims_seen]}."
)
scatter_dims_seen += 1
return operand.shape
|
https://github.com/google/jax/issues/3905
|
LayerError Traceback (most recent call last)
<ipython-input-91-cc4d1abeffd2> in <module>
----> 1 embed_out = embed(x)
/opt/conda/lib/python3.7/site-packages/trax/layers/base.py in __call__(self, x, weights, state, rng)
165 self.state = state # Needed if the model wasn't fully initialized.
166 state = self.state
--> 167 outputs, new_state = self.pure_fn(x, weights, state, rng)
168 self.state = new_state
169 self.weights = weights
/opt/conda/lib/python3.7/site-packages/trax/layers/base.py in pure_fn(self, x, weights, state, rng, use_cache)
448 name, trace = self._name, _short_traceback(skip=3)
449 raise LayerError(name, 'pure_fn',
--> 450 self._caller, signature(x), trace) from None
451
452 def output_signature(self, input_signature):
LayerError: Exception passing through layer Embedding_9088_256 (in pure_fn):
layer created in file [...]/<ipython-input-89-4dbaf3019a8b>, line 1
layer input shapes: ShapeDtype{shape:(16, 18), dtype:int32}
File [...]/trax/layers/core.py, line 150, in forward
return jnp.take(self.weights, x, axis=0)
File [...]/jax/numpy/lax_numpy.py, line 3298, in take
slice_sizes=tuple(slice_sizes))
File [...]/jax/lax/lax.py, line 835, in gather
slice_sizes=canonicalize_shape(slice_sizes))
File [...]/site-packages/jax/core.py, line 273, in bind
return self.impl(*args, **kwargs)
File [...]/jax/interpreters/xla.py, line 228, in apply_primitive
compiled_fun = xla_primitive_callable(prim, *unsafe_map(arg_spec, args), **params)
File [...]/jax/interpreters/xla.py, line 262, in xla_primitive_callable
*avals, **params)
File [...]/jax/interpreters/xla.py, line 320, in primitive_computation
raise RuntimeError(msg) from e
RuntimeError: Invalid argument: Slice size at index 0 in gather op is out of range, must be within [0, 1), got 1.:
This is a bug in JAX's shape-checking rules; please report it!
|
LayerError
|
def choice(key, a, shape=(), replace=True, p=None):
"""Generates a random sample from a given 1-D array.
Args:
key: a PRNGKey used as the random key.
a : 1D array or int. If an ndarray, a random sample is generated from
its elements. If an int, the random sample is generated as if a were
arange(a).
shape : tuple of ints, optional. Output shape. If the given shape is,
e.g., ``(m, n)``, then ``m * n`` samples are drawn. Default is (),
in which case a single value is returned.
replace : boolean. Whether the sample is with or without replacement.
default is True.
p : 1-D array-like, The probabilities associated with each entry in a.
If not given the sample assumes a uniform distribution over all
entries in a.
Returns:
An array of shape `shape` containing samples from `a`.
"""
if not isinstance(shape, Sequence):
raise TypeError(
f"shape argument of jax.random.choice must be a sequence, got {shape}"
)
a = jnp.asarray(a)
if a.ndim not in [0, 1]:
raise ValueError("a must be an integer or 1-dimensional")
n_inputs = int(a) if a.ndim == 0 else len(a)
n_draws = prod(shape)
if n_draws == 0:
return jnp.zeros(shape, dtype=a.dtype)
if n_inputs <= 0:
raise ValueError("a must be greater than 0 unless no samples are taken")
if not replace and n_draws > n_inputs:
raise ValueError(
"Cannot take a larger sample than population when 'replace=False'"
)
if p is None:
if replace:
ind = randint(key, shape, 0, n_inputs)
result = ind if a.ndim == 0 else a[ind]
else:
result = permutation(key, a)[:n_draws]
else:
p = jnp.asarray(p)
if p.shape != (n_inputs,):
raise ValueError("p must be None or match the shape of a")
if replace:
p_cuml = jnp.cumsum(p)
r = p_cuml[-1] * (1 - uniform(key, shape))
ind = jnp.searchsorted(p_cuml, r)
result = ind if a.ndim == 0 else a[ind]
else:
# Gumbel top-k trick: https://timvieira.github.io/blog/post/2019/09/16/algorithms-for-sampling-without-replacement/
g = -gumbel(key, (n_inputs,)) - jnp.log(p)
ind = jnp.argsort(g)[:n_draws]
result = ind if a.ndim == 0 else a[ind]
return result.reshape(shape)
|
def choice(key, a, shape=(), replace=True, p=None):
"""Generates a random sample from a given 1-D array.
Args:
key: a PRNGKey used as the random key.
a : 1D array or int. If an ndarray, a random sample is generated from
its elements. If an int, the random sample is generated as if a were
arange(a).
shape : tuple of ints, optional. Output shape. If the given shape is,
e.g., ``(m, n)``, then ``m * n`` samples are drawn. Default is (),
in which case a single value is returned.
replace : boolean. Whether the sample is with or without replacement.
default is True.
p : 1-D array-like, The probabilities associated with each entry in a.
If not given the sample assumes a uniform distribution over all
entries in a.
Returns:
An array of shape `shape` containing samples from `a`.
"""
a = jnp.asarray(a)
if a.ndim not in [0, 1]:
raise ValueError("a must be an integer or 1-dimensional")
n_inputs = int(a) if a.ndim == 0 else len(a)
n_draws = prod(shape)
if n_draws == 0:
return jnp.zeros(shape, dtype=a.dtype)
if n_inputs <= 0:
raise ValueError("a must be greater than 0 unless no samples are taken")
if not replace and n_draws > n_inputs:
raise ValueError(
"Cannot take a larger sample than population when 'replace=False'"
)
if p is None:
if replace:
ind = randint(key, shape, 0, n_inputs)
result = ind if a.ndim == 0 else a[ind]
else:
result = permutation(key, a)[:n_draws]
else:
p = jnp.asarray(p)
if p.shape != (n_inputs,):
raise ValueError("p must be None or match the shape of a")
if replace:
p_cuml = jnp.cumsum(p)
r = p_cuml[-1] * (1 - uniform(key, shape))
ind = jnp.searchsorted(p_cuml, r)
result = ind if a.ndim == 0 else a[ind]
else:
# Gumbel top-k trick: https://timvieira.github.io/blog/post/2019/09/16/algorithms-for-sampling-without-replacement/
g = -gumbel(key, (n_inputs,)) - jnp.log(p)
ind = jnp.argsort(g)[:n_draws]
result = ind if a.ndim == 0 else a[ind]
return result.reshape(shape)
|
https://github.com/google/jax/issues/4124
|
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-19-56696338bc13> in <module>()
1 key = jax.random.PRNGKey(0)
2 jax.random.choice(key, 5, 2, replace=False)
----> 3 jax.random.choice(key, 5, 2, replace=True)
2 frames
/usr/local/lib/python3.6/dist-packages/jax/random.py in choice(key, a, shape, replace, p)
566 if p is None:
567 if replace:
--> 568 ind = randint(key, shape, 0, n_inputs)
569 result = ind if a.ndim == 0 else a[ind]
570 else:
/usr/local/lib/python3.6/dist-packages/jax/random.py in randint(key, shape, minval, maxval, dtype)
417 """
418 dtype = dtypes.canonicalize_dtype(dtype)
--> 419 shape = abstract_arrays.canonicalize_shape(shape)
420 return _randint(key, shape, minval, maxval, dtype)
421
/usr/local/lib/python3.6/dist-packages/jax/core.py in canonicalize_shape(shape)
1078 "got {}.")
1079 if any(isinstance(x, Tracer) and isinstance(get_aval(x), ShapedArray)
-> 1080 and not isinstance(get_aval(x), ConcreteArray) for x in shape):
1081 msg += ("\nIf using `jit`, try using `static_argnums` or applying `jit` to "
1082 "smaller subfunctions.")
TypeError: 'int' object is not iterable
|
TypeError
|
def _rewrite_eqn(
eqn: core.JaxprEqn,
eqns: List[core.JaxprEqn],
input_token_var: core.Var,
output_token_var: core.Var,
mk_new_var: Callable[[core.AbstractValue], core.Var],
):
"""Rewrite an `eqn` and append equations to `eqns`.
Assume that the current token is in `input_token_var` and the resulting
token must end in `output_token_var`.
"""
if eqn.primitive is id_tap_p:
assert "has_token_" not in eqn.params
eqns.append(
core.new_jaxpr_eqn(
eqn.invars + [input_token_var],
eqn.outvars + [output_token_var],
eqn.primitive,
dict(eqn.params, has_token_=True),
eqn.source_info,
)
)
elif eqn.primitive is lax.while_p:
cond_jaxpr, _, body_jaxpr, _ = util.split_dict(
eqn.params, ["cond_jaxpr", "cond_nconsts", "body_jaxpr", "body_nconsts"]
)
if xla.jaxpr_uses_outfeed(cond_jaxpr.jaxpr):
_rewrite_while_outfeed_cond(
eqn, eqns, input_token_var, output_token_var, mk_new_var
)
return
eqns.append(
core.new_jaxpr_eqn(
eqn.invars + [input_token_var],
eqn.outvars + [output_token_var],
eqn.primitive,
dict(
eqn.params,
body_jaxpr=_rewrite_typed_jaxpr(body_jaxpr, True, True),
cond_jaxpr=_rewrite_typed_jaxpr(cond_jaxpr, True, False),
),
eqn.source_info,
)
)
elif eqn.primitive is lax.cond_p:
branches, linear = util.split_dict(eqn.params, ["branches", "linear"])
index, *operands = eqn.invars
new_invars = [index, *operands, input_token_var]
eqns.append(
core.new_jaxpr_eqn(
new_invars,
eqn.outvars + [output_token_var],
eqn.primitive,
dict(
eqn.params,
branches=tuple(
_rewrite_typed_jaxpr(jaxpr, True, True) for jaxpr in branches
),
linear=(*linear, False),
),
eqn.source_info,
)
)
elif eqn.primitive is lax.scan_p:
num_consts, num_carry, carry_jaxpr, linear, _, _, _ = util.split_dict(
eqn.params,
[
"num_consts",
"num_carry",
"jaxpr",
"linear",
"reverse",
"length",
"unroll",
],
)
# We add the token right at the end of carry
nr_const_and_carry = num_consts + num_carry
new_invars = (
eqn.invars[0:nr_const_and_carry]
+ [input_token_var]
+ eqn.invars[nr_const_and_carry:]
)
new_jaxpr = _rewrite_typed_jaxpr(carry_jaxpr, True, True)
# The rewrite has put the token at end, it has to be at end of carry
new_jaxpr_invars = new_jaxpr.jaxpr.invars
new_jaxpr_invars = (
new_jaxpr_invars[0:nr_const_and_carry]
+ [new_jaxpr_invars[-1]]
+ new_jaxpr_invars[nr_const_and_carry:-1]
)
new_jaxpr.jaxpr.invars = new_jaxpr_invars
new_jaxpr.in_avals = [v.aval for v in new_jaxpr_invars]
new_jaxpr_outvars = new_jaxpr.jaxpr.outvars
new_jaxpr_outvars = (
new_jaxpr_outvars[0:num_carry]
+ [new_jaxpr_outvars[-1]]
+ new_jaxpr_outvars[num_carry:-1]
)
new_jaxpr.jaxpr.outvars = new_jaxpr_outvars
new_jaxpr.out_avals = [v.aval for v in new_jaxpr_outvars]
eqns.append(
core.new_jaxpr_eqn(
new_invars,
# Output token is at the end of carry result
eqn.outvars[0:num_carry] + [output_token_var] + eqn.outvars[num_carry:],
eqn.primitive,
dict(
eqn.params,
jaxpr=new_jaxpr,
num_carry=num_carry + 1,
linear=linear + (False,),
),
eqn.source_info,
)
)
elif eqn.primitive is xla.xla_call_p:
call_jaxpr = cast(core.Jaxpr, eqn.params["call_jaxpr"])
eqns.append(
core.new_jaxpr_eqn(
eqn.invars + [input_token_var],
eqn.outvars + [output_token_var],
eqn.primitive,
dict(
eqn.params,
call_jaxpr=_rewrite_jaxpr(call_jaxpr, True, True),
donated_invars=eqn.params["donated_invars"] + (False,),
),
eqn.source_info,
)
)
elif eqn.primitive is custom_derivatives.custom_jvp_call_jaxpr_p:
fun_jaxpr = eqn.params["fun_jaxpr"]
new_invars = [*eqn.invars, input_token_var]
def unreachable_thunk():
assert False, "Should not be reached"
eqns.append(
core.new_jaxpr_eqn(
new_invars,
eqn.outvars + [output_token_var],
eqn.primitive,
dict(
eqn.params,
fun_jaxpr=_rewrite_typed_jaxpr(fun_jaxpr, True, True),
jvp_jaxpr_thunk=unreachable_thunk,
),
eqn.source_info,
)
)
elif eqn.primitive is custom_derivatives.custom_vjp_call_jaxpr_p:
fun_jaxpr = eqn.params["fun_jaxpr"]
new_invars = [*eqn.invars, input_token_var]
def unreachable_thunk():
assert False, "Should not be reached"
eqns.append(
core.new_jaxpr_eqn(
new_invars,
eqn.outvars + [output_token_var],
eqn.primitive,
dict(
eqn.params,
fun_jaxpr=_rewrite_typed_jaxpr(fun_jaxpr, True, True),
fwd_jaxpr_thunk=unreachable_thunk,
# The following are illegal values for the parameters, they
# should not be needed because this rewrite is just before
# compilation to XLA, which does not use those parameters.
bwd="illegal param",
out_trees="illegal param",
),
eqn.source_info,
)
)
else:
raise NotImplementedError(f"outfeed rewrite {eqn.primitive}")
|
def _rewrite_eqn(
eqn: core.JaxprEqn,
eqns: List[core.JaxprEqn],
input_token_var: core.Var,
output_token_var: core.Var,
mk_new_var: Callable[[core.AbstractValue], core.Var],
):
"""Rewrite an `eqn` and append equations to `eqns`.
Assume that the current token is in `input_token_var` and the resulting
token must end in `output_token_var`.
"""
if eqn.primitive is id_tap_p:
assert "has_token_" not in eqn.params
eqns.append(
core.new_jaxpr_eqn(
eqn.invars + [input_token_var],
eqn.outvars + [output_token_var],
eqn.primitive,
dict(eqn.params, has_token_=True),
eqn.source_info,
)
)
elif eqn.primitive is lax.while_p:
cond_jaxpr, _, body_jaxpr, _ = util.split_dict(
eqn.params, ["cond_jaxpr", "cond_nconsts", "body_jaxpr", "body_nconsts"]
)
if xla.jaxpr_uses_outfeed(cond_jaxpr.jaxpr):
_rewrite_while_outfeed_cond(
eqn, eqns, input_token_var, output_token_var, mk_new_var
)
return
eqns.append(
core.new_jaxpr_eqn(
eqn.invars + [input_token_var],
eqn.outvars + [output_token_var],
eqn.primitive,
dict(
eqn.params,
body_jaxpr=_rewrite_typed_jaxpr(body_jaxpr, True, True),
cond_jaxpr=_rewrite_typed_jaxpr(cond_jaxpr, True, False),
),
eqn.source_info,
)
)
elif eqn.primitive is lax.cond_p:
branches, linear = util.split_dict(eqn.params, ["branches", "linear"])
index, *operands = eqn.invars
new_invars = [index, *operands, input_token_var]
eqns.append(
core.new_jaxpr_eqn(
new_invars,
eqn.outvars + [output_token_var],
eqn.primitive,
dict(
eqn.params,
branches=tuple(
_rewrite_typed_jaxpr(jaxpr, True, True) for jaxpr in branches
),
linear=(*linear, False),
),
eqn.source_info,
)
)
elif eqn.primitive is lax.scan_p:
num_consts, num_carry, carry_jaxpr, linear, _, _, _ = util.split_dict(
eqn.params,
[
"num_consts",
"num_carry",
"jaxpr",
"linear",
"reverse",
"length",
"unroll",
],
)
# We add the token right at the end of carry
nr_const_and_carry = num_consts + num_carry
new_invars = (
eqn.invars[0:nr_const_and_carry]
+ [input_token_var]
+ eqn.invars[nr_const_and_carry:]
)
new_jaxpr = _rewrite_typed_jaxpr(carry_jaxpr, True, True)
# The rewrite has put the token at end, it has to be at end of carry
new_jaxpr_invars = new_jaxpr.jaxpr.invars
new_jaxpr_invars = (
new_jaxpr_invars[0:nr_const_and_carry]
+ [new_jaxpr_invars[-1]]
+ new_jaxpr_invars[nr_const_and_carry:-1]
)
new_jaxpr.jaxpr.invars = new_jaxpr_invars
new_jaxpr.in_avals = [v.aval for v in new_jaxpr_invars]
new_jaxpr_outvars = new_jaxpr.jaxpr.outvars
new_jaxpr_outvars = (
new_jaxpr_outvars[0:num_carry]
+ [new_jaxpr_outvars[-1]]
+ new_jaxpr_outvars[num_carry:-1]
)
new_jaxpr.jaxpr.outvars = new_jaxpr_outvars
new_jaxpr.out_avals = [v.aval for v in new_jaxpr_outvars]
eqns.append(
core.new_jaxpr_eqn(
new_invars,
# Output token is at the end of carry result
eqn.outvars[0:num_carry] + [output_token_var] + eqn.outvars[num_carry:],
eqn.primitive,
dict(
eqn.params,
jaxpr=new_jaxpr,
num_carry=num_carry + 1,
linear=linear + (False,),
),
eqn.source_info,
)
)
elif eqn.primitive is xla.xla_call_p:
call_jaxpr = cast(core.Jaxpr, eqn.params["call_jaxpr"])
eqns.append(
core.new_jaxpr_eqn(
eqn.invars + [input_token_var],
eqn.outvars + [output_token_var],
eqn.primitive,
dict(eqn.params, call_jaxpr=_rewrite_jaxpr(call_jaxpr, True, True)),
eqn.source_info,
)
)
elif eqn.primitive is custom_derivatives.custom_jvp_call_jaxpr_p:
fun_jaxpr = eqn.params["fun_jaxpr"]
new_invars = [*eqn.invars, input_token_var]
def unreachable_thunk():
assert False, "Should not be reached"
eqns.append(
core.new_jaxpr_eqn(
new_invars,
eqn.outvars + [output_token_var],
eqn.primitive,
dict(
eqn.params,
fun_jaxpr=_rewrite_typed_jaxpr(fun_jaxpr, True, True),
jvp_jaxpr_thunk=unreachable_thunk,
),
eqn.source_info,
)
)
elif eqn.primitive is custom_derivatives.custom_vjp_call_jaxpr_p:
fun_jaxpr = eqn.params["fun_jaxpr"]
new_invars = [*eqn.invars, input_token_var]
def unreachable_thunk():
assert False, "Should not be reached"
eqns.append(
core.new_jaxpr_eqn(
new_invars,
eqn.outvars + [output_token_var],
eqn.primitive,
dict(
eqn.params,
fun_jaxpr=_rewrite_typed_jaxpr(fun_jaxpr, True, True),
fwd_jaxpr_thunk=unreachable_thunk,
# The following are illegal values for the parameters, they
# should not be needed because this rewrite is just before
# compilation to XLA, which does not use those parameters.
bwd="illegal param",
out_trees="illegal param",
),
eqn.source_info,
)
)
else:
raise NotImplementedError(f"outfeed rewrite {eqn.primitive}")
|
https://github.com/google/jax/issues/3863
|
Traceback (most recent call last):
File "demos/encoding.py", line 95, in <module>
encoding_demo()
File "demos/encoding.py", line 80, in encoding_demo
training_trajectory = problem.train()
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/cmm/problem/problem.py", line 31, in train
trajectory, self.model_parameters, self.iterated_function = train_model(
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/cmm/model/inference.py", line 76, in train_model
augmented, trajectory = method(model_meta_parameters,
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/api.py", line 169, in f_jitted
out = xla.xla_call(flat_fun, *args_flat, device=device, backend=backend,
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/core.py", line 1103, in call_bind
outs = primitive.impl(fun, *args, **params)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/interpreters/xla.py", line 532, in _xla_call_impl
compiled_fun = _xla_callable(fun, device, backend, name, donated_invars,
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/linear_util.py", line 221, in memoized_fun
ans = call(fun, *args)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/interpreters/xla.py", line 641, in _xla_callable
out_nodes = jaxpr_subcomp(
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/interpreters/xla.py", line 410, in jaxpr_subcomp
ans = rule(c, axis_env, extend_name_stack(name_stack, eqn.primitive.name),
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/interpreters/xla.py", line 912, in f
jaxpr, _, consts = pe.trace_to_jaxpr(
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/interpreters/partial_eval.py", line 429, in trace_to_jaxpr
jaxpr, (out_pvals, consts, env) = fun.call_wrapped(pvals)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/linear_util.py", line 150, in call_wrapped
ans = self.f(*args, **dict(self.params, **kwargs))
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/lax/lax_control_flow.py", line 1319, in _scan_impl
return _scan_impl_loop(
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/lax/lax_control_flow.py", line 1280, in _scan_impl_loop
_, *outs = while_loop(cond_fun, body_fun, init_val)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/lax/lax_control_flow.py", line 277, in while_loop
body_jaxpr, body_consts, body_tree = _initial_style_jaxpr(body_fun, in_tree, init_avals)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/lax/lax_control_flow.py", line 72, in _initial_style_jaxpr
jaxpr, out_pvals, consts, out_tree = _initial_style_untyped_jaxpr(
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/lax/lax_control_flow.py", line 66, in _initial_style_untyped_jaxpr
jaxpr, out_pvals, consts = pe.trace_to_jaxpr(
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/interpreters/partial_eval.py", line 429, in trace_to_jaxpr
jaxpr, (out_pvals, consts, env) = fun.call_wrapped(pvals)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/linear_util.py", line 150, in call_wrapped
ans = self.f(*args, **dict(self.params, **kwargs))
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/lax/lax_control_flow.py", line 1270, in body_fun
out_flat = f_impl(*consts, *carry, *x)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/core.py", line 142, in jaxpr_as_fun
return eval_jaxpr(typed_jaxpr.jaxpr, typed_jaxpr.literals, *args)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/core.py", line 346, in eval_jaxpr
ans = eqn.primitive.bind(*(subfuns + in_vals), **params)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/core.py", line 1106, in call_bind
outs = primitive.process(top_trace, fun, tracers, params)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/core.py", line 1115, in process
return trace.process_call(self, fun, tracers, params)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/interpreters/partial_eval.py", line 232, in process_call
new_params = update_params(new_params, [not t.pval.is_known() for t in tracers])
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/interpreters/xla.py", line 813, in _xla_call_partial_eval_update_params
donated_invars = [d for d, uk in zip(donated_invars, in_unknowns) if uk]
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/util.py", line 26, in safe_zip
assert len(arg) == n, 'length mismatch: {}'.format(list(map(len, args)))
AssertionError: length mismatch: [18, 19]
|
AssertionError
|
def _rewrite_while_outfeed_cond(
eqn: core.JaxprEqn,
eqns: List[core.JaxprEqn],
input_token_var: core.Var,
output_token_var: core.Var,
mk_new_var: Callable,
):
"""Rewrite a while whose cond has outfeed"""
cond_jaxpr, cond_nconsts, body_jaxpr, body_nconsts = util.split_dict(
eqn.params, ["cond_jaxpr", "cond_nconsts", "body_jaxpr", "body_nconsts"]
)
transformed_cond_jaxpr = _rewrite_typed_jaxpr(cond_jaxpr, True, True)
carry_invars = eqn.invars[cond_nconsts + body_nconsts :]
# pred1, token1 = rewrite(COND)(cond_consts, carry_invars, input_token)
pred1_and_token1 = [
mk_new_var(ov.aval) for ov in transformed_cond_jaxpr.jaxpr.outvars
]
eqns.append(
core.new_jaxpr_eqn(
eqn.invars[0:cond_nconsts] + carry_invars + [input_token_var],
pred1_and_token1,
xla.xla_call_p,
dict(
call_jaxpr=transformed_cond_jaxpr.jaxpr,
name="cond_before",
donated_invars=(False,) * len(transformed_cond_jaxpr.in_avals),
),
eqn.source_info,
)
)
# Make a new cond "lambda pred, carry, token: pred"
new_cond_pred_invar = mk_new_var(cond_jaxpr.out_avals[0])
new_cond_invars = (
[new_cond_pred_invar]
+ [mk_new_var(cv.aval) for cv in carry_invars]
+ [mk_new_var(core.abstract_token)]
)
new_cond_jaxpr = _mk_typed_jaxpr(
core.Jaxpr([], new_cond_invars, [new_cond_pred_invar], []), []
)
# Make a new body:
# "lambda cond_constvars, body_constvars, pred, carry, token:
# carry2, token2 = rewrite(BODY)(body_constvars, carry, token)
# pred2, token3 = rewrite(COND)(cond_constvars, carry2, token2)
# (pred2, carry2, token3)
transformed_body_jaxpr = _rewrite_typed_jaxpr(body_jaxpr, True, True)
new_body_invars_cond_constvars = [
mk_new_var(v.aval) for v in eqn.invars[0:cond_nconsts]
]
new_body_invars_body_constvars = [
mk_new_var(v.aval)
for v in eqn.invars[cond_nconsts : cond_nconsts + body_nconsts]
]
new_body_invars_pred = mk_new_var(cond_jaxpr.out_avals[0])
new_body_invars_carry = [mk_new_var(cv.aval) for cv in carry_invars]
new_body_invars_token = mk_new_var(core.abstract_token)
new_body_carry2 = [mk_new_var(cv.aval) for cv in carry_invars]
new_body_token2 = mk_new_var(core.abstract_token)
new_body_pred2 = mk_new_var(cond_jaxpr.out_avals[0])
new_body_token3 = mk_new_var(core.abstract_token)
new_body_eqns = [
core.new_jaxpr_eqn(
new_body_invars_body_constvars
+ new_body_invars_carry
+ [new_body_invars_token],
new_body_carry2 + [new_body_token2],
xla.xla_call_p,
dict(
call_jaxpr=transformed_body_jaxpr.jaxpr,
name="body",
donated_invars=(False,) * len(transformed_body_jaxpr.in_avals),
),
eqn.source_info,
),
core.new_jaxpr_eqn(
new_body_invars_cond_constvars + new_body_carry2 + [new_body_token2],
[new_body_pred2, new_body_token3],
xla.xla_call_p,
dict(
call_jaxpr=transformed_cond_jaxpr.jaxpr,
name="cond_body",
donated_invars=(False,) * len(transformed_cond_jaxpr.in_avals),
),
eqn.source_info,
),
]
new_body_jaxpr = _mk_typed_jaxpr(
core.Jaxpr(
[],
(
new_body_invars_cond_constvars
+ new_body_invars_body_constvars
+ [new_body_invars_pred]
+ new_body_invars_carry
+ [new_body_invars_token]
),
([new_body_pred2] + new_body_carry2 + [new_body_token3]),
new_body_eqns,
),
[],
)
pred_out = mk_new_var(cond_jaxpr.out_avals[0])
eqns.append(
core.new_jaxpr_eqn(
(
eqn.invars[0 : cond_nconsts + body_nconsts]
+ [pred1_and_token1[0]]
+ carry_invars
+ [pred1_and_token1[1]]
),
([pred_out] + eqn.outvars + [output_token_var]),
lax.while_p,
dict(
cond_jaxpr=new_cond_jaxpr,
cond_nconsts=0,
body_jaxpr=new_body_jaxpr,
body_nconsts=cond_nconsts + body_nconsts,
),
eqn.source_info,
)
)
|
def _rewrite_while_outfeed_cond(
eqn: core.JaxprEqn,
eqns: List[core.JaxprEqn],
input_token_var: core.Var,
output_token_var: core.Var,
mk_new_var: Callable,
):
"""Rewrite a while whose cond has outfeed"""
cond_jaxpr, cond_nconsts, body_jaxpr, body_nconsts = util.split_dict(
eqn.params, ["cond_jaxpr", "cond_nconsts", "body_jaxpr", "body_nconsts"]
)
transformed_cond_jaxpr = _rewrite_typed_jaxpr(cond_jaxpr, True, True)
carry_invars = eqn.invars[cond_nconsts + body_nconsts :]
# pred1, token1 = rewrite(COND)(cond_consts, carry_invars, input_token)
pred1_and_token1 = [
mk_new_var(ov.aval) for ov in transformed_cond_jaxpr.jaxpr.outvars
]
eqns.append(
core.new_jaxpr_eqn(
eqn.invars[0:cond_nconsts] + carry_invars + [input_token_var],
pred1_and_token1,
xla.xla_call_p,
dict(
call_jaxpr=transformed_cond_jaxpr.jaxpr,
name="cond_before",
donated_invars=(False,) * (cond_nconsts + len(carry_invars) + 1),
),
eqn.source_info,
)
)
# Make a new cond "lambda pred, carry, token: pred"
new_cond_pred_invar = mk_new_var(cond_jaxpr.out_avals[0])
new_cond_invars = (
[new_cond_pred_invar]
+ [mk_new_var(cv.aval) for cv in carry_invars]
+ [mk_new_var(core.abstract_token)]
)
new_cond_jaxpr = _mk_typed_jaxpr(
core.Jaxpr([], new_cond_invars, [new_cond_pred_invar], []), []
)
# Make a new body:
# "lambda cond_constvars, body_constvars, pred, carry, token:
# carry2, token2 = rewrite(BODY)(body_constvars, carry, token)
# pred2, token3 = rewrite(COND)(cond_constvars, carry2, token2)
# (pred2, carry2, token3)
transformed_body_jaxpr = _rewrite_typed_jaxpr(body_jaxpr, True, True)
new_body_invars_cond_constvars = [
mk_new_var(v.aval) for v in eqn.invars[0:cond_nconsts]
]
new_body_invars_body_constvars = [
mk_new_var(v.aval)
for v in eqn.invars[cond_nconsts : cond_nconsts + body_nconsts]
]
new_body_invars_pred = mk_new_var(cond_jaxpr.out_avals[0])
new_body_invars_carry = [mk_new_var(cv.aval) for cv in carry_invars]
new_body_invars_token = mk_new_var(core.abstract_token)
new_body_carry2 = [mk_new_var(cv.aval) for cv in carry_invars]
new_body_token2 = mk_new_var(core.abstract_token)
new_body_pred2 = mk_new_var(cond_jaxpr.out_avals[0])
new_body_token3 = mk_new_var(core.abstract_token)
new_body_eqns = [
core.new_jaxpr_eqn(
new_body_invars_body_constvars
+ new_body_invars_carry
+ [new_body_invars_token],
new_body_carry2 + [new_body_token2],
xla.xla_call_p,
dict(
call_jaxpr=transformed_body_jaxpr.jaxpr,
name="body",
donated_invars=(False,)
* (
len(new_body_invars_body_constvars)
+ len(new_body_invars_carry)
+ 1
+ len(new_body_carry2)
+ 1
),
),
eqn.source_info,
),
core.new_jaxpr_eqn(
new_body_invars_cond_constvars + new_body_carry2 + [new_body_token2],
[new_body_pred2, new_body_token3],
xla.xla_call_p,
dict(
call_jaxpr=transformed_cond_jaxpr.jaxpr,
name="cond_body",
donated_invars=(False,)
* (len(new_body_invars_cond_constvars) + len(new_body_carry2) + 1 + 2),
),
eqn.source_info,
),
]
new_body_jaxpr = _mk_typed_jaxpr(
core.Jaxpr(
[],
(
new_body_invars_cond_constvars
+ new_body_invars_body_constvars
+ [new_body_invars_pred]
+ new_body_invars_carry
+ [new_body_invars_token]
),
([new_body_pred2] + new_body_carry2 + [new_body_token3]),
new_body_eqns,
),
[],
)
pred_out = mk_new_var(cond_jaxpr.out_avals[0])
eqns.append(
core.new_jaxpr_eqn(
(
eqn.invars[0 : cond_nconsts + body_nconsts]
+ [pred1_and_token1[0]]
+ carry_invars
+ [pred1_and_token1[1]]
),
([pred_out] + eqn.outvars + [output_token_var]),
lax.while_p,
dict(
cond_jaxpr=new_cond_jaxpr,
cond_nconsts=0,
body_jaxpr=new_body_jaxpr,
body_nconsts=cond_nconsts + body_nconsts,
),
eqn.source_info,
)
)
|
https://github.com/google/jax/issues/3863
|
Traceback (most recent call last):
File "demos/encoding.py", line 95, in <module>
encoding_demo()
File "demos/encoding.py", line 80, in encoding_demo
training_trajectory = problem.train()
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/cmm/problem/problem.py", line 31, in train
trajectory, self.model_parameters, self.iterated_function = train_model(
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/cmm/model/inference.py", line 76, in train_model
augmented, trajectory = method(model_meta_parameters,
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/api.py", line 169, in f_jitted
out = xla.xla_call(flat_fun, *args_flat, device=device, backend=backend,
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/core.py", line 1103, in call_bind
outs = primitive.impl(fun, *args, **params)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/interpreters/xla.py", line 532, in _xla_call_impl
compiled_fun = _xla_callable(fun, device, backend, name, donated_invars,
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/linear_util.py", line 221, in memoized_fun
ans = call(fun, *args)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/interpreters/xla.py", line 641, in _xla_callable
out_nodes = jaxpr_subcomp(
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/interpreters/xla.py", line 410, in jaxpr_subcomp
ans = rule(c, axis_env, extend_name_stack(name_stack, eqn.primitive.name),
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/interpreters/xla.py", line 912, in f
jaxpr, _, consts = pe.trace_to_jaxpr(
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/interpreters/partial_eval.py", line 429, in trace_to_jaxpr
jaxpr, (out_pvals, consts, env) = fun.call_wrapped(pvals)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/linear_util.py", line 150, in call_wrapped
ans = self.f(*args, **dict(self.params, **kwargs))
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/lax/lax_control_flow.py", line 1319, in _scan_impl
return _scan_impl_loop(
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/lax/lax_control_flow.py", line 1280, in _scan_impl_loop
_, *outs = while_loop(cond_fun, body_fun, init_val)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/lax/lax_control_flow.py", line 277, in while_loop
body_jaxpr, body_consts, body_tree = _initial_style_jaxpr(body_fun, in_tree, init_avals)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/lax/lax_control_flow.py", line 72, in _initial_style_jaxpr
jaxpr, out_pvals, consts, out_tree = _initial_style_untyped_jaxpr(
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/lax/lax_control_flow.py", line 66, in _initial_style_untyped_jaxpr
jaxpr, out_pvals, consts = pe.trace_to_jaxpr(
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/interpreters/partial_eval.py", line 429, in trace_to_jaxpr
jaxpr, (out_pvals, consts, env) = fun.call_wrapped(pvals)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/linear_util.py", line 150, in call_wrapped
ans = self.f(*args, **dict(self.params, **kwargs))
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/lax/lax_control_flow.py", line 1270, in body_fun
out_flat = f_impl(*consts, *carry, *x)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/core.py", line 142, in jaxpr_as_fun
return eval_jaxpr(typed_jaxpr.jaxpr, typed_jaxpr.literals, *args)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/core.py", line 346, in eval_jaxpr
ans = eqn.primitive.bind(*(subfuns + in_vals), **params)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/core.py", line 1106, in call_bind
outs = primitive.process(top_trace, fun, tracers, params)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/core.py", line 1115, in process
return trace.process_call(self, fun, tracers, params)
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/interpreters/partial_eval.py", line 232, in process_call
new_params = update_params(new_params, [not t.pval.is_known() for t in tracers])
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/interpreters/xla.py", line 813, in _xla_call_partial_eval_update_params
donated_invars = [d for d, uk in zip(donated_invars, in_unknowns) if uk]
File "/home/neil/.pyenv/versions/3.8.2/lib/python3.8/site-packages/jax/util.py", line 26, in safe_zip
assert len(arg) == n, 'length mismatch: {}'.format(list(map(len, args)))
AssertionError: length mismatch: [18, 19]
|
AssertionError
|
def population_count(x):
assert np.issubdtype(x.dtype, np.integer)
dtype = x.dtype
iinfo = np.iinfo(x.dtype)
if np.iinfo(x.dtype).bits < 32:
assert iinfo.kind in ("i", "u")
x = x.astype(np.uint32 if iinfo.kind == "u" else np.int32)
if iinfo.kind == "i":
x = x.view(f"uint{np.iinfo(x.dtype).bits}")
assert x.dtype in (np.uint32, np.uint64)
m = [
0x5555555555555555, # binary: 0101...
0x3333333333333333, # binary: 00110011..
0x0F0F0F0F0F0F0F0F, # binary: 4 zeros, 4 ones ...
0x00FF00FF00FF00FF, # binary: 8 zeros, 8 ones ...
0x0000FFFF0000FFFF, # binary: 16 zeros, 16 ones ...
0x00000000FFFFFFFF, # binary: 32 zeros, 32 ones
]
if x.dtype == np.uint32:
m = list(map(np.uint32, m[:-1]))
else:
m = list(map(np.uint64, m))
x = (x & m[0]) + ((x >> 1) & m[0]) # put count of each 2 bits into those 2 bits
x = (x & m[1]) + ((x >> 2) & m[1]) # put count of each 4 bits into those 4 bits
x = (x & m[2]) + ((x >> 4) & m[2]) # put count of each 8 bits into those 8 bits
x = (x & m[3]) + ((x >> 8) & m[3]) # put count of each 16 bits into those 16 bits
x = (x & m[4]) + ((x >> 16) & m[4]) # put count of each 32 bits into those 32 bits
if x.dtype == np.uint64:
x = (x & m[5]) + (
(x >> 32) & m[5]
) # put count of each 64 bits into those 64 bits
return x.astype(dtype)
|
def population_count(x):
dtype = x.dtype
if x.dtype in (np.uint8, np.uint16):
x = x.astype(np.uint32)
assert x.dtype in (np.uint32, np.uint64)
m = [
0x5555555555555555, # binary: 0101...
0x3333333333333333, # binary: 00110011..
0x0F0F0F0F0F0F0F0F, # binary: 4 zeros, 4 ones ...
0x00FF00FF00FF00FF, # binary: 8 zeros, 8 ones ...
0x0000FFFF0000FFFF, # binary: 16 zeros, 16 ones ...
0x00000000FFFFFFFF, # binary: 32 zeros, 32 ones
]
if x.dtype == np.uint32:
m = list(map(np.uint32, m[:-1]))
else:
m = list(map(np.uint64, m))
x = (x & m[0]) + ((x >> 1) & m[0]) # put count of each 2 bits into those 2 bits
x = (x & m[1]) + ((x >> 2) & m[1]) # put count of each 4 bits into those 4 bits
x = (x & m[2]) + ((x >> 4) & m[2]) # put count of each 8 bits into those 8 bits
x = (x & m[3]) + ((x >> 8) & m[3]) # put count of each 16 bits into those 16 bits
x = (x & m[4]) + ((x >> 16) & m[4]) # put count of each 32 bits into those 32 bits
if x.dtype == np.uint64:
x = (x & m[5]) + (
(x >> 32) & m[5]
) # put count of each 64 bits into those 64 bits
return x.astype(dtype)
|
https://github.com/google/jax/issues/3886
|
lax.population_count(np.array([True, False], dtype=np.bool_))
Traceback (most recent call last):
File "/jax/jax/interpreters/xla.py", line 311, in primitive_computation
return c.build()
RuntimeError: Invalid argument: Expected an integral element type in argument to PopulationCount operation; got PRED.:
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/jax/jax/lax/lax.py", line 296, in population_count
return population_count_p.bind(x)
File "/jax/jax/core.py", line 275, in bind
return self.impl(*args, **kwargs)
File "/jax/jax/interpreters/xla.py", line 224, in apply_primitive
compiled_fun = xla_primitive_callable(prim, *unsafe_map(arg_spec, args), **params)
File "/jax/jax/interpreters/xla.py", line 257, in xla_primitive_callable
built_c = primitive_computation(prim, AxisEnv(nreps), backend, tuple_args,
File "/jax/jax/interpreters/xla.py", line 316, in primitive_computation
raise RuntimeError(msg) from e
RuntimeError: Invalid argument: Expected an integral element type in argument to PopulationCount operation; got PRED.:
This is a bug in JAX's shape-checking rules; please report it!
https://github.com/google/jax/issues
|
RuntimeError
|
def _reduce_prod_jvp_rule(primals, tangents, *, axes):
(operand,) = primals
(tangent,) = tangents
input_shape = onp.array(operand.shape)
n = onp.prod(input_shape[list(axes)])
non_axes = onp.delete(onp.arange(len(input_shape)), axes)
# Move the reduced axes to the front, and flatten them to 1D.
permutation = axes + tuple(non_axes)
new_shape = (n,) + tuple(input_shape[non_axes])
operand = reshape(operand, new_shape, permutation)
tangent = reshape(tangent, new_shape, permutation)
def _reduce_prod_tree(x, axis=0):
"""Reduce by repeatedly splitting the array and multiplying."""
while x.shape[axis] > 1:
n = x.shape[axis]
n1 = (n + 1) // 2
n2 = n - n1
x1 = slice_in_dim(x, 0, n1)
x2 = slice_in_dim(x, n1, None)
if n2 != n1:
paddings = [(0, 0, 0)] * len(x.shape)
paddings[axis] = (0, 1, 0)
x2 = pad(x2, _const(x, 1), paddings)
x = x1 * x2
if x.shape[axis] == 0:
return full(input_shape[non_axes], _one(x))
return squeeze(x, (axis,))
return api.jvp(_reduce_prod_tree, (operand,), (tangent,))
|
def _reduce_prod_jvp_rule(primals, tangents, *, axes):
(operand,) = primals
(tangent,) = tangents
input_shape = onp.array(operand.shape)
n = onp.prod(input_shape[list(axes)])
non_axes = onp.delete(onp.arange(len(input_shape)), axes)
# Move the reduced axes to the front, and flatten them to 1D.
permutation = axes + tuple(non_axes)
new_shape = (n,) + tuple(input_shape[non_axes])
operand = reshape(operand, new_shape, permutation)
tangent = reshape(tangent, new_shape, permutation)
def _reduce_prod_tree(x, axis=0):
"""Reduce by repeatedly splitting the array and multiplying."""
while x.shape[axis] > 1:
n = x.shape[axis]
n1 = (n + 1) // 2
n2 = n - n1
x1 = slice_in_dim(x, 0, n1)
x2 = slice_in_dim(x, n1, None)
if n2 != n1:
paddings = [(0, 0, 0)] * len(x.shape)
paddings[axis] = (0, 1, 0)
x2 = pad(x2, _const(x, 1), paddings)
x = x1 * x2
shape = list(x.shape)
del shape[axis]
return reshape(x, shape)
return api.jvp(_reduce_prod_tree, (operand,), (tangent,))
|
https://github.com/google/jax/issues/1888
|
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/jax/interpreters/xla.py in primitive_computation(prim, *avals, **params)
179 try:
--> 180 return c.Build()
181 except RuntimeError as e:
23 frames
/usr/local/lib/python3.6/dist-packages/jax/lib/xla_bridge.py in Build(self, *args, **kwargs)
256 return super(_JaxComputationBuilder, self).Build(
--> 257 *args, **kwargs)
258
/usr/local/lib/python3.6/dist-packages/jaxlib/xla_client.py in Build(self, root, backend)
729 else:
--> 730 return Computation(self._builder.Build(), backend=backend)
731
RuntimeError: Invalid argument: Padding result in negative size for dimension 0:
During handling of the above exception, another exception occurred:
RuntimeError Traceback (most recent call last)
<ipython-input-2-26b18538a688> in <module>()
----> 1 jax.grad(lambda params: np.prod(np.take(params, np.array([], np.int32), axis=0)))(np.ones(6))
/usr/local/lib/python3.6/dist-packages/jax/api.py in grad_f(*args, **kwargs)
345 @wraps(fun, docstr=docstr, argnums=argnums)
346 def grad_f(*args, **kwargs):
--> 347 _, g = value_and_grad_f(*args, **kwargs)
348 return g
349
/usr/local/lib/python3.6/dist-packages/jax/api.py in value_and_grad_f(*args, **kwargs)
400 f_partial, dyn_args = _argnums_partial(f, argnums, args)
401 if not has_aux:
--> 402 ans, vjp_py = vjp(f_partial, *dyn_args)
403 else:
404 ans, vjp_py, aux = vjp(f_partial, *dyn_args, has_aux=True)
/usr/local/lib/python3.6/dist-packages/jax/api.py in vjp(fun, *primals, **kwargs)
1255 if not has_aux:
1256 flat_fun, out_tree = flatten_fun_nokwargs(fun, in_tree)
-> 1257 out_primal, out_vjp = ad.vjp(flat_fun, primals_flat)
1258 out_tree = out_tree()
1259 else:
/usr/local/lib/python3.6/dist-packages/jax/interpreters/ad.py in vjp(traceable, primals, has_aux)
105 def vjp(traceable, primals, has_aux=False):
106 if not has_aux:
--> 107 out_primals, pvals, jaxpr, consts = linearize(traceable, *primals)
108 else:
109 out_primals, pvals, jaxpr, consts, aux = linearize(traceable, *primals, has_aux=True)
/usr/local/lib/python3.6/dist-packages/jax/interpreters/ad.py in linearize(traceable, *primals, **kwargs)
94 _, in_tree = tree_flatten(((primals, primals), {}))
95 jvpfun_flat, out_tree = flatten_fun(jvpfun, in_tree)
---> 96 jaxpr, out_pvals, consts = pe.trace_to_jaxpr(jvpfun_flat, in_pvals)
97 pval_primals, pval_tangents = tree_unflatten(out_tree(), out_pvals)
98 aval_primals, const_primals = unzip2(pval_primals)
/usr/local/lib/python3.6/dist-packages/jax/interpreters/partial_eval.py in trace_to_jaxpr(fun, pvals, **kwargs)
341 with new_master(JaxprTrace) as master:
342 fun = trace_to_subjaxpr(fun, master, instantiate)
--> 343 jaxpr, (out_pvals, consts, env) = fun.call_wrapped(pvals)
344 assert not env
345 del master
/usr/local/lib/python3.6/dist-packages/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
151
152 del gen
--> 153 ans = self.f(*args, **dict(self.params, **kwargs))
154 del args
155 while stack:
<ipython-input-2-26b18538a688> in <lambda>(params)
----> 1 jax.grad(lambda params: np.prod(np.take(params, np.array([], np.int32), axis=0)))(np.ones(6))
/usr/local/lib/python3.6/dist-packages/jax/numpy/lax_numpy.py in reduction(a, axis, dtype, out, keepdims)
1127 if _dtype(a) != result_dtype:
1128 a = lax.convert_element_type(a, result_dtype)
-> 1129 result = lax.reduce(a, _reduction_init_val(a, init_val), op, dims)
1130 if keepdims:
1131 shape_with_singletons = lax.subvals(shape(a), zip(dims, (1,) * len(dims)))
/usr/local/lib/python3.6/dist-packages/jax/lax/lax.py in reduce(operand, init_value, computation, dimensions)
874 monoid_reducer = _get_monoid_reducer(computation, init_value)
875 if monoid_reducer:
--> 876 return monoid_reducer(operand, dimensions)
877 else:
878 jaxpr, consts = _reduction_jaxpr(computation, _abstractify(init_value))
/usr/local/lib/python3.6/dist-packages/jax/lax/lax.py in _reduce_prod(operand, axes)
925
926 def _reduce_prod(operand, axes):
--> 927 return reduce_prod_p.bind(operand, axes=tuple(axes))
928
929 def _reduce_max(operand, axes):
/usr/local/lib/python3.6/dist-packages/jax/core.py in bind(self, *args, **kwargs)
153
154 tracers = map(top_trace.full_raise, args)
--> 155 out_tracer = top_trace.process_primitive(self, tracers, kwargs)
156 if self.multiple_results:
157 return map(full_lower, out_tracer)
/usr/local/lib/python3.6/dist-packages/jax/interpreters/ad.py in process_primitive(self, primitive, tracers, params)
220 "Forward-mode differentiation rule for '{}' not implemented"
221 .format(primitive))
--> 222 primal_out, tangent_out = jvp(primals_in, tangents_in, **params)
223 if primitive.multiple_results:
224 return [JVPTracer(self, x, t) for x, t in zip(primal_out, tangent_out)]
/usr/local/lib/python3.6/dist-packages/jax/interpreters/ad.py in standard_jvp(jvprules, primitive, primals, tangents, **params)
319 def standard_jvp(jvprules, primitive, primals, tangents, **params):
320 val_out = primitive.bind(*primals, **params)
--> 321 tangents_out = [rule(t, *primals, **params) for rule, t in zip(jvprules, tangents)
322 if rule is not None and t is not zero]
323 return val_out, reduce(add_tangents, tangents_out, zero)
/usr/local/lib/python3.6/dist-packages/jax/interpreters/ad.py in <listcomp>(.0)
320 val_out = primitive.bind(*primals, **params)
321 tangents_out = [rule(t, *primals, **params) for rule, t in zip(jvprules, tangents)
--> 322 if rule is not None and t is not zero]
323 return val_out, reduce(add_tangents, tangents_out, zero)
324
/usr/local/lib/python3.6/dist-packages/jax/lax/lax.py in _reduce_prod_jvp_rule(tangent, operand, axes)
3410 left_padding = [(n, -1, 0)] + [(0, 0, 0)] * len(non_axes)
3411 right_padding = [(-1, n, 0)] + [(0, 0, 0)] * len(non_axes)
-> 3412 left_products = _reduce_window_prod(pad(operand, one, left_padding),
3413 window_dims, window_strides,
3414 xla_client.PaddingType.VALID)
/usr/local/lib/python3.6/dist-packages/jax/lax/lax.py in pad(operand, padding_value, padding_config)
634 operator.
635 """
--> 636 return pad_p.bind(operand, padding_value, padding_config=tuple(padding_config))
637
638 def rev(operand, dimensions):
/usr/local/lib/python3.6/dist-packages/jax/core.py in bind(self, *args, **kwargs)
150 top_trace = find_top_trace(args)
151 if top_trace is None:
--> 152 return self.impl(*args, **kwargs)
153
154 tracers = map(top_trace.full_raise, args)
/usr/local/lib/python3.6/dist-packages/jax/interpreters/xla.py in apply_primitive(prim, *args, **params)
138 """Impl rule that compiles and runs a single primitive 'prim' using XLA."""
139 abstract_args = map(abstractify, args)
--> 140 compiled_fun = xla_primitive_callable(prim, *abstract_args, **params)
141 return compiled_fun(*args)
142
/usr/local/lib/python3.6/dist-packages/jax/interpreters/xla.py in xla_primitive_callable(prim, *abstract_args, **params)
150 else:
151 handle_result = aval_to_result_handler(aval_out)
--> 152 built_c = primitive_computation(prim, *abstract_args, **params)
153 compiled = built_c.Compile(compile_options=xb.get_compile_options(),
154 backend=xb.get_backend(backend))
/usr/local/lib/python3.6/dist-packages/jax/interpreters/xla.py in primitive_computation(prim, *avals, **params)
183 "This is a bug in JAX's shape-checking rules; please report it!\n"
184 "https://github.com/google/jax/issues\n")
--> 185 raise RuntimeError(msg)
186
187 def _execute_compiled_primitive(prim, compiled, backend, result_handler, *args):
RuntimeError: Invalid argument: Padding result in negative size for dimension 0:
This is a bug in JAX's shape-checking rules; please report it!
https://github.com/google/jax/issues
|
RuntimeError
|
def _reduce_prod_tree(x, axis=0):
"""Reduce by repeatedly splitting the array and multiplying."""
while x.shape[axis] > 1:
n = x.shape[axis]
n1 = (n + 1) // 2
n2 = n - n1
x1 = slice_in_dim(x, 0, n1)
x2 = slice_in_dim(x, n1, None)
if n2 != n1:
paddings = [(0, 0, 0)] * len(x.shape)
paddings[axis] = (0, 1, 0)
x2 = pad(x2, _const(x, 1), paddings)
x = x1 * x2
if x.shape[axis] == 0:
return full(input_shape[non_axes], _one(x))
return squeeze(x, (axis,))
|
def _reduce_prod_tree(x, axis=0):
"""Reduce by repeatedly splitting the array and multiplying."""
while x.shape[axis] > 1:
n = x.shape[axis]
n1 = (n + 1) // 2
n2 = n - n1
x1 = slice_in_dim(x, 0, n1)
x2 = slice_in_dim(x, n1, None)
if n2 != n1:
paddings = [(0, 0, 0)] * len(x.shape)
paddings[axis] = (0, 1, 0)
x2 = pad(x2, _const(x, 1), paddings)
x = x1 * x2
shape = list(x.shape)
del shape[axis]
return reshape(x, shape)
|
https://github.com/google/jax/issues/1888
|
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/jax/interpreters/xla.py in primitive_computation(prim, *avals, **params)
179 try:
--> 180 return c.Build()
181 except RuntimeError as e:
23 frames
/usr/local/lib/python3.6/dist-packages/jax/lib/xla_bridge.py in Build(self, *args, **kwargs)
256 return super(_JaxComputationBuilder, self).Build(
--> 257 *args, **kwargs)
258
/usr/local/lib/python3.6/dist-packages/jaxlib/xla_client.py in Build(self, root, backend)
729 else:
--> 730 return Computation(self._builder.Build(), backend=backend)
731
RuntimeError: Invalid argument: Padding result in negative size for dimension 0:
During handling of the above exception, another exception occurred:
RuntimeError Traceback (most recent call last)
<ipython-input-2-26b18538a688> in <module>()
----> 1 jax.grad(lambda params: np.prod(np.take(params, np.array([], np.int32), axis=0)))(np.ones(6))
/usr/local/lib/python3.6/dist-packages/jax/api.py in grad_f(*args, **kwargs)
345 @wraps(fun, docstr=docstr, argnums=argnums)
346 def grad_f(*args, **kwargs):
--> 347 _, g = value_and_grad_f(*args, **kwargs)
348 return g
349
/usr/local/lib/python3.6/dist-packages/jax/api.py in value_and_grad_f(*args, **kwargs)
400 f_partial, dyn_args = _argnums_partial(f, argnums, args)
401 if not has_aux:
--> 402 ans, vjp_py = vjp(f_partial, *dyn_args)
403 else:
404 ans, vjp_py, aux = vjp(f_partial, *dyn_args, has_aux=True)
/usr/local/lib/python3.6/dist-packages/jax/api.py in vjp(fun, *primals, **kwargs)
1255 if not has_aux:
1256 flat_fun, out_tree = flatten_fun_nokwargs(fun, in_tree)
-> 1257 out_primal, out_vjp = ad.vjp(flat_fun, primals_flat)
1258 out_tree = out_tree()
1259 else:
/usr/local/lib/python3.6/dist-packages/jax/interpreters/ad.py in vjp(traceable, primals, has_aux)
105 def vjp(traceable, primals, has_aux=False):
106 if not has_aux:
--> 107 out_primals, pvals, jaxpr, consts = linearize(traceable, *primals)
108 else:
109 out_primals, pvals, jaxpr, consts, aux = linearize(traceable, *primals, has_aux=True)
/usr/local/lib/python3.6/dist-packages/jax/interpreters/ad.py in linearize(traceable, *primals, **kwargs)
94 _, in_tree = tree_flatten(((primals, primals), {}))
95 jvpfun_flat, out_tree = flatten_fun(jvpfun, in_tree)
---> 96 jaxpr, out_pvals, consts = pe.trace_to_jaxpr(jvpfun_flat, in_pvals)
97 pval_primals, pval_tangents = tree_unflatten(out_tree(), out_pvals)
98 aval_primals, const_primals = unzip2(pval_primals)
/usr/local/lib/python3.6/dist-packages/jax/interpreters/partial_eval.py in trace_to_jaxpr(fun, pvals, **kwargs)
341 with new_master(JaxprTrace) as master:
342 fun = trace_to_subjaxpr(fun, master, instantiate)
--> 343 jaxpr, (out_pvals, consts, env) = fun.call_wrapped(pvals)
344 assert not env
345 del master
/usr/local/lib/python3.6/dist-packages/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
151
152 del gen
--> 153 ans = self.f(*args, **dict(self.params, **kwargs))
154 del args
155 while stack:
<ipython-input-2-26b18538a688> in <lambda>(params)
----> 1 jax.grad(lambda params: np.prod(np.take(params, np.array([], np.int32), axis=0)))(np.ones(6))
/usr/local/lib/python3.6/dist-packages/jax/numpy/lax_numpy.py in reduction(a, axis, dtype, out, keepdims)
1127 if _dtype(a) != result_dtype:
1128 a = lax.convert_element_type(a, result_dtype)
-> 1129 result = lax.reduce(a, _reduction_init_val(a, init_val), op, dims)
1130 if keepdims:
1131 shape_with_singletons = lax.subvals(shape(a), zip(dims, (1,) * len(dims)))
/usr/local/lib/python3.6/dist-packages/jax/lax/lax.py in reduce(operand, init_value, computation, dimensions)
874 monoid_reducer = _get_monoid_reducer(computation, init_value)
875 if monoid_reducer:
--> 876 return monoid_reducer(operand, dimensions)
877 else:
878 jaxpr, consts = _reduction_jaxpr(computation, _abstractify(init_value))
/usr/local/lib/python3.6/dist-packages/jax/lax/lax.py in _reduce_prod(operand, axes)
925
926 def _reduce_prod(operand, axes):
--> 927 return reduce_prod_p.bind(operand, axes=tuple(axes))
928
929 def _reduce_max(operand, axes):
/usr/local/lib/python3.6/dist-packages/jax/core.py in bind(self, *args, **kwargs)
153
154 tracers = map(top_trace.full_raise, args)
--> 155 out_tracer = top_trace.process_primitive(self, tracers, kwargs)
156 if self.multiple_results:
157 return map(full_lower, out_tracer)
/usr/local/lib/python3.6/dist-packages/jax/interpreters/ad.py in process_primitive(self, primitive, tracers, params)
220 "Forward-mode differentiation rule for '{}' not implemented"
221 .format(primitive))
--> 222 primal_out, tangent_out = jvp(primals_in, tangents_in, **params)
223 if primitive.multiple_results:
224 return [JVPTracer(self, x, t) for x, t in zip(primal_out, tangent_out)]
/usr/local/lib/python3.6/dist-packages/jax/interpreters/ad.py in standard_jvp(jvprules, primitive, primals, tangents, **params)
319 def standard_jvp(jvprules, primitive, primals, tangents, **params):
320 val_out = primitive.bind(*primals, **params)
--> 321 tangents_out = [rule(t, *primals, **params) for rule, t in zip(jvprules, tangents)
322 if rule is not None and t is not zero]
323 return val_out, reduce(add_tangents, tangents_out, zero)
/usr/local/lib/python3.6/dist-packages/jax/interpreters/ad.py in <listcomp>(.0)
320 val_out = primitive.bind(*primals, **params)
321 tangents_out = [rule(t, *primals, **params) for rule, t in zip(jvprules, tangents)
--> 322 if rule is not None and t is not zero]
323 return val_out, reduce(add_tangents, tangents_out, zero)
324
/usr/local/lib/python3.6/dist-packages/jax/lax/lax.py in _reduce_prod_jvp_rule(tangent, operand, axes)
3410 left_padding = [(n, -1, 0)] + [(0, 0, 0)] * len(non_axes)
3411 right_padding = [(-1, n, 0)] + [(0, 0, 0)] * len(non_axes)
-> 3412 left_products = _reduce_window_prod(pad(operand, one, left_padding),
3413 window_dims, window_strides,
3414 xla_client.PaddingType.VALID)
/usr/local/lib/python3.6/dist-packages/jax/lax/lax.py in pad(operand, padding_value, padding_config)
634 operator.
635 """
--> 636 return pad_p.bind(operand, padding_value, padding_config=tuple(padding_config))
637
638 def rev(operand, dimensions):
/usr/local/lib/python3.6/dist-packages/jax/core.py in bind(self, *args, **kwargs)
150 top_trace = find_top_trace(args)
151 if top_trace is None:
--> 152 return self.impl(*args, **kwargs)
153
154 tracers = map(top_trace.full_raise, args)
/usr/local/lib/python3.6/dist-packages/jax/interpreters/xla.py in apply_primitive(prim, *args, **params)
138 """Impl rule that compiles and runs a single primitive 'prim' using XLA."""
139 abstract_args = map(abstractify, args)
--> 140 compiled_fun = xla_primitive_callable(prim, *abstract_args, **params)
141 return compiled_fun(*args)
142
/usr/local/lib/python3.6/dist-packages/jax/interpreters/xla.py in xla_primitive_callable(prim, *abstract_args, **params)
150 else:
151 handle_result = aval_to_result_handler(aval_out)
--> 152 built_c = primitive_computation(prim, *abstract_args, **params)
153 compiled = built_c.Compile(compile_options=xb.get_compile_options(),
154 backend=xb.get_backend(backend))
/usr/local/lib/python3.6/dist-packages/jax/interpreters/xla.py in primitive_computation(prim, *avals, **params)
183 "This is a bug in JAX's shape-checking rules; please report it!\n"
184 "https://github.com/google/jax/issues\n")
--> 185 raise RuntimeError(msg)
186
187 def _execute_compiled_primitive(prim, compiled, backend, result_handler, *args):
RuntimeError: Invalid argument: Padding result in negative size for dimension 0:
This is a bug in JAX's shape-checking rules; please report it!
https://github.com/google/jax/issues
|
RuntimeError
|
def broadcast_shapes(*shapes):
"""Returns the shape that results from NumPy broadcasting of `shapes`."""
if len(shapes) == 1:
return shapes[0]
ndim = _max(len(shape) for shape in shapes)
shapes = onp.array([(1,) * (ndim - len(shape)) + shape for shape in shapes])
result_shape = _try_broadcast_shapes(shapes)
if result_shape is None:
raise ValueError(
"Incompatible shapes for broadcasting: {}".format(tuple(map(tuple, shapes)))
)
return result_shape
|
def broadcast_shapes(*shapes):
"""Returns the shape that results from NumPy broadcasting of `shapes`."""
if len(shapes) == 1:
return shapes[0]
ndim = _max(len(shape) for shape in shapes)
shapes = onp.array([(1,) * (ndim - len(shape)) + shape for shape in shapes])
is_zero = onp.any(shapes == 0, axis=0)
max_shape = onp.max(shapes, axis=0)
result_shape = onp.where(is_zero, 0, max_shape)
if not onp.all((shapes == result_shape) | (shapes == 1)):
raise ValueError(
"Incompatible shapes for broadcasting: {}".format(tuple(map(tuple, shapes)))
)
return canonicalize_shape(result_shape)
|
https://github.com/google/jax/issues/3216
|
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-9-b3bfdb20b090> in <module>()
3
4 jax.shapecheck(["(m,n)", "n"], "(m,n)")(jnp.add) # passes
----> 5 jax.shapecheck(["n", "(m,n)"], "(m,n)")(jnp.add) # errors
google3/third_party/py/jax/api.py in shapecheck(in_shapes, out_shape, fun)
1263 flat_fun, out_tree_ = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)
1264 avals = map(partial(ShapedArray, dtype=onp.float32), in_shapes)
-> 1265 out_shapes_ = [o.shape for o in pe.abstract_eval_fun(flat_fun.call_wrapped, *avals)]
1266 if out_tree != out_tree_(): raise TypeError("pytree mismatch")
1267 if not all(map(masking._shape_spec_consistent, out_shapes, out_shapes_)):
google3/third_party/py/jax/interpreters/partial_eval.py in abstract_eval_fun(fun, *avals, **params)
340 pvals_in = [PartialVal.unknown(a) for a in avals]
341 _, pvals_out, _ = trace_to_jaxpr(lu.wrap_init(fun, params), pvals_in,
--> 342 instantiate=True, stage_out=True)
343 avals_out, _ = unzip2(pvals_out)
344 for aval_out in avals_out:
google3/third_party/py/jax/interpreters/partial_eval.py in trace_to_jaxpr(fun, pvals, instantiate, stage_out, bottom, trace_type)
436 with new_master(trace_type, bottom=bottom) as master:
437 fun = trace_to_subjaxpr(fun, master, instantiate)
--> 438 jaxpr, (out_pvals, consts, env) = fun.call_wrapped(pvals)
439 assert not env
440 del master
google3/third_party/py/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
148 gen = None
149
--> 150 ans = self.f(*args, **dict(self.params, **kwargs))
151 del args
152 while stack:
google3/third_party/py/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
148 gen = None
149
--> 150 ans = self.f(*args, **dict(self.params, **kwargs))
151 del args
152 while stack:
google3/third_party/py/jax/numpy/lax_numpy.py in fn(x1, x2)
350 def _maybe_bool_binop(numpy_fn, lax_fn, bool_lax_fn):
351 def fn(x1, x2):
--> 352 x1, x2 = _promote_args(numpy_fn.__name__, x1, x2)
353 return lax_fn(x1, x2) if x1.dtype != bool_ else bool_lax_fn(x1, x2)
354 return _wraps(numpy_fn)(fn)
google3/third_party/py/jax/numpy/lax_numpy.py in _promote_args(fun_name, *args)
281 """Convenience function to apply Numpy argument shape and dtype promotion."""
282 _check_arraylike(fun_name, *args)
--> 283 return _promote_shapes(fun_name, *_promote_dtypes(*args))
284
285 def _promote_args_inexact(fun_name, *args):
google3/third_party/py/jax/numpy/lax_numpy.py in _promote_shapes(fun_name, *args)
218 if FLAGS.jax_numpy_rank_promotion != "allow":
219 _rank_promotion_warning_or_error(fun_name, shapes)
--> 220 result_rank = len(lax.broadcast_shapes(*shapes))
221 return [lax.reshape(arg, (1,) * (result_rank - len(shp)) + shp)
222 if shp and len(shp) != result_rank else arg
google3/third_party/py/jax/lax/lax.py in broadcast_shapes(*shapes)
75 shapes = onp.array([(1,) * (ndim - len(shape)) + shape for shape in shapes])
76 is_zero = onp.any(shapes == 0, axis=0)
---> 77 max_shape = onp.max(shapes, axis=0)
78 result_shape = onp.where(is_zero, 0, max_shape)
79 if not onp.all((shapes == result_shape) | (shapes == 1)):
google3/third_party/py/numpy/core/fromnumeric.py in amax(a, axis, out, keepdims, initial)
2503 """
2504 return _wrapreduction(a, np.maximum, 'max', axis, None, out, keepdims=keepdims,
-> 2505 initial=initial)
2506
2507
google3/third_party/py/numpy/core/fromnumeric.py in _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs)
84 return reduction(axis=axis, out=out, **passkwargs)
85
---> 86 return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
87
88
google3/third_party/py/jax/interpreters/masking.py in __le__(self, other)
184
185 def __le__(self, other):
--> 186 return _ensure_poly(other) >= self
187
188 def __lt__(self, other):
google3/third_party/py/jax/interpreters/masking.py in __ge__(self, other)
181
182 raise ValueError('Polynomials comparison "{} >= {}" is inconclusive.'
--> 183 .format(self, other))
184
185 def __le__(self, other):
ValueError: Polynomials comparison "1 >= m" is inconclusive.
|
ValueError
|
def _broadcasting_shape_rule(name, *avals):
shapes = onp.array([aval.shape for aval in avals if aval.shape])
if not shapes.size:
return ()
if len({len(shape) for shape in shapes}) != 1:
msg = "{} got arrays of different rank: {}."
raise TypeError(msg.format(name, ", ".join(map(str, map(tuple, shapes)))))
result_shape = _try_broadcast_shapes(shapes)
if result_shape is None:
msg = "{} got incompatible shapes for broadcasting: {}."
raise TypeError(msg.format(name, ", ".join(map(str, map(tuple, shapes)))))
return result_shape
|
def _broadcasting_shape_rule(name, *avals):
shapes = onp.array([aval.shape for aval in avals if aval.shape])
if not shapes.size:
return ()
if len({len(shape) for shape in shapes}) != 1:
msg = "{} got arrays of different rank: {}."
raise TypeError(msg.format(name, ", ".join(map(str, map(tuple, shapes)))))
is_zero = onp.any(shapes == 0, axis=0)
max_shape = onp.max(shapes, axis=0)
result_shape = onp.where(is_zero, 0, max_shape)
if not onp.all((shapes == result_shape) | (shapes == 1)):
msg = "{} got incompatible shapes for broadcasting: {}."
raise TypeError(msg.format(name, ", ".join(map(str, map(tuple, shapes)))))
return tuple(result_shape)
|
https://github.com/google/jax/issues/3216
|
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-9-b3bfdb20b090> in <module>()
3
4 jax.shapecheck(["(m,n)", "n"], "(m,n)")(jnp.add) # passes
----> 5 jax.shapecheck(["n", "(m,n)"], "(m,n)")(jnp.add) # errors
google3/third_party/py/jax/api.py in shapecheck(in_shapes, out_shape, fun)
1263 flat_fun, out_tree_ = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)
1264 avals = map(partial(ShapedArray, dtype=onp.float32), in_shapes)
-> 1265 out_shapes_ = [o.shape for o in pe.abstract_eval_fun(flat_fun.call_wrapped, *avals)]
1266 if out_tree != out_tree_(): raise TypeError("pytree mismatch")
1267 if not all(map(masking._shape_spec_consistent, out_shapes, out_shapes_)):
google3/third_party/py/jax/interpreters/partial_eval.py in abstract_eval_fun(fun, *avals, **params)
340 pvals_in = [PartialVal.unknown(a) for a in avals]
341 _, pvals_out, _ = trace_to_jaxpr(lu.wrap_init(fun, params), pvals_in,
--> 342 instantiate=True, stage_out=True)
343 avals_out, _ = unzip2(pvals_out)
344 for aval_out in avals_out:
google3/third_party/py/jax/interpreters/partial_eval.py in trace_to_jaxpr(fun, pvals, instantiate, stage_out, bottom, trace_type)
436 with new_master(trace_type, bottom=bottom) as master:
437 fun = trace_to_subjaxpr(fun, master, instantiate)
--> 438 jaxpr, (out_pvals, consts, env) = fun.call_wrapped(pvals)
439 assert not env
440 del master
google3/third_party/py/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
148 gen = None
149
--> 150 ans = self.f(*args, **dict(self.params, **kwargs))
151 del args
152 while stack:
google3/third_party/py/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
148 gen = None
149
--> 150 ans = self.f(*args, **dict(self.params, **kwargs))
151 del args
152 while stack:
google3/third_party/py/jax/numpy/lax_numpy.py in fn(x1, x2)
350 def _maybe_bool_binop(numpy_fn, lax_fn, bool_lax_fn):
351 def fn(x1, x2):
--> 352 x1, x2 = _promote_args(numpy_fn.__name__, x1, x2)
353 return lax_fn(x1, x2) if x1.dtype != bool_ else bool_lax_fn(x1, x2)
354 return _wraps(numpy_fn)(fn)
google3/third_party/py/jax/numpy/lax_numpy.py in _promote_args(fun_name, *args)
281 """Convenience function to apply Numpy argument shape and dtype promotion."""
282 _check_arraylike(fun_name, *args)
--> 283 return _promote_shapes(fun_name, *_promote_dtypes(*args))
284
285 def _promote_args_inexact(fun_name, *args):
google3/third_party/py/jax/numpy/lax_numpy.py in _promote_shapes(fun_name, *args)
218 if FLAGS.jax_numpy_rank_promotion != "allow":
219 _rank_promotion_warning_or_error(fun_name, shapes)
--> 220 result_rank = len(lax.broadcast_shapes(*shapes))
221 return [lax.reshape(arg, (1,) * (result_rank - len(shp)) + shp)
222 if shp and len(shp) != result_rank else arg
google3/third_party/py/jax/lax/lax.py in broadcast_shapes(*shapes)
75 shapes = onp.array([(1,) * (ndim - len(shape)) + shape for shape in shapes])
76 is_zero = onp.any(shapes == 0, axis=0)
---> 77 max_shape = onp.max(shapes, axis=0)
78 result_shape = onp.where(is_zero, 0, max_shape)
79 if not onp.all((shapes == result_shape) | (shapes == 1)):
google3/third_party/py/numpy/core/fromnumeric.py in amax(a, axis, out, keepdims, initial)
2503 """
2504 return _wrapreduction(a, np.maximum, 'max', axis, None, out, keepdims=keepdims,
-> 2505 initial=initial)
2506
2507
google3/third_party/py/numpy/core/fromnumeric.py in _wrapreduction(obj, ufunc, method, axis, dtype, out, **kwargs)
84 return reduction(axis=axis, out=out, **passkwargs)
85
---> 86 return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
87
88
google3/third_party/py/jax/interpreters/masking.py in __le__(self, other)
184
185 def __le__(self, other):
--> 186 return _ensure_poly(other) >= self
187
188 def __lt__(self, other):
google3/third_party/py/jax/interpreters/masking.py in __ge__(self, other)
181
182 raise ValueError('Polynomials comparison "{} >= {}" is inconclusive.'
--> 183 .format(self, other))
184
185 def __le__(self, other):
ValueError: Polynomials comparison "1 >= m" is inconclusive.
|
ValueError
|
def _while_loop_translation_rule(
c,
axis_env,
name_stack,
avals,
backend,
*args,
cond_jaxpr,
body_jaxpr,
cond_nconsts,
body_nconsts,
):
cond_consts, body_consts, init_vals = split_list(args, [cond_nconsts, body_nconsts])
batched = bool(cond_jaxpr.out_avals[0].shape)
# Since jaxprs don't have tuples and have multiple return values, but we need
# the HLO While loop to take a single tuple input and output a single boolean
# (for the cond computation) or a single tuple output (for the body
# computation), we build XLA computations that handle the tuple munging before
# generating a Call into the computations formed from the jaxprs.
init_carry = xops.Tuple(c, cond_consts + body_consts + init_vals)
cond_c = xb.make_computation_builder("cond_computation")
cond_carry = xb.parameter(cond_c, 0, c.get_shape(init_carry))
cond_carry_elts = [xops.GetTupleElement(cond_carry, i) for i in range(len(args))]
x, _, z = split_list(cond_carry_elts, [cond_nconsts, body_nconsts])
(pred,) = xla.jaxpr_subcomp(
cond_c,
cond_jaxpr.jaxpr,
backend,
axis_env,
_map(partial(xb.constant, cond_c), cond_jaxpr.literals),
extend_name_stack(name_stack, "cond"),
*(x + z),
)
if batched:
scalar = ShapedArray((), onp.bool_)
or_ = xla.primitive_subcomputation(lax.or_p, scalar, scalar)
pred = xops.Reduce(
cond_c,
[pred],
[xb.constant(cond_c, onp.array(False))],
or_,
list(range(cond_jaxpr.out_avals[0].ndim)),
)
body_c = xb.make_computation_builder("body_computation")
body_carry = xb.parameter(body_c, 0, c.get_shape(init_carry))
body_carry_elts = [xops.GetTupleElement(body_carry, i) for i in range(len(args))]
x, y, z = split_list(body_carry_elts, [cond_nconsts, body_nconsts])
new_z = xla.jaxpr_subcomp(
body_c,
body_jaxpr.jaxpr,
backend,
axis_env,
_map(partial(xb.constant, body_c), body_jaxpr.literals),
extend_name_stack(name_stack, "body"),
*(y + z),
)
if batched:
(body_pred,) = xla.jaxpr_subcomp(
body_c,
cond_jaxpr.jaxpr,
backend,
axis_env,
_map(partial(xb.constant, body_c), cond_jaxpr.literals),
extend_name_stack(name_stack, "body_pred"),
*(x + z),
)
new_z = _map(
partial(_pred_bcast_select, body_c, body_pred),
new_z,
z,
body_jaxpr.out_avals,
)
assert _map(body_c.get_shape, new_z) == _map(
body_c.get_shape, z
) # no broadcast
new_carry = xops.Tuple(body_c, list(itertools.chain(x, y, new_z)))
ans = xops.While(cond_c.build(pred), body_c.build(new_carry), init_carry)
ans_elts = [xops.GetTupleElement(ans, i) for i in range(len(args))]
_, _, z = split_list(ans_elts, [cond_nconsts, body_nconsts])
return xops.Tuple(c, z)
|
def _while_loop_translation_rule(
c,
axis_env,
name_stack,
avals,
backend,
*args,
cond_jaxpr,
body_jaxpr,
cond_nconsts,
body_nconsts,
):
cond_consts, body_consts, init_vals = split_list(args, [cond_nconsts, body_nconsts])
batched = bool(cond_jaxpr.out_avals[0].shape)
# Since jaxprs don't have tuples and have multiple return values, but we need
# the HLO While loop to take a single tuple input and output a single boolean
# (for the cond computation) or a single tuple output (for the body
# computation), we build XLA computations that handle the tuple munging before
# generating a Call into the computations formed from the jaxprs.
init_carry = xops.Tuple(c, cond_consts + body_consts + init_vals)
cond_c = xb.make_computation_builder("cond_computation")
cond_carry = xb.parameter(cond_c, 0, c.get_shape(init_carry))
cond_carry_elts = [xops.GetTupleElement(cond_carry, i) for i in range(len(args))]
x, _, z = split_list(cond_carry_elts, [cond_nconsts, body_nconsts])
(pred,) = xla.jaxpr_subcomp(
cond_c,
cond_jaxpr.jaxpr,
backend,
axis_env,
_map(partial(xb.constant, cond_c), cond_jaxpr.literals),
extend_name_stack(name_stack, "cond"),
*(x + z),
)
if batched:
scalar = ShapedArray((), onp.bool_)
or_ = xla.primitive_subcomputation(lax.or_p, scalar, scalar)
pred = xops.Reduce(
cond_c,
[pred],
[xb.constant(cond_c, onp.array(False))],
or_,
list(range(cond_jaxpr.out_avals[0].ndim)),
)
body_c = xb.make_computation_builder("body_computation")
body_carry = xb.parameter(body_c, 0, c.get_shape(init_carry))
body_carry_elts = [xops.GetTupleElement(body_carry, i) for i in range(len(args))]
x, y, z = split_list(body_carry_elts, [cond_nconsts, body_nconsts])
new_z = xla.jaxpr_subcomp(
body_c,
body_jaxpr.jaxpr,
backend,
axis_env,
_map(partial(xb.constant, body_c), body_jaxpr.literals),
extend_name_stack(name_stack, "body"),
*(y + z),
)
if batched:
(body_pred,) = xla.jaxpr_subcomp(
body_c,
cond_jaxpr.jaxpr,
backend,
axis_env,
_map(partial(xb.constant, body_c), cond_jaxpr.literals),
extend_name_stack(name_stack, "body_pred"),
*(x + z),
)
new_z = _map(partial(_pred_bcast_select, body_c, body_pred), new_z, z)
assert _map(body_c.get_shape, new_z) == _map(
body_c.get_shape, z
) # no broadcast
new_carry = xops.Tuple(body_c, list(itertools.chain(x, y, new_z)))
ans = xops.While(cond_c.build(pred), body_c.build(new_carry), init_carry)
ans_elts = [xops.GetTupleElement(ans, i) for i in range(len(args))]
_, _, z = split_list(ans_elts, [cond_nconsts, body_nconsts])
return xops.Tuple(c, z)
|
https://github.com/google/jax/issues/3204
|
Traceback (most recent call last):
File "test.py", line 21, in <module>
print(vmap_test(arr, arr))
File "/home/adabbott/Git/jax/jax/jax/api.py", line 858, in batched_fun
lambda: flatten_axes(out_tree(), out_axes))
File "/home/adabbott/Git/jax/jax/jax/interpreters/batching.py", line 34, in batch
return batched_fun.call_wrapped(*in_vals)
File "/home/adabbott/Git/jax/jax/jax/linear_util.py", line 150, in call_wrapped
ans = self.f(*args, **dict(self.params, **kwargs))
File "test.py", line 12, in test
for _ in s.while_range(lambda: s.j < b + 1):
File "/home/adabbott/Git/jax/jax/jax/experimental/loops.py", line 341, in __next__
self.end_tracing_body()
File "/home/adabbott/Git/jax/jax/jax/experimental/loops.py", line 407, in end_tracing_body
carried_init_vals, body_typed_jaxpr, body_const_vals)
File "/home/adabbott/Git/jax/jax/jax/experimental/loops.py", line 576, in build_output_vals
body_jaxpr=body_typed_jaxpr)
File "/home/adabbott/Git/jax/jax/jax/core.py", line 212, in bind
out_tracer = top_trace.process_primitive(self, tracers, kwargs)
File "/home/adabbott/Git/jax/jax/jax/interpreters/partial_eval.py", line 141, in process_primitive
return custom_partial_eval_rules[primitive](self, *tracers, **params)
File "/home/adabbott/Git/jax/jax/jax/lax/lax_control_flow.py", line 517, in _while_partial_eval
body_jaxpr=body_jaxpr_known)
File "/home/adabbott/Git/jax/jax/jax/core.py", line 212, in bind
out_tracer = top_trace.process_primitive(self, tracers, kwargs)
File "/home/adabbott/Git/jax/jax/jax/interpreters/batching.py", line 134, in process_primitive
val_out, dim_out = batched_primitive(vals_in, dims_in, **params)
File "/home/adabbott/Git/jax/jax/jax/lax/lax_control_flow.py", line 391, in _while_loop_batching_rule
body_nconsts=body_nconsts, body_jaxpr=body_jaxpr_batched)
File "/home/adabbott/Git/jax/jax/jax/core.py", line 209, in bind
return self.impl(*args, **kwargs)
File "/home/adabbott/Git/jax/jax/jax/interpreters/xla.py", line 217, in apply_primitive
compiled_fun = xla_primitive_callable(prim, *map(arg_spec, args), **params)
File "/home/adabbott/Git/jax/jax/jax/interpreters/xla.py", line 248, in xla_primitive_callable
*avals, **params)
File "/home/adabbott/Git/jax/jax/jax/interpreters/xla.py", line 295, in primitive_computation
*xla_args, **params)
File "/home/adabbott/Git/jax/jax/jax/lax/lax_control_flow.py", line 332, in _while_loop_translation_rule
new_z = _map(partial(_pred_bcast_select, body_c, body_pred), new_z, z)
File "/home/adabbott/Git/jax/jax/jax/util.py", line 34, in safe_map
return list(map(f, *args))
File "/home/adabbott/Git/jax/jax/jax/lax/lax_control_flow.py", line 350, in _pred_bcast_select
assert pred_shape == x_shape[:len(pred_shape)] == y_shape[:len(pred_shape)]
AssertionError
|
AssertionError
|
def _pred_bcast_select(c, pred, x, y, x_y_aval: core.AbstractValue):
pred_shape = c.get_shape(pred).dimensions()
x_shape = c.get_shape(x).dimensions()
y_shape = c.get_shape(y).dimensions()
assert x_shape == y_shape
if x_y_aval is core.abstract_unit:
return x
elif x_y_aval is core.abstract_token:
return xops.AfterAll(c, [x, y])
else:
assert pred_shape == x_shape[: len(pred_shape)] == y_shape[: len(pred_shape)]
bcast_pred = xops.BroadcastInDim(pred, x_shape, list(range(len(pred_shape))))
return xops.Select(bcast_pred, x, y)
|
def _pred_bcast_select(c, pred, x, y):
pred_shape = c.get_shape(pred).dimensions()
x_shape = c.get_shape(x).dimensions()
y_shape = c.get_shape(y).dimensions()
assert x_shape == y_shape
if not c.get_shape(x).is_array() and not c.get_shape(y).is_array():
# Two tokens
return xops.AfterAll(c, [x, y])
else:
assert pred_shape == x_shape[: len(pred_shape)] == y_shape[: len(pred_shape)]
bcast_pred = xops.BroadcastInDim(pred, x_shape, list(range(len(pred_shape))))
return xops.Select(bcast_pred, x, y)
|
https://github.com/google/jax/issues/3204
|
Traceback (most recent call last):
File "test.py", line 21, in <module>
print(vmap_test(arr, arr))
File "/home/adabbott/Git/jax/jax/jax/api.py", line 858, in batched_fun
lambda: flatten_axes(out_tree(), out_axes))
File "/home/adabbott/Git/jax/jax/jax/interpreters/batching.py", line 34, in batch
return batched_fun.call_wrapped(*in_vals)
File "/home/adabbott/Git/jax/jax/jax/linear_util.py", line 150, in call_wrapped
ans = self.f(*args, **dict(self.params, **kwargs))
File "test.py", line 12, in test
for _ in s.while_range(lambda: s.j < b + 1):
File "/home/adabbott/Git/jax/jax/jax/experimental/loops.py", line 341, in __next__
self.end_tracing_body()
File "/home/adabbott/Git/jax/jax/jax/experimental/loops.py", line 407, in end_tracing_body
carried_init_vals, body_typed_jaxpr, body_const_vals)
File "/home/adabbott/Git/jax/jax/jax/experimental/loops.py", line 576, in build_output_vals
body_jaxpr=body_typed_jaxpr)
File "/home/adabbott/Git/jax/jax/jax/core.py", line 212, in bind
out_tracer = top_trace.process_primitive(self, tracers, kwargs)
File "/home/adabbott/Git/jax/jax/jax/interpreters/partial_eval.py", line 141, in process_primitive
return custom_partial_eval_rules[primitive](self, *tracers, **params)
File "/home/adabbott/Git/jax/jax/jax/lax/lax_control_flow.py", line 517, in _while_partial_eval
body_jaxpr=body_jaxpr_known)
File "/home/adabbott/Git/jax/jax/jax/core.py", line 212, in bind
out_tracer = top_trace.process_primitive(self, tracers, kwargs)
File "/home/adabbott/Git/jax/jax/jax/interpreters/batching.py", line 134, in process_primitive
val_out, dim_out = batched_primitive(vals_in, dims_in, **params)
File "/home/adabbott/Git/jax/jax/jax/lax/lax_control_flow.py", line 391, in _while_loop_batching_rule
body_nconsts=body_nconsts, body_jaxpr=body_jaxpr_batched)
File "/home/adabbott/Git/jax/jax/jax/core.py", line 209, in bind
return self.impl(*args, **kwargs)
File "/home/adabbott/Git/jax/jax/jax/interpreters/xla.py", line 217, in apply_primitive
compiled_fun = xla_primitive_callable(prim, *map(arg_spec, args), **params)
File "/home/adabbott/Git/jax/jax/jax/interpreters/xla.py", line 248, in xla_primitive_callable
*avals, **params)
File "/home/adabbott/Git/jax/jax/jax/interpreters/xla.py", line 295, in primitive_computation
*xla_args, **params)
File "/home/adabbott/Git/jax/jax/jax/lax/lax_control_flow.py", line 332, in _while_loop_translation_rule
new_z = _map(partial(_pred_bcast_select, body_c, body_pred), new_z, z)
File "/home/adabbott/Git/jax/jax/jax/util.py", line 34, in safe_map
return list(map(f, *args))
File "/home/adabbott/Git/jax/jax/jax/lax/lax_control_flow.py", line 350, in _pred_bcast_select
assert pred_shape == x_shape[:len(pred_shape)] == y_shape[:len(pred_shape)]
AssertionError
|
AssertionError
|
def psum(x, axis_name, *, axis_index_groups=None):
"""Compute an all-reduce sum on ``x`` over the pmapped axis ``axis_name``.
If ``x`` is a pytree then the result is equivalent to mapping this function to
each leaf in the tree.
Inputs of boolean dtype are converted to integers before the reduction.
Args:
x: array(s) with a mapped axis named ``axis_name``.
axis_name: hashable Python object used to name a pmapped axis (see the
``pmap`` docstring for more details).
axis_index_groups: optional list of lists containing axis indices (e.g. for
an axis of size 4, [[0, 1], [2, 3]] would perform psums over the first
two and last two replicas). Groups must cover all axis indices exactly
once, and all groups must be the same size.
Returns:
Array(s) with the same shape as ``x`` representing the result of an
all-reduce sum along the axis ``axis_name``.
For example, with 4 XLA devices available:
>>> x = np.arange(4)
>>> y = jax.pmap(lambda x: jax.lax.psum(x, 'i'), axis_name='i')(x)
>>> print(y)
[6 6 6 6]
>>> y = jax.pmap(lambda x: x / jax.lax.psum(x, 'i'), axis_name='i')(x)
>>> print(y)
[ 0. 0.16666667 0.33333334 0.5 ]
"""
_validate_axis_index_groups(axis_index_groups)
leaves, treedef = tree_util.tree_flatten(x)
leaves = [
lax.convert_element_type(l, onp.int32) if dtypes.dtype(l) == onp.bool_ else l
for l in leaves
]
out_flat = psum_p.bind(
*leaves, axis_name=axis_name, axis_index_groups=axis_index_groups
)
return tree_util.tree_unflatten(treedef, out_flat)
|
def psum(x, axis_name, *, axis_index_groups=None):
"""Compute an all-reduce sum on ``x`` over the pmapped axis ``axis_name``.
If ``x`` is a pytree then the result is equivalent to mapping this function to
each leaf in the tree.
Args:
x: array(s) with a mapped axis named ``axis_name``.
axis_name: hashable Python object used to name a pmapped axis (see the
``pmap`` docstring for more details).
axis_index_groups: optional list of lists containing axis indices (e.g. for
an axis of size 4, [[0, 1], [2, 3]] would perform psums over the first
two and last two replicas). Groups must cover all axis indices exactly
once, and all groups must be the same size.
Returns:
Array(s) with the same shape as ``x`` representing the result of an
all-reduce sum along the axis ``axis_name``.
For example, with 4 XLA devices available:
>>> x = np.arange(4)
>>> y = jax.pmap(lambda x: jax.lax.psum(x, 'i'), axis_name='i')(x)
>>> print(y)
[6 6 6 6]
>>> y = jax.pmap(lambda x: x / jax.lax.psum(x, 'i'), axis_name='i')(x)
>>> print(y)
[ 0. 0.16666667 0.33333334 0.5 ]
"""
leaves, treedef = tree_util.tree_flatten(x)
_validate_axis_index_groups(axis_index_groups)
return treedef.unflatten(
psum_p.bind(*leaves, axis_name=axis_name, axis_index_groups=axis_index_groups)
)
|
https://github.com/google/jax/issues/3123
|
Traceback (most recent call last):
File "[REDACTED]/py/jax/interpreters/xla.py", line 301, in primitive_computation
return c.build()
RuntimeError: Invalid argument: Expected element type in shape to be arithmetic type for operation add; got PRED.: @ 0x55b73da20345 xla::XlaBuilder::BinaryOp()
@ 0x55b73da19dc9 xla::Add()
@ 0x7fc98c23d5f4 pybind11::cpp_function::initialize<>()::{lambda()#1}::__invoke()
@ 0x7fc98c1e9963 pybind11::cpp_function::dispatcher()
@ 0x55b745431fe7 PyCFunction_Call
@ 0x55b7454b3adf _PyEval_EvalFrameDefault
@ 0x55b7454b7160 _PyEval_EvalCodeWithName
@ 0x55b7454ad938 PyEval_EvalCodeEx
@ 0x55b7454171a6 function_call
@ 0x55b7453e64ba PyObject_Call
@ 0x55b7450f983e partial_call
@ 0x55b7453e64ba PyObject_Call
@ 0x55b7454b3a04 _PyEval_EvalFrameDefault
@ 0x55b7454b7160 _PyEval_EvalCodeWithName
@ 0x55b7454ad938 PyEval_EvalCodeEx
@ 0x55b7454171a6 function_call
@ 0x55b7453e64ba PyObject_Call
@ 0x55b7450fa680 bounded_lru_cache_wrapper
@ 0x55b7453e64ba PyObject_Call
@ 0x55b7454b3a04 _PyEval_EvalFrameDefault
@ 0x55b7454b7160 _PyEval_EvalCodeWithName
@ 0x55b7454b7a24 fast_function
@ 0x55b7454b66bc call_function
@ 0x55b7454b375f _PyEval_EvalFrameDefault
@ 0x55b7454b7160 _PyEval_EvalCodeWithName
@ 0x55b7454ad938 PyEval_EvalCodeEx
@ 0x55b7454171a6 function_call
@ 0x55b7453e64ba PyObject_Call
@ 0x55b7450f983e partial_call
@ 0x55b7453e678f _PyObject_FastCallDict
@ 0x55b7454b669d call_function
@ 0x55b7454b375f _PyEval_EvalFrameDefault
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "[REDACTED]/py/absl/app.py", line 464, in run
_run_main(main, args)
File "[REDACTED]/py/absl/app.py", line 393, in _run_main
sys.exit(main(argv))
File "[REDACTED]/imagenet/train.py", line 255, in main
batch["image"], batch["label"])
File "[REDACTED]/py/jax/api.py", line 1051, in f_pmapped
mapped_invars=tuple(axis is not None for axis in in_axes_flat))
File "[REDACTED]/py/jax/core.py", line 1021, in _call_bind
outs = primitive.impl(f, *args, **params)
File "[REDACTED]/py/jax/interpreters/pxla.py", line 604, in xla_pmap_impl
*abstract_args)
File "[REDACTED]/py/jax/linear_util.py", line 221, in memoized_fun
ans = call(fun, *args)
File "[REDACTED]/py/jax/interpreters/pxla.py", line 702, in parallel_callable
extend_name_stack(wrap_name(name, 'pmap')), *xla_args)
File "[REDACTED]/py/jax/interpreters/xla.py", line 406, in jaxpr_subcomp
**new_params)
File "[REDACTED]/py/jax/lax/lax_parallel.py", line 311, in _psum_translation_rule
return _notuple_psum_translation_rule(c, *args, replica_groups=replica_groups)
File "[REDACTED]/py/jax/lax/lax_parallel.py", line 357, in _notuple_psum_translation_rule
return xops.Tuple(c, list(map(_translate, args)))
File "[REDACTED]/py/jax/lax/lax_parallel.py", line 356, in _translate
return psum(val)
File "[REDACTED]/py/jax/lax/lax_parallel.py", line 304, in _allreduce_translation_rule
computation = xla.primitive_subcomputation(prim, scalar, scalar)
File "[REDACTED]/py/jax/interpreters/xla.py", line 309, in primitive_subcomputation
return primitive_computation(prim, AxisEnv(1), None, False, *avals, **params)
File "[REDACTED]/py/jax/interpreters/xla.py", line 306, in primitive_computation
raise RuntimeError(msg) from e
RuntimeError: Invalid argument: Expected element type in shape to be arithmetic type for operation add; got PRED.: @ 0x55b73da20345 xla::XlaBuilder::BinaryOp()
@ 0x55b73da19dc9 xla::Add()
@ 0x7fc98c23d5f4 pybind11::cpp_function::initialize<>()::{lambda()#1}::__invoke()
@ 0x7fc98c1e9963 pybind11::cpp_function::dispatcher()
@ 0x55b745431fe7 PyCFunction_Call
@ 0x55b7454b3adf _PyEval_EvalFrameDefault
@ 0x55b7454b7160 _PyEval_EvalCodeWithName
@ 0x55b7454ad938 PyEval_EvalCodeEx
@ 0x55b7454171a6 function_call
@ 0x55b7453e64ba PyObject_Call
@ 0x55b7450f983e partial_call
@ 0x55b7453e64ba PyObject_Call
@ 0x55b7454b3a04 _PyEval_EvalFrameDefault
@ 0x55b7454b7160 _PyEval_EvalCodeWithName
@ 0x55b7454ad938 PyEval_EvalCodeEx
@ 0x55b7454171a6 function_call
@ 0x55b7453e64ba PyObject_Call
@ 0x55b7450fa680 bounded_lru_cache_wrapper
@ 0x55b7453e64ba PyObject_Call
@ 0x55b7454b3a04 _PyEval_EvalFrameDefault
@ 0x55b7454b7160 _PyEval_EvalCodeWithName
@ 0x55b7454b7a24 fast_function
@ 0x55b7454b66bc call_function
@ 0x55b7454b375f _PyEval_EvalFrameDefault
@ 0x55b7454b7160 _PyEval_EvalCodeWithName
@ 0x55b7454ad938 PyEval_EvalCodeEx
@ 0x55b7454171a6 function_call
@ 0x55b7453e64ba PyObject_Call
@ 0x55b7450f983e partial_call
@ 0x55b7453e678f _PyObject_FastCallDict
@ 0x55b7454b669d call_function
@ 0x55b7454b375f _PyEval_EvalFrameDefault
This is a bug in JAX's shape-checking rules; please report it!
https://github.com/google/jax/issues
|
RuntimeError
|
def _sort_translation_rule(c, *operands, dimension):
types = [c.get_shape(x).xla_element_type() for x in operands]
subc = xla_bridge.make_computation_builder("sort_lt_comparator")
params = [
xb.parameter(subc, 2 * i + j, xc.Shape.array_shape(typ, ()))
for i, typ in enumerate(types)
for j in range(2)
]
result = xla.lower_fun(_sort_lt_comparator, multiple_results=False)(subc, *params)
comparator = subc.build(result)
out = xops.Sort(
c, operands, dimension=dimension, is_stable=True, comparator=comparator
)
return out if len(operands) != 1 else xops.Tuple(c, [out])
|
def _sort_translation_rule(c, *operands, dimension):
out = xops.Sort(c, operands, dimension=dimension, is_stable=True)
return out if len(operands) != 1 else xops.Tuple(c, [out])
|
https://github.com/google/jax/issues/3074
|
❯ pipenv run python -m research.lqr
/Users/skainswo/dev/jax/jax/lib/xla_bridge.py:116: UserWarning: No GPU/TPU found, falling back to CPU.
warnings.warn('No GPU/TPU found, falling back to CPU.')
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/Users/skainswo/dev/research/research/lqr.py", line 50, in <module>
_test_lqr1(2)
File "/Users/skainswo/dev/research/research/lqr.py", line 45, in _test_lqr1
actual = lqr_continuous_time_infinite_horizon(A, B, Q, R, N)
File "/Users/skainswo/dev/research/research/lqr.py", line 26, in lqr_continuous_time_infinite_horizon
argsort = jp.argsort(eigvals)
File "/Users/skainswo/dev/jax/jax/numpy/lax_numpy.py", line 2886, in argsort
_, perm = lax.sort_key_val(a, iota, dimension=axis)
File "/Users/skainswo/dev/jax/jax/lax/lax.py", line 1190, in sort_key_val
result = sort_key_val_p.bind(keys, values, dimension=dimension)
File "/Users/skainswo/dev/jax/jax/core.py", line 211, in bind
return self.impl(*args, **kwargs)
File "/Users/skainswo/dev/jax/jax/interpreters/xla.py", line 217, in apply_primitive
compiled_fun = xla_primitive_callable(prim, *map(arg_spec, args), **params)
File "/Users/skainswo/dev/jax/jax/interpreters/xla.py", line 254, in xla_primitive_callable
compiled = backend.compile(built_c, compile_options=options)
RuntimeError: Unimplemented: complex comparison 'LT'
|
RuntimeError
|
def _quantile(a, q, axis, interpolation, keepdims):
a = asarray(a, dtype=promote_types(_dtype(a), float_))
q = asarray(q, dtype=promote_types(_dtype(q), float_))
if axis is None:
a = ravel(a)
axis = 0
elif isinstance(axis, tuple):
raise NotImplementedError("Tuple values for axis are not implemented")
else:
axis = _canonicalize_axis(axis, ndim(a))
q_ndim = ndim(q)
if q_ndim > 1:
raise ValueError("q must be have rank <= 1, got shape {}".format(shape(q)))
a_shape = shape(a)
a = lax.sort(a, dimension=axis)
n = a_shape[axis]
q = lax.mul(q, _constant_like(q, n - 1))
low = lax.floor(q)
high = lax.ceil(q)
high_weight = lax.sub(q, low)
low_weight = lax.sub(_constant_like(high_weight, 1), high_weight)
low = lax.clamp(_constant_like(low, 0), low, _constant_like(low, n - 1))
high = lax.clamp(_constant_like(high, 0), high, _constant_like(high, n - 1))
low = lax.convert_element_type(low, int64)
high = lax.convert_element_type(high, int64)
slice_sizes = list(a_shape)
slice_sizes[axis] = 1
dnums = lax.GatherDimensionNumbers(
offset_dims=tuple(
range(
q_ndim, len(a_shape) + q_ndim if keepdims else len(a_shape) + q_ndim - 1
)
),
collapsed_slice_dims=() if keepdims else (axis,),
start_index_map=(axis,),
)
low = low[..., None]
high = high[..., None]
low_value = lax.gather(a, low, dimension_numbers=dnums, slice_sizes=slice_sizes)
high_value = lax.gather(a, high, dimension_numbers=dnums, slice_sizes=slice_sizes)
if q_ndim == 1:
low_weight = lax.broadcast_in_dim(
low_weight, low_value.shape, broadcast_dimensions=(0,)
)
high_weight = lax.broadcast_in_dim(
high_weight, high_value.shape, broadcast_dimensions=(0,)
)
if interpolation == "linear":
result = lax.add(
lax.mul(low_value.astype(q.dtype), low_weight),
lax.mul(high_value.astype(q.dtype), high_weight),
)
elif interpolation == "lower":
result = low_value
elif interpolation == "higher":
result = high_value
elif interpolation == "nearest":
pred = lax.le(high_weight, _constant_like(high_weight, 0.5))
result = lax.select(pred, low_value, high_value)
elif interpolation == "midpoint":
result = lax.mul(lax.add(low_value, high_value), _constant_like(low_value, 0.5))
else:
raise ValueError(f"interpolation={interpolation!r} not recognized")
return lax.convert_element_type(result, a.dtype)
|
def _quantile(a, q, axis, interpolation, keepdims):
a = asarray(a)
if axis is None:
a = ravel(a)
axis = 0
elif isinstance(axis, tuple):
raise NotImplementedError("Tuple values for axis are not implemented")
else:
axis = _canonicalize_axis(axis, ndim(a))
q_ndim = ndim(q)
if q_ndim > 1:
raise ValueError("q must be have rank <= 1, got shape {}".format(shape(q)))
q = asarray(q)
if not issubdtype(a.dtype, floating) or not issubdtype(q.dtype, floating):
msg = "q and a arguments to quantile must be of float type, got {} and {}"
raise TypeError(msg.format(a.dtype, q.dtype))
# Promote q to at least float32 for precise interpolation.
q = lax.convert_element_type(q, promote_types(q.dtype, float32))
a_shape = shape(a)
a = lax.sort(a, dimension=axis)
n = a_shape[axis]
q = lax.mul(q, _constant_like(q, n - 1))
low = lax.floor(q)
high = lax.ceil(q)
high_weight = lax.sub(q, low)
low_weight = lax.sub(_constant_like(high_weight, 1), high_weight)
low = lax.clamp(_constant_like(low, 0), low, _constant_like(low, n - 1))
high = lax.clamp(_constant_like(high, 0), high, _constant_like(high, n - 1))
low = lax.convert_element_type(low, int64)
high = lax.convert_element_type(high, int64)
slice_sizes = list(a_shape)
slice_sizes[axis] = 1
dnums = lax.GatherDimensionNumbers(
offset_dims=tuple(
range(
q_ndim, len(a_shape) + q_ndim if keepdims else len(a_shape) + q_ndim - 1
)
),
collapsed_slice_dims=() if keepdims else (axis,),
start_index_map=(axis,),
)
low = low[..., None]
high = high[..., None]
low_value = lax.gather(a, low, dimension_numbers=dnums, slice_sizes=slice_sizes)
high_value = lax.gather(a, high, dimension_numbers=dnums, slice_sizes=slice_sizes)
if q_ndim == 1:
low_weight = lax.broadcast_in_dim(
low_weight, low_value.shape, broadcast_dimensions=(0,)
)
high_weight = lax.broadcast_in_dim(
high_weight, high_value.shape, broadcast_dimensions=(0,)
)
if interpolation == "linear":
result = lax.add(
lax.mul(low_value.astype(q.dtype), low_weight),
lax.mul(high_value.astype(q.dtype), high_weight),
)
elif interpolation == "lower":
result = low_value
elif interpolation == "higher":
result = high_value
elif interpolation == "nearest":
pred = lax.le(high_weight, _constant_like(high_weight, 0.5))
result = lax.select(pred, low_value, high_value)
elif interpolation == "midpoint":
result = lax.mul(lax.add(low_value, high_value), _constant_like(low_value, 0.5))
else:
raise ValueError(f"interpolation={interpolation!r} not recognized")
return lax.convert_element_type(result, a.dtype)
|
https://github.com/google/jax/issues/3070
|
TypeError Traceback (most recent call last)
<ipython-input-28-eb17bd577cca> in <module>
----> 1 np.median(np.array([i for i in range(0,10)]))
/opt/anaconda3/lib/python3.7/site-packages/jax/numpy/lax_numpy.py in median(a, axis, out, overwrite_input, keepdims)
3556 q = 0.5
3557 return quantile(a, q, axis=axis, out=out, overwrite_input=overwrite_input,
-> 3558 keepdims=keepdims, interpolation='midpoint')
3559
3560 def _astype(arr, dtype):
/opt/anaconda3/lib/python3.7/site-packages/jax/numpy/lax_numpy.py in quantile(a, q, axis, out, overwrite_input, interpolation, keepdims)
3464 if interpolation not in ["linear", "lower", "higher", "midpoint", "nearest"]:
3465 raise ValueError("interpolation can only be 'linear', 'lower', 'higher', 'midpoint', or 'nearest'")
-> 3466 return _quantile(a, q, axis, interpolation, keepdims)
3467
3468 @partial(jit, static_argnums=(2, 3, 4))
/opt/anaconda3/lib/python3.7/site-packages/jax/api.py in f_jitted(*args, **kwargs)
151 flat_fun, out_tree = flatten_fun(f, in_tree)
152 out = xla.xla_call(flat_fun, *args_flat, device=device, backend=backend,
--> 153 name=flat_fun.__name__)
154 return tree_unflatten(out_tree(), out)
155
/opt/anaconda3/lib/python3.7/site-packages/jax/core.py in call_bind(primitive, f, *args, **params)
976 if top_trace is None:
977 with new_sublevel():
--> 978 outs = primitive.impl(f, *args, **params)
979 else:
980 tracers = map(top_trace.full_raise, args)
/opt/anaconda3/lib/python3.7/site-packages/jax/interpreters/xla.py in _xla_call_impl(fun, device, backend, name, *args)
461
462 def _xla_call_impl(fun: lu.WrappedFun, *args, device, backend, name):
--> 463 compiled_fun = _xla_callable(fun, device, backend, name, *map(arg_spec, args))
464 try:
465 return compiled_fun(*args)
/opt/anaconda3/lib/python3.7/site-packages/jax/linear_util.py in memoized_fun(fun, *args)
219 fun.populate_stores(stores)
220 else:
--> 221 ans = call(fun, *args)
222 cache[key] = (ans, fun.stores)
223 return ans
/opt/anaconda3/lib/python3.7/site-packages/jax/interpreters/xla.py in _xla_callable(fun, device, backend, name, *arg_specs)
478 pvals: Sequence[pe.PartialVal] = [pe.PartialVal.unknown(aval) for aval in abstract_args]
479 jaxpr, pvals, consts = pe.trace_to_jaxpr(
--> 480 fun, pvals, instantiate=False, stage_out=True, bottom=True)
481
482 _map(prefetch, it.chain(consts, jaxpr_literals(jaxpr)))
/opt/anaconda3/lib/python3.7/site-packages/jax/interpreters/partial_eval.py in trace_to_jaxpr(fun, pvals, instantiate, stage_out, bottom)
419 with new_master(trace_type, bottom=bottom) as master:
420 fun = trace_to_subjaxpr(fun, master, instantiate)
--> 421 jaxpr, (out_pvals, consts, env) = fun.call_wrapped(pvals)
422 assert not env
423 del master
/opt/anaconda3/lib/python3.7/site-packages/jax/linear_util.py in call_wrapped(self, *args, **kwargs)
148 gen = None
149
--> 150 ans = self.f(*args, **dict(self.params, **kwargs))
151 del args
152 while stack:
/opt/anaconda3/lib/python3.7/site-packages/jax/numpy/lax_numpy.py in _quantile(a, q, axis, interpolation, keepdims)
3485 if not issubdtype(a.dtype, floating) or not issubdtype(q.dtype, floating):
3486 msg = "q and a arguments to quantile must be of float type, got {} and {}"
-> 3487 raise TypeError(msg.format(a.dtype, q.dtype))
3488
3489 # Promote q to at least float32 for precise interpolation.
TypeError: q and a arguments to quantile must be of float type, got int32 and float32
|
TypeError
|
def mask(fun: Callable, in_shapes, out_shape) -> Callable:
_check_callable(fun)
in_specs, in_shapes_tree = tree_flatten(in_shapes)
out_specs, out_shapes_tree = tree_flatten(out_shape)
in_specs = map(masking.parse_spec, in_specs)
out_specs = map(masking.parse_spec, out_specs)
unique_ids: Dict[Any, Any] = collections.defaultdict(object)
in_specs = map(partial(_remap_ids, unique_ids), in_specs)
out_specs = map(partial(_remap_ids, unique_ids), out_specs)
def wrapped_fun(args, logical_env):
args_flat, in_tree = tree_flatten(args)
if in_tree != in_shapes_tree:
raise TypeError("pytree mismatch")
logical_env = {unique_ids[name]: val for name, val in logical_env.items()}
in_shapes = map(masking.finalize_spec, in_specs, map(onp.shape, args_flat))
padded_env = _bind_shapes(in_shapes, [x.shape for x in args_flat])
f = lu.wrap_init(fun)
flat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)
outs, out_shapes_ = masking.mask_fun(
flat_fun, logical_env, padded_env, args_flat, in_shapes
)
if not out_tree() == out_shapes_tree:
raise TypeError("pytree mismatch")
out_shapes = map(masking.finalize_spec, out_specs, map(onp.shape, outs))
if not out_shapes == list(out_shapes_):
raise masking.ShapeError
if not all(
onp.shape(out) == eval_polymorphic_shape(shape, padded_env)
for out, shape in zip(outs, out_shapes)
):
raise masking.ShapeError
return tree_unflatten(out_tree(), outs)
return wrapped_fun
|
def mask(fun: Callable, in_shapes, out_shape) -> Callable:
_check_callable(fun)
in_specs, in_shapes_tree = tree_flatten(in_shapes)
out_specs, out_shapes_tree = tree_flatten(out_shape)
in_specs = map(masking.parse_spec, in_specs)
out_specs = map(masking.parse_spec, out_specs)
unique_ids: Dict[Any, Any] = collections.defaultdict(object)
in_specs = map(partial(_remap_ids, unique_ids), in_specs)
out_specs = map(partial(_remap_ids, unique_ids), out_specs)
def wrapped_fun(args, logical_env):
args_flat, in_tree = tree_flatten(args)
if in_tree != in_shapes_tree:
raise TypeError("pytree mismatch")
logical_env = {unique_ids[name]: val for name, val in logical_env.items()}
in_shapes = map(masking.finalize_spec, in_specs, map(onp.shape, args_flat))
padded_env = _bind_shapes(in_shapes, [x.shape for x in args_flat])
f = lu.wrap_init(fun)
flat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)
outs, out_shapes_ = masking.mask_fun(
flat_fun, logical_env, padded_env, args_flat, in_shapes
)
if not out_tree() == out_shapes_tree:
raise TypeError("pytree mismatch")
out_shapes = map(masking.finalize_spec, out_specs, map(onp.shape, outs))
if not out_shapes == list(out_shapes_):
raise masking.ShapeError
if not all(
onp.shape(out) == masking.eval_shape_expr(padded_env, expr)
for out, expr in zip(outs, out_shapes)
):
raise masking.ShapeError
return tree_unflatten(out_tree(), outs)
return wrapped_fun
|
https://github.com/google/jax/issues/2245
|
Traceback (most recent call last):
File "/Users/necula/Source/jax/jax/interpreters/xla.py", line 230, in primitive_computation
return c.Build()
File "/Users/necula/Source/jax/jax/lib/xla_bridge.py", line 281, in Build
*args, **kwargs)
File "/Users/necula/Source/jax/build/jaxlib/xla_client.py", line 734, in Build
return Computation(self._builder.Build(), backend=backend)
RuntimeError: Invalid argument: Slice size at index 0 in gather op is out of range, must be within [0, 6), got 10.:
|
RuntimeError
|
def wrapped_fun(args, logical_env):
args_flat, in_tree = tree_flatten(args)
if in_tree != in_shapes_tree:
raise TypeError("pytree mismatch")
logical_env = {unique_ids[name]: val for name, val in logical_env.items()}
in_shapes = map(masking.finalize_spec, in_specs, map(onp.shape, args_flat))
padded_env = _bind_shapes(in_shapes, [x.shape for x in args_flat])
f = lu.wrap_init(fun)
flat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)
outs, out_shapes_ = masking.mask_fun(
flat_fun, logical_env, padded_env, args_flat, in_shapes
)
if not out_tree() == out_shapes_tree:
raise TypeError("pytree mismatch")
out_shapes = map(masking.finalize_spec, out_specs, map(onp.shape, outs))
if not out_shapes == list(out_shapes_):
raise masking.ShapeError
if not all(
onp.shape(out) == eval_polymorphic_shape(shape, padded_env)
for out, shape in zip(outs, out_shapes)
):
raise masking.ShapeError
return tree_unflatten(out_tree(), outs)
|
def wrapped_fun(args, logical_env):
args_flat, in_tree = tree_flatten(args)
if in_tree != in_shapes_tree:
raise TypeError("pytree mismatch")
logical_env = {unique_ids[name]: val for name, val in logical_env.items()}
in_shapes = map(masking.finalize_spec, in_specs, map(onp.shape, args_flat))
padded_env = _bind_shapes(in_shapes, [x.shape for x in args_flat])
f = lu.wrap_init(fun)
flat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)
outs, out_shapes_ = masking.mask_fun(
flat_fun, logical_env, padded_env, args_flat, in_shapes
)
if not out_tree() == out_shapes_tree:
raise TypeError("pytree mismatch")
out_shapes = map(masking.finalize_spec, out_specs, map(onp.shape, outs))
if not out_shapes == list(out_shapes_):
raise masking.ShapeError
if not all(
onp.shape(out) == masking.eval_shape_expr(padded_env, expr)
for out, expr in zip(outs, out_shapes)
):
raise masking.ShapeError
return tree_unflatten(out_tree(), outs)
|
https://github.com/google/jax/issues/2245
|
Traceback (most recent call last):
File "/Users/necula/Source/jax/jax/interpreters/xla.py", line 230, in primitive_computation
return c.Build()
File "/Users/necula/Source/jax/jax/lib/xla_bridge.py", line 281, in Build
*args, **kwargs)
File "/Users/necula/Source/jax/build/jaxlib/xla_client.py", line 734, in Build
return Computation(self._builder.Build(), backend=backend)
RuntimeError: Invalid argument: Slice size at index 0 in gather op is out of range, must be within [0, 6), got 10.:
|
RuntimeError
|
def _remap_ids(names, shape_spec):
return masking.ShapeSpec(
Poly(
{
Mon({names[id]: deg for id, deg in mon.items()}): coeff
for mon, coeff in poly.items()
}
)
if poly is not masking._monomorphic_dim
else masking._monomorphic_dim
for poly in shape_spec
)
|
def _remap_ids(names, shape_spec):
ShapeSpec, Poly, Mon = masking.ShapeSpec, masking.Poly, masking.Mon
mdim = masking.monomorphic_dim
return ShapeSpec(
Poly(
{
Mon({names[id]: deg for id, deg in mon.items()}): coeff
for mon, coeff in poly.items()
}
)
if poly is not mdim
else mdim
for poly in shape_spec
)
|
https://github.com/google/jax/issues/2245
|
Traceback (most recent call last):
File "/Users/necula/Source/jax/jax/interpreters/xla.py", line 230, in primitive_computation
return c.Build()
File "/Users/necula/Source/jax/jax/lib/xla_bridge.py", line 281, in Build
*args, **kwargs)
File "/Users/necula/Source/jax/build/jaxlib/xla_client.py", line 734, in Build
return Computation(self._builder.Build(), backend=backend)
RuntimeError: Invalid argument: Slice size at index 0 in gather op is out of range, must be within [0, 6), got 10.:
|
RuntimeError
|
def _bind_shapes(shape_exprs, shapes):
env = {}
for shape_expr, shape in zip(shape_exprs, shapes):
for poly, d in zip(shape_expr, shape):
if type(poly) is not Poly or poly.is_constant:
continue
else:
((binder,),) = poly # TODO generalize to handle striding
if env.setdefault(binder, d) != d:
raise masking.ShapeError
return env
|
def _bind_shapes(shape_exprs, shapes):
env = {}
for shape_expr, shape in zip(shape_exprs, shapes):
for poly, d in zip(shape_expr, shape):
if ensure_poly(poly).is_constant:
continue
else:
((binder,),) = poly # TODO generalize to handle striding
if env.setdefault(binder, d) != d:
raise masking.ShapeError
return env
|
https://github.com/google/jax/issues/2245
|
Traceback (most recent call last):
File "/Users/necula/Source/jax/jax/interpreters/xla.py", line 230, in primitive_computation
return c.Build()
File "/Users/necula/Source/jax/jax/lib/xla_bridge.py", line 281, in Build
*args, **kwargs)
File "/Users/necula/Source/jax/build/jaxlib/xla_client.py", line 734, in Build
return Computation(self._builder.Build(), backend=backend)
RuntimeError: Invalid argument: Slice size at index 0 in gather op is out of range, must be within [0, 6), got 10.:
|
RuntimeError
|
def shapecheck(in_shapes, out_shape, fun: Callable):
_check_callable(fun)
in_shapes, in_tree = tree_flatten(in_shapes)
in_shapes = map(masking.parse_spec, in_shapes)
out_shapes, out_tree = tree_flatten(out_shape)
out_shapes = map(masking.parse_spec, out_shapes)
flat_fun, out_tree_ = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)
avals = map(partial(ShapedArray, dtype=onp.float32), in_shapes)
out_shapes_ = [o.shape for o in pe.abstract_eval_fun(flat_fun.call_wrapped, *avals)]
if out_tree != out_tree_():
raise TypeError("pytree mismatch")
if not all(map(masking._shape_spec_consistent, out_shapes, out_shapes_)):
raise masking.ShapeError
return fun
|
def shapecheck(in_shapes, out_shape, fun):
_check_callable(fun)
in_shapes, in_tree = tree_flatten(in_shapes)
in_shapes = map(masking.parse_spec, in_shapes)
out_shapes, out_tree = tree_flatten(out_shape)
out_shapes = map(masking.parse_spec, out_shapes)
flat_fun, out_tree_ = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)
out_shapes_ = masking.shapecheck(flat_fun, in_shapes)
if out_tree != out_tree_():
raise TypeError("pytree mismatch")
if not all(map(_shape_spec_consistent, out_shapes, out_shapes_)):
raise masking.ShapeError
return fun
|
https://github.com/google/jax/issues/2245
|
Traceback (most recent call last):
File "/Users/necula/Source/jax/jax/interpreters/xla.py", line 230, in primitive_computation
return c.Build()
File "/Users/necula/Source/jax/jax/lib/xla_bridge.py", line 281, in Build
*args, **kwargs)
File "/Users/necula/Source/jax/build/jaxlib/xla_client.py", line 734, in Build
return Computation(self._builder.Build(), backend=backend)
RuntimeError: Invalid argument: Slice size at index 0 in gather op is out of range, must be within [0, 6), got 10.:
|
RuntimeError
|
def extend_shape_envs(logical_env, padded_env):
global shape_envs
new_logical = dict(chain(shape_envs.logical.items(), logical_env.items()))
new_padded = dict(chain(shape_envs.padded.items(), padded_env.items()))
shape_envs, prev = ShapeEnvs(new_logical, new_padded), shape_envs
yield
shape_envs = prev
|
def extend_shape_envs(logical_env, padded_env):
global shape_envs
new_logical = dict(it.chain(shape_envs.logical.items(), logical_env.items()))
new_padded = dict(it.chain(shape_envs.padded.items(), padded_env.items()))
shape_envs, prev = ShapeEnvs(new_logical, new_padded), shape_envs
yield
shape_envs = prev
|
https://github.com/google/jax/issues/2245
|
Traceback (most recent call last):
File "/Users/necula/Source/jax/jax/interpreters/xla.py", line 230, in primitive_computation
return c.Build()
File "/Users/necula/Source/jax/jax/lib/xla_bridge.py", line 281, in Build
*args, **kwargs)
File "/Users/necula/Source/jax/build/jaxlib/xla_client.py", line 734, in Build
return Computation(self._builder.Build(), backend=backend)
RuntimeError: Invalid argument: Slice size at index 0 in gather op is out of range, must be within [0, 6), got 10.:
|
RuntimeError
|
def shape_as_value(shape):
return eval_polymorphic_shape(shape, shape_envs.logical)
|
def shape_as_value(expr):
if type(expr) is tuple and is_polymorphic(expr):
return tuple(
eval_dim_expr(shape_envs.logical, d) if type(d) is Poly else d for d in expr
)
else:
return expr
|
https://github.com/google/jax/issues/2245
|
Traceback (most recent call last):
File "/Users/necula/Source/jax/jax/interpreters/xla.py", line 230, in primitive_computation
return c.Build()
File "/Users/necula/Source/jax/jax/lib/xla_bridge.py", line 281, in Build
*args, **kwargs)
File "/Users/necula/Source/jax/build/jaxlib/xla_client.py", line 734, in Build
return Computation(self._builder.Build(), backend=backend)
RuntimeError: Invalid argument: Slice size at index 0 in gather op is out of range, must be within [0, 6), got 10.:
|
RuntimeError
|
def padded_shape_as_value(shape):
return eval_polymorphic_shape(shape, shape_envs.padded)
|
def padded_shape_as_value(expr):
if type(expr) is tuple and is_polymorphic(expr):
return tuple(
eval_dim_expr(shape_envs.padded, d) if type(d) is Poly else d for d in expr
)
else:
return expr
|
https://github.com/google/jax/issues/2245
|
Traceback (most recent call last):
File "/Users/necula/Source/jax/jax/interpreters/xla.py", line 230, in primitive_computation
return c.Build()
File "/Users/necula/Source/jax/jax/lib/xla_bridge.py", line 281, in Build
*args, **kwargs)
File "/Users/necula/Source/jax/build/jaxlib/xla_client.py", line 734, in Build
return Computation(self._builder.Build(), backend=backend)
RuntimeError: Invalid argument: Slice size at index 0 in gather op is out of range, must be within [0, 6), got 10.:
|
RuntimeError
|
def __init__(self, coeffs):
# Makes sure Polynomials are always in canonical form
coeffs = {mon: op.index(coeff) for mon, coeff in coeffs.items() if coeff != 0}
coeffs = coeffs or {Mon(): 0}
super().__init__(coeffs)
|
def __init__(self, coeffs):
# Makes sure Polynomials are always in canonical form to simplify operators:
coeffs = {mon: coeff for mon, coeff in coeffs.items() if coeff != 0}
coeffs = {Mon(): 0} if len(coeffs) == 0 else coeffs
super().__init__(coeffs)
|
https://github.com/google/jax/issues/2245
|
Traceback (most recent call last):
File "/Users/necula/Source/jax/jax/interpreters/xla.py", line 230, in primitive_computation
return c.Build()
File "/Users/necula/Source/jax/jax/lib/xla_bridge.py", line 281, in Build
*args, **kwargs)
File "/Users/necula/Source/jax/build/jaxlib/xla_client.py", line 734, in Build
return Computation(self._builder.Build(), backend=backend)
RuntimeError: Invalid argument: Slice size at index 0 in gather op is out of range, must be within [0, 6), got 10.:
|
RuntimeError
|
def __add__(self, other):
coeffs = self.copy()
for mon, coeff in _ensure_poly(other).items():
coeffs[mon] = coeffs.get(mon, 0) + coeff
return Poly(coeffs)
|
def __add__(self, other):
coeffs = self.copy()
for mon, coeff in ensure_poly(other).items():
coeffs[mon] = coeffs.get(mon, 0) + coeff
return Poly(coeffs)
|
https://github.com/google/jax/issues/2245
|
Traceback (most recent call last):
File "/Users/necula/Source/jax/jax/interpreters/xla.py", line 230, in primitive_computation
return c.Build()
File "/Users/necula/Source/jax/jax/lib/xla_bridge.py", line 281, in Build
*args, **kwargs)
File "/Users/necula/Source/jax/build/jaxlib/xla_client.py", line 734, in Build
return Computation(self._builder.Build(), backend=backend)
RuntimeError: Invalid argument: Slice size at index 0 in gather op is out of range, must be within [0, 6), got 10.:
|
RuntimeError
|
def __mul__(self, other):
other = _ensure_poly(other)
coeffs = {}
for (mon1, coeff1), (mon2, coeff2) in product(self.items(), other.items()):
mon = mon1 * mon2
coeffs[mon] = coeffs.get(mon, 0) + coeff1 * coeff2
return Poly(coeffs)
|
def __mul__(self, other):
coeffs = dict()
for (mon1, coeff1), (mon2, coeff2) in it.product(
self.items(), ensure_poly(other).items()
):
mon = Mon(mon1 + mon2) # add monomials' id degrees
coeff = coeff1 * coeff2 # multiply integer coeffs
coeffs[mon] = coeffs.get(mon, 0) + coeff # accumulate coeffs
return Poly(coeffs)
|
https://github.com/google/jax/issues/2245
|
Traceback (most recent call last):
File "/Users/necula/Source/jax/jax/interpreters/xla.py", line 230, in primitive_computation
return c.Build()
File "/Users/necula/Source/jax/jax/lib/xla_bridge.py", line 281, in Build
*args, **kwargs)
File "/Users/necula/Source/jax/build/jaxlib/xla_client.py", line 734, in Build
return Computation(self._builder.Build(), backend=backend)
RuntimeError: Invalid argument: Slice size at index 0 in gather op is out of range, must be within [0, 6), got 10.:
|
RuntimeError
|
def __rmul__(self, other):
return self * other # multiplication commutes
|
def __rmul__(self, other):
return self * other
|
https://github.com/google/jax/issues/2245
|
Traceback (most recent call last):
File "/Users/necula/Source/jax/jax/interpreters/xla.py", line 230, in primitive_computation
return c.Build()
File "/Users/necula/Source/jax/jax/lib/xla_bridge.py", line 281, in Build
*args, **kwargs)
File "/Users/necula/Source/jax/build/jaxlib/xla_client.py", line 734, in Build
return Computation(self._builder.Build(), backend=backend)
RuntimeError: Invalid argument: Slice size at index 0 in gather op is out of range, must be within [0, 6), got 10.:
|
RuntimeError
|
def __radd__(self, other):
return self + other # addition commutes
|
def __radd__(self, other):
return self + other
|
https://github.com/google/jax/issues/2245
|
Traceback (most recent call last):
File "/Users/necula/Source/jax/jax/interpreters/xla.py", line 230, in primitive_computation
return c.Build()
File "/Users/necula/Source/jax/jax/lib/xla_bridge.py", line 281, in Build
*args, **kwargs)
File "/Users/necula/Source/jax/build/jaxlib/xla_client.py", line 734, in Build
return Computation(self._builder.Build(), backend=backend)
RuntimeError: Invalid argument: Slice size at index 0 in gather op is out of range, must be within [0, 6), got 10.:
|
RuntimeError
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.