Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- parrot/lib/python3.10/asyncio/__init__.py +43 -0
- parrot/lib/python3.10/asyncio/__main__.py +127 -0
- parrot/lib/python3.10/asyncio/base_futures.py +80 -0
- parrot/lib/python3.10/asyncio/base_tasks.py +85 -0
- parrot/lib/python3.10/asyncio/coroutines.py +269 -0
- parrot/lib/python3.10/asyncio/exceptions.py +58 -0
- parrot/lib/python3.10/asyncio/format_helpers.py +76 -0
- parrot/lib/python3.10/asyncio/futures.py +426 -0
- parrot/lib/python3.10/asyncio/locks.py +438 -0
- parrot/lib/python3.10/asyncio/mixins.py +31 -0
- parrot/lib/python3.10/asyncio/protocols.py +216 -0
- parrot/lib/python3.10/asyncio/runners.py +73 -0
- parrot/lib/python3.10/asyncio/selector_events.py +1105 -0
- parrot/lib/python3.10/asyncio/subprocess.py +223 -0
- parrot/lib/python3.10/asyncio/tasks.py +946 -0
- parrot/lib/python3.10/asyncio/threads.py +25 -0
- parrot/lib/python3.10/asyncio/windows_utils.py +173 -0
- parrot/lib/python3.10/site-packages/fire-0.6.0.dist-info/INSTALLER +1 -0
- parrot/lib/python3.10/site-packages/fire-0.6.0.dist-info/LICENSE +13 -0
- parrot/lib/python3.10/site-packages/fire-0.6.0.dist-info/RECORD +99 -0
- parrot/lib/python3.10/site-packages/fire-0.6.0.dist-info/REQUESTED +0 -0
- parrot/lib/python3.10/site-packages/fire-0.6.0.dist-info/WHEEL +6 -0
- parrot/lib/python3.10/site-packages/fire-0.6.0.dist-info/top_level.txt +1 -0
- parrot/lib/python3.10/site-packages/jsonschema_specifications-2023.12.1.dist-info/INSTALLER +1 -0
- parrot/lib/python3.10/site-packages/jsonschema_specifications-2023.12.1.dist-info/METADATA +56 -0
- parrot/lib/python3.10/site-packages/jsonschema_specifications-2023.12.1.dist-info/RECORD +34 -0
- parrot/lib/python3.10/site-packages/jsonschema_specifications-2023.12.1.dist-info/REQUESTED +0 -0
- parrot/lib/python3.10/site-packages/jsonschema_specifications-2023.12.1.dist-info/WHEEL +4 -0
- parrot/lib/python3.10/site-packages/jsonschema_specifications-2023.12.1.dist-info/licenses/COPYING +19 -0
- parrot/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/INSTALLER +1 -0
- parrot/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/LICENSE +38 -0
- parrot/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/METADATA +203 -0
- parrot/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/RECORD +74 -0
- parrot/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/REQUESTED +0 -0
- parrot/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/WHEEL +5 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/native/BatchLinearAlgebra.h +321 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/native/BinaryOps.h +119 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/native/ComplexHelper.h +97 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/native/CompositeRandomAccessorCommon.h +263 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/native/Cross.h +14 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/native/DilatedConvolutionUtils.h +229 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/native/DistributionTemplates.h +394 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/native/EmbeddingBag.h +153 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/native/FusedSGD.h +21 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/native/GridSampler.h +298 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/native/GridSamplerUtils.h +105 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/native/IndexKernel.h +41 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/native/Lerp.h +46 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/native/LinearAlgebraUtils.h +623 -0
- vllm/lib/python3.10/site-packages/torch/include/ATen/native/Math.h +0 -0
parrot/lib/python3.10/asyncio/__init__.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The asyncio package, tracking PEP 3156."""
|
| 2 |
+
|
| 3 |
+
# flake8: noqa
|
| 4 |
+
|
| 5 |
+
import sys
|
| 6 |
+
|
| 7 |
+
# This relies on each of the submodules having an __all__ variable.
|
| 8 |
+
from .base_events import *
|
| 9 |
+
from .coroutines import *
|
| 10 |
+
from .events import *
|
| 11 |
+
from .exceptions import *
|
| 12 |
+
from .futures import *
|
| 13 |
+
from .locks import *
|
| 14 |
+
from .protocols import *
|
| 15 |
+
from .runners import *
|
| 16 |
+
from .queues import *
|
| 17 |
+
from .streams import *
|
| 18 |
+
from .subprocess import *
|
| 19 |
+
from .tasks import *
|
| 20 |
+
from .threads import *
|
| 21 |
+
from .transports import *
|
| 22 |
+
|
| 23 |
+
__all__ = (base_events.__all__ +
|
| 24 |
+
coroutines.__all__ +
|
| 25 |
+
events.__all__ +
|
| 26 |
+
exceptions.__all__ +
|
| 27 |
+
futures.__all__ +
|
| 28 |
+
locks.__all__ +
|
| 29 |
+
protocols.__all__ +
|
| 30 |
+
runners.__all__ +
|
| 31 |
+
queues.__all__ +
|
| 32 |
+
streams.__all__ +
|
| 33 |
+
subprocess.__all__ +
|
| 34 |
+
tasks.__all__ +
|
| 35 |
+
threads.__all__ +
|
| 36 |
+
transports.__all__)
|
| 37 |
+
|
| 38 |
+
if sys.platform == 'win32': # pragma: no cover
|
| 39 |
+
from .windows_events import *
|
| 40 |
+
__all__ += windows_events.__all__
|
| 41 |
+
else:
|
| 42 |
+
from .unix_events import * # pragma: no cover
|
| 43 |
+
__all__ += unix_events.__all__
|
parrot/lib/python3.10/asyncio/__main__.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ast
|
| 2 |
+
import asyncio
|
| 3 |
+
import code
|
| 4 |
+
import concurrent.futures
|
| 5 |
+
import inspect
|
| 6 |
+
import sys
|
| 7 |
+
import threading
|
| 8 |
+
import types
|
| 9 |
+
import warnings
|
| 10 |
+
|
| 11 |
+
from . import futures
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class AsyncIOInteractiveConsole(code.InteractiveConsole):
|
| 15 |
+
|
| 16 |
+
def __init__(self, locals, loop):
|
| 17 |
+
super().__init__(locals)
|
| 18 |
+
self.compile.compiler.flags |= ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
|
| 19 |
+
|
| 20 |
+
self.loop = loop
|
| 21 |
+
|
| 22 |
+
def runcode(self, code):
|
| 23 |
+
future = concurrent.futures.Future()
|
| 24 |
+
|
| 25 |
+
def callback():
|
| 26 |
+
global repl_future
|
| 27 |
+
global repl_future_interrupted
|
| 28 |
+
|
| 29 |
+
repl_future = None
|
| 30 |
+
repl_future_interrupted = False
|
| 31 |
+
|
| 32 |
+
func = types.FunctionType(code, self.locals)
|
| 33 |
+
try:
|
| 34 |
+
coro = func()
|
| 35 |
+
except SystemExit:
|
| 36 |
+
raise
|
| 37 |
+
except KeyboardInterrupt as ex:
|
| 38 |
+
repl_future_interrupted = True
|
| 39 |
+
future.set_exception(ex)
|
| 40 |
+
return
|
| 41 |
+
except BaseException as ex:
|
| 42 |
+
future.set_exception(ex)
|
| 43 |
+
return
|
| 44 |
+
|
| 45 |
+
if not inspect.iscoroutine(coro):
|
| 46 |
+
future.set_result(coro)
|
| 47 |
+
return
|
| 48 |
+
|
| 49 |
+
try:
|
| 50 |
+
repl_future = self.loop.create_task(coro)
|
| 51 |
+
futures._chain_future(repl_future, future)
|
| 52 |
+
except BaseException as exc:
|
| 53 |
+
future.set_exception(exc)
|
| 54 |
+
|
| 55 |
+
loop.call_soon_threadsafe(callback)
|
| 56 |
+
|
| 57 |
+
try:
|
| 58 |
+
return future.result()
|
| 59 |
+
except SystemExit:
|
| 60 |
+
raise
|
| 61 |
+
except BaseException:
|
| 62 |
+
if repl_future_interrupted:
|
| 63 |
+
self.write("\nKeyboardInterrupt\n")
|
| 64 |
+
else:
|
| 65 |
+
self.showtraceback()
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class REPLThread(threading.Thread):
|
| 69 |
+
|
| 70 |
+
def run(self):
|
| 71 |
+
try:
|
| 72 |
+
banner = (
|
| 73 |
+
f'asyncio REPL {sys.version} on {sys.platform}\n'
|
| 74 |
+
f'Use "await" directly instead of "asyncio.run()".\n'
|
| 75 |
+
f'Type "help", "copyright", "credits" or "license" '
|
| 76 |
+
f'for more information.\n'
|
| 77 |
+
f'{getattr(sys, "ps1", ">>> ")}import asyncio'
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
console.interact(
|
| 81 |
+
banner=banner,
|
| 82 |
+
exitmsg='exiting asyncio REPL...')
|
| 83 |
+
finally:
|
| 84 |
+
warnings.filterwarnings(
|
| 85 |
+
'ignore',
|
| 86 |
+
message=r'^coroutine .* was never awaited$',
|
| 87 |
+
category=RuntimeWarning)
|
| 88 |
+
|
| 89 |
+
loop.call_soon_threadsafe(loop.stop)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
if __name__ == '__main__':
|
| 93 |
+
sys.audit("cpython.run_stdin")
|
| 94 |
+
|
| 95 |
+
loop = asyncio.new_event_loop()
|
| 96 |
+
asyncio.set_event_loop(loop)
|
| 97 |
+
|
| 98 |
+
repl_locals = {'asyncio': asyncio}
|
| 99 |
+
for key in {'__name__', '__package__',
|
| 100 |
+
'__loader__', '__spec__',
|
| 101 |
+
'__builtins__', '__file__'}:
|
| 102 |
+
repl_locals[key] = locals()[key]
|
| 103 |
+
|
| 104 |
+
console = AsyncIOInteractiveConsole(repl_locals, loop)
|
| 105 |
+
|
| 106 |
+
repl_future = None
|
| 107 |
+
repl_future_interrupted = False
|
| 108 |
+
|
| 109 |
+
try:
|
| 110 |
+
import readline # NoQA
|
| 111 |
+
except ImportError:
|
| 112 |
+
pass
|
| 113 |
+
|
| 114 |
+
repl_thread = REPLThread()
|
| 115 |
+
repl_thread.daemon = True
|
| 116 |
+
repl_thread.start()
|
| 117 |
+
|
| 118 |
+
while True:
|
| 119 |
+
try:
|
| 120 |
+
loop.run_forever()
|
| 121 |
+
except KeyboardInterrupt:
|
| 122 |
+
if repl_future and not repl_future.done():
|
| 123 |
+
repl_future.cancel()
|
| 124 |
+
repl_future_interrupted = True
|
| 125 |
+
continue
|
| 126 |
+
else:
|
| 127 |
+
break
|
parrot/lib/python3.10/asyncio/base_futures.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__all__ = ()
|
| 2 |
+
|
| 3 |
+
import reprlib
|
| 4 |
+
from _thread import get_ident
|
| 5 |
+
|
| 6 |
+
from . import format_helpers
|
| 7 |
+
|
| 8 |
+
# States for Future.
|
| 9 |
+
_PENDING = 'PENDING'
|
| 10 |
+
_CANCELLED = 'CANCELLED'
|
| 11 |
+
_FINISHED = 'FINISHED'
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def isfuture(obj):
|
| 15 |
+
"""Check for a Future.
|
| 16 |
+
|
| 17 |
+
This returns True when obj is a Future instance or is advertising
|
| 18 |
+
itself as duck-type compatible by setting _asyncio_future_blocking.
|
| 19 |
+
See comment in Future for more details.
|
| 20 |
+
"""
|
| 21 |
+
return (hasattr(obj.__class__, '_asyncio_future_blocking') and
|
| 22 |
+
obj._asyncio_future_blocking is not None)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _format_callbacks(cb):
|
| 26 |
+
"""helper function for Future.__repr__"""
|
| 27 |
+
size = len(cb)
|
| 28 |
+
if not size:
|
| 29 |
+
cb = ''
|
| 30 |
+
|
| 31 |
+
def format_cb(callback):
|
| 32 |
+
return format_helpers._format_callback_source(callback, ())
|
| 33 |
+
|
| 34 |
+
if size == 1:
|
| 35 |
+
cb = format_cb(cb[0][0])
|
| 36 |
+
elif size == 2:
|
| 37 |
+
cb = '{}, {}'.format(format_cb(cb[0][0]), format_cb(cb[1][0]))
|
| 38 |
+
elif size > 2:
|
| 39 |
+
cb = '{}, <{} more>, {}'.format(format_cb(cb[0][0]),
|
| 40 |
+
size - 2,
|
| 41 |
+
format_cb(cb[-1][0]))
|
| 42 |
+
return f'cb=[{cb}]'
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# bpo-42183: _repr_running is needed for repr protection
|
| 46 |
+
# when a Future or Task result contains itself directly or indirectly.
|
| 47 |
+
# The logic is borrowed from @reprlib.recursive_repr decorator.
|
| 48 |
+
# Unfortunately, the direct decorator usage is impossible because of
|
| 49 |
+
# AttributeError: '_asyncio.Task' object has no attribute '__module__' error.
|
| 50 |
+
#
|
| 51 |
+
# After fixing this thing we can return to the decorator based approach.
|
| 52 |
+
_repr_running = set()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _future_repr_info(future):
|
| 56 |
+
# (Future) -> str
|
| 57 |
+
"""helper function for Future.__repr__"""
|
| 58 |
+
info = [future._state.lower()]
|
| 59 |
+
if future._state == _FINISHED:
|
| 60 |
+
if future._exception is not None:
|
| 61 |
+
info.append(f'exception={future._exception!r}')
|
| 62 |
+
else:
|
| 63 |
+
key = id(future), get_ident()
|
| 64 |
+
if key in _repr_running:
|
| 65 |
+
result = '...'
|
| 66 |
+
else:
|
| 67 |
+
_repr_running.add(key)
|
| 68 |
+
try:
|
| 69 |
+
# use reprlib to limit the length of the output, especially
|
| 70 |
+
# for very long strings
|
| 71 |
+
result = reprlib.repr(future._result)
|
| 72 |
+
finally:
|
| 73 |
+
_repr_running.discard(key)
|
| 74 |
+
info.append(f'result={result}')
|
| 75 |
+
if future._callbacks:
|
| 76 |
+
info.append(_format_callbacks(future._callbacks))
|
| 77 |
+
if future._source_traceback:
|
| 78 |
+
frame = future._source_traceback[-1]
|
| 79 |
+
info.append(f'created at {frame[0]}:{frame[1]}')
|
| 80 |
+
return info
|
parrot/lib/python3.10/asyncio/base_tasks.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import linecache
|
| 2 |
+
import traceback
|
| 3 |
+
|
| 4 |
+
from . import base_futures
|
| 5 |
+
from . import coroutines
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _task_repr_info(task):
|
| 9 |
+
info = base_futures._future_repr_info(task)
|
| 10 |
+
|
| 11 |
+
if task._must_cancel:
|
| 12 |
+
# replace status
|
| 13 |
+
info[0] = 'cancelling'
|
| 14 |
+
|
| 15 |
+
info.insert(1, 'name=%r' % task.get_name())
|
| 16 |
+
|
| 17 |
+
coro = coroutines._format_coroutine(task._coro)
|
| 18 |
+
info.insert(2, f'coro=<{coro}>')
|
| 19 |
+
|
| 20 |
+
if task._fut_waiter is not None:
|
| 21 |
+
info.insert(3, f'wait_for={task._fut_waiter!r}')
|
| 22 |
+
return info
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _task_get_stack(task, limit):
|
| 26 |
+
frames = []
|
| 27 |
+
if hasattr(task._coro, 'cr_frame'):
|
| 28 |
+
# case 1: 'async def' coroutines
|
| 29 |
+
f = task._coro.cr_frame
|
| 30 |
+
elif hasattr(task._coro, 'gi_frame'):
|
| 31 |
+
# case 2: legacy coroutines
|
| 32 |
+
f = task._coro.gi_frame
|
| 33 |
+
elif hasattr(task._coro, 'ag_frame'):
|
| 34 |
+
# case 3: async generators
|
| 35 |
+
f = task._coro.ag_frame
|
| 36 |
+
else:
|
| 37 |
+
# case 4: unknown objects
|
| 38 |
+
f = None
|
| 39 |
+
if f is not None:
|
| 40 |
+
while f is not None:
|
| 41 |
+
if limit is not None:
|
| 42 |
+
if limit <= 0:
|
| 43 |
+
break
|
| 44 |
+
limit -= 1
|
| 45 |
+
frames.append(f)
|
| 46 |
+
f = f.f_back
|
| 47 |
+
frames.reverse()
|
| 48 |
+
elif task._exception is not None:
|
| 49 |
+
tb = task._exception.__traceback__
|
| 50 |
+
while tb is not None:
|
| 51 |
+
if limit is not None:
|
| 52 |
+
if limit <= 0:
|
| 53 |
+
break
|
| 54 |
+
limit -= 1
|
| 55 |
+
frames.append(tb.tb_frame)
|
| 56 |
+
tb = tb.tb_next
|
| 57 |
+
return frames
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _task_print_stack(task, limit, file):
|
| 61 |
+
extracted_list = []
|
| 62 |
+
checked = set()
|
| 63 |
+
for f in task.get_stack(limit=limit):
|
| 64 |
+
lineno = f.f_lineno
|
| 65 |
+
co = f.f_code
|
| 66 |
+
filename = co.co_filename
|
| 67 |
+
name = co.co_name
|
| 68 |
+
if filename not in checked:
|
| 69 |
+
checked.add(filename)
|
| 70 |
+
linecache.checkcache(filename)
|
| 71 |
+
line = linecache.getline(filename, lineno, f.f_globals)
|
| 72 |
+
extracted_list.append((filename, lineno, name, line))
|
| 73 |
+
|
| 74 |
+
exc = task._exception
|
| 75 |
+
if not extracted_list:
|
| 76 |
+
print(f'No stack for {task!r}', file=file)
|
| 77 |
+
elif exc is not None:
|
| 78 |
+
print(f'Traceback for {task!r} (most recent call last):', file=file)
|
| 79 |
+
else:
|
| 80 |
+
print(f'Stack for {task!r} (most recent call last):', file=file)
|
| 81 |
+
|
| 82 |
+
traceback.print_list(extracted_list, file=file)
|
| 83 |
+
if exc is not None:
|
| 84 |
+
for line in traceback.format_exception_only(exc.__class__, exc):
|
| 85 |
+
print(line, file=file, end='')
|
parrot/lib/python3.10/asyncio/coroutines.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__all__ = 'coroutine', 'iscoroutinefunction', 'iscoroutine'
|
| 2 |
+
|
| 3 |
+
import collections.abc
|
| 4 |
+
import functools
|
| 5 |
+
import inspect
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
import traceback
|
| 9 |
+
import types
|
| 10 |
+
import warnings
|
| 11 |
+
|
| 12 |
+
from . import base_futures
|
| 13 |
+
from . import constants
|
| 14 |
+
from . import format_helpers
|
| 15 |
+
from .log import logger
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _is_debug_mode():
|
| 19 |
+
# If you set _DEBUG to true, @coroutine will wrap the resulting
|
| 20 |
+
# generator objects in a CoroWrapper instance (defined below). That
|
| 21 |
+
# instance will log a message when the generator is never iterated
|
| 22 |
+
# over, which may happen when you forget to use "await" or "yield from"
|
| 23 |
+
# with a coroutine call.
|
| 24 |
+
# Note that the value of the _DEBUG flag is taken
|
| 25 |
+
# when the decorator is used, so to be of any use it must be set
|
| 26 |
+
# before you define your coroutines. A downside of using this feature
|
| 27 |
+
# is that tracebacks show entries for the CoroWrapper.__next__ method
|
| 28 |
+
# when _DEBUG is true.
|
| 29 |
+
return sys.flags.dev_mode or (not sys.flags.ignore_environment and
|
| 30 |
+
bool(os.environ.get('PYTHONASYNCIODEBUG')))
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
_DEBUG = _is_debug_mode()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class CoroWrapper:
|
| 37 |
+
# Wrapper for coroutine object in _DEBUG mode.
|
| 38 |
+
|
| 39 |
+
def __init__(self, gen, func=None):
|
| 40 |
+
assert inspect.isgenerator(gen) or inspect.iscoroutine(gen), gen
|
| 41 |
+
self.gen = gen
|
| 42 |
+
self.func = func # Used to unwrap @coroutine decorator
|
| 43 |
+
self._source_traceback = format_helpers.extract_stack(sys._getframe(1))
|
| 44 |
+
self.__name__ = getattr(gen, '__name__', None)
|
| 45 |
+
self.__qualname__ = getattr(gen, '__qualname__', None)
|
| 46 |
+
|
| 47 |
+
def __repr__(self):
|
| 48 |
+
coro_repr = _format_coroutine(self)
|
| 49 |
+
if self._source_traceback:
|
| 50 |
+
frame = self._source_traceback[-1]
|
| 51 |
+
coro_repr += f', created at {frame[0]}:{frame[1]}'
|
| 52 |
+
|
| 53 |
+
return f'<{self.__class__.__name__} {coro_repr}>'
|
| 54 |
+
|
| 55 |
+
def __iter__(self):
|
| 56 |
+
return self
|
| 57 |
+
|
| 58 |
+
def __next__(self):
|
| 59 |
+
return self.gen.send(None)
|
| 60 |
+
|
| 61 |
+
def send(self, value):
|
| 62 |
+
return self.gen.send(value)
|
| 63 |
+
|
| 64 |
+
def throw(self, type, value=None, traceback=None):
|
| 65 |
+
return self.gen.throw(type, value, traceback)
|
| 66 |
+
|
| 67 |
+
def close(self):
|
| 68 |
+
return self.gen.close()
|
| 69 |
+
|
| 70 |
+
@property
|
| 71 |
+
def gi_frame(self):
|
| 72 |
+
return self.gen.gi_frame
|
| 73 |
+
|
| 74 |
+
@property
|
| 75 |
+
def gi_running(self):
|
| 76 |
+
return self.gen.gi_running
|
| 77 |
+
|
| 78 |
+
@property
|
| 79 |
+
def gi_code(self):
|
| 80 |
+
return self.gen.gi_code
|
| 81 |
+
|
| 82 |
+
def __await__(self):
|
| 83 |
+
return self
|
| 84 |
+
|
| 85 |
+
@property
|
| 86 |
+
def gi_yieldfrom(self):
|
| 87 |
+
return self.gen.gi_yieldfrom
|
| 88 |
+
|
| 89 |
+
def __del__(self):
|
| 90 |
+
# Be careful accessing self.gen.frame -- self.gen might not exist.
|
| 91 |
+
gen = getattr(self, 'gen', None)
|
| 92 |
+
frame = getattr(gen, 'gi_frame', None)
|
| 93 |
+
if frame is not None and frame.f_lasti == -1:
|
| 94 |
+
msg = f'{self!r} was never yielded from'
|
| 95 |
+
tb = getattr(self, '_source_traceback', ())
|
| 96 |
+
if tb:
|
| 97 |
+
tb = ''.join(traceback.format_list(tb))
|
| 98 |
+
msg += (f'\nCoroutine object created at '
|
| 99 |
+
f'(most recent call last, truncated to '
|
| 100 |
+
f'{constants.DEBUG_STACK_DEPTH} last lines):\n')
|
| 101 |
+
msg += tb.rstrip()
|
| 102 |
+
logger.error(msg)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def coroutine(func):
|
| 106 |
+
"""Decorator to mark coroutines.
|
| 107 |
+
|
| 108 |
+
If the coroutine is not yielded from before it is destroyed,
|
| 109 |
+
an error message is logged.
|
| 110 |
+
"""
|
| 111 |
+
warnings.warn('"@coroutine" decorator is deprecated since Python 3.8, use "async def" instead',
|
| 112 |
+
DeprecationWarning,
|
| 113 |
+
stacklevel=2)
|
| 114 |
+
if inspect.iscoroutinefunction(func):
|
| 115 |
+
# In Python 3.5 that's all we need to do for coroutines
|
| 116 |
+
# defined with "async def".
|
| 117 |
+
return func
|
| 118 |
+
|
| 119 |
+
if inspect.isgeneratorfunction(func):
|
| 120 |
+
coro = func
|
| 121 |
+
else:
|
| 122 |
+
@functools.wraps(func)
|
| 123 |
+
def coro(*args, **kw):
|
| 124 |
+
res = func(*args, **kw)
|
| 125 |
+
if (base_futures.isfuture(res) or inspect.isgenerator(res) or
|
| 126 |
+
isinstance(res, CoroWrapper)):
|
| 127 |
+
res = yield from res
|
| 128 |
+
else:
|
| 129 |
+
# If 'res' is an awaitable, run it.
|
| 130 |
+
try:
|
| 131 |
+
await_meth = res.__await__
|
| 132 |
+
except AttributeError:
|
| 133 |
+
pass
|
| 134 |
+
else:
|
| 135 |
+
if isinstance(res, collections.abc.Awaitable):
|
| 136 |
+
res = yield from await_meth()
|
| 137 |
+
return res
|
| 138 |
+
|
| 139 |
+
coro = types.coroutine(coro)
|
| 140 |
+
if not _DEBUG:
|
| 141 |
+
wrapper = coro
|
| 142 |
+
else:
|
| 143 |
+
@functools.wraps(func)
|
| 144 |
+
def wrapper(*args, **kwds):
|
| 145 |
+
w = CoroWrapper(coro(*args, **kwds), func=func)
|
| 146 |
+
if w._source_traceback:
|
| 147 |
+
del w._source_traceback[-1]
|
| 148 |
+
# Python < 3.5 does not implement __qualname__
|
| 149 |
+
# on generator objects, so we set it manually.
|
| 150 |
+
# We use getattr as some callables (such as
|
| 151 |
+
# functools.partial may lack __qualname__).
|
| 152 |
+
w.__name__ = getattr(func, '__name__', None)
|
| 153 |
+
w.__qualname__ = getattr(func, '__qualname__', None)
|
| 154 |
+
return w
|
| 155 |
+
|
| 156 |
+
wrapper._is_coroutine = _is_coroutine # For iscoroutinefunction().
|
| 157 |
+
return wrapper
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
# A marker for iscoroutinefunction.
|
| 161 |
+
_is_coroutine = object()
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def iscoroutinefunction(func):
|
| 165 |
+
"""Return True if func is a decorated coroutine function."""
|
| 166 |
+
return (inspect.iscoroutinefunction(func) or
|
| 167 |
+
getattr(func, '_is_coroutine', None) is _is_coroutine)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
# Prioritize native coroutine check to speed-up
|
| 171 |
+
# asyncio.iscoroutine.
|
| 172 |
+
_COROUTINE_TYPES = (types.CoroutineType, types.GeneratorType,
|
| 173 |
+
collections.abc.Coroutine, CoroWrapper)
|
| 174 |
+
_iscoroutine_typecache = set()
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def iscoroutine(obj):
|
| 178 |
+
"""Return True if obj is a coroutine object."""
|
| 179 |
+
if type(obj) in _iscoroutine_typecache:
|
| 180 |
+
return True
|
| 181 |
+
|
| 182 |
+
if isinstance(obj, _COROUTINE_TYPES):
|
| 183 |
+
# Just in case we don't want to cache more than 100
|
| 184 |
+
# positive types. That shouldn't ever happen, unless
|
| 185 |
+
# someone stressing the system on purpose.
|
| 186 |
+
if len(_iscoroutine_typecache) < 100:
|
| 187 |
+
_iscoroutine_typecache.add(type(obj))
|
| 188 |
+
return True
|
| 189 |
+
else:
|
| 190 |
+
return False
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def _format_coroutine(coro):
|
| 194 |
+
assert iscoroutine(coro)
|
| 195 |
+
|
| 196 |
+
is_corowrapper = isinstance(coro, CoroWrapper)
|
| 197 |
+
|
| 198 |
+
def get_name(coro):
|
| 199 |
+
# Coroutines compiled with Cython sometimes don't have
|
| 200 |
+
# proper __qualname__ or __name__. While that is a bug
|
| 201 |
+
# in Cython, asyncio shouldn't crash with an AttributeError
|
| 202 |
+
# in its __repr__ functions.
|
| 203 |
+
if is_corowrapper:
|
| 204 |
+
return format_helpers._format_callback(coro.func, (), {})
|
| 205 |
+
|
| 206 |
+
if hasattr(coro, '__qualname__') and coro.__qualname__:
|
| 207 |
+
coro_name = coro.__qualname__
|
| 208 |
+
elif hasattr(coro, '__name__') and coro.__name__:
|
| 209 |
+
coro_name = coro.__name__
|
| 210 |
+
else:
|
| 211 |
+
# Stop masking Cython bugs, expose them in a friendly way.
|
| 212 |
+
coro_name = f'<{type(coro).__name__} without __name__>'
|
| 213 |
+
return f'{coro_name}()'
|
| 214 |
+
|
| 215 |
+
def is_running(coro):
|
| 216 |
+
try:
|
| 217 |
+
return coro.cr_running
|
| 218 |
+
except AttributeError:
|
| 219 |
+
try:
|
| 220 |
+
return coro.gi_running
|
| 221 |
+
except AttributeError:
|
| 222 |
+
return False
|
| 223 |
+
|
| 224 |
+
coro_code = None
|
| 225 |
+
if hasattr(coro, 'cr_code') and coro.cr_code:
|
| 226 |
+
coro_code = coro.cr_code
|
| 227 |
+
elif hasattr(coro, 'gi_code') and coro.gi_code:
|
| 228 |
+
coro_code = coro.gi_code
|
| 229 |
+
|
| 230 |
+
coro_name = get_name(coro)
|
| 231 |
+
|
| 232 |
+
if not coro_code:
|
| 233 |
+
# Built-in types might not have __qualname__ or __name__.
|
| 234 |
+
if is_running(coro):
|
| 235 |
+
return f'{coro_name} running'
|
| 236 |
+
else:
|
| 237 |
+
return coro_name
|
| 238 |
+
|
| 239 |
+
coro_frame = None
|
| 240 |
+
if hasattr(coro, 'gi_frame') and coro.gi_frame:
|
| 241 |
+
coro_frame = coro.gi_frame
|
| 242 |
+
elif hasattr(coro, 'cr_frame') and coro.cr_frame:
|
| 243 |
+
coro_frame = coro.cr_frame
|
| 244 |
+
|
| 245 |
+
# If Cython's coroutine has a fake code object without proper
|
| 246 |
+
# co_filename -- expose that.
|
| 247 |
+
filename = coro_code.co_filename or '<empty co_filename>'
|
| 248 |
+
|
| 249 |
+
lineno = 0
|
| 250 |
+
if (is_corowrapper and
|
| 251 |
+
coro.func is not None and
|
| 252 |
+
not inspect.isgeneratorfunction(coro.func)):
|
| 253 |
+
source = format_helpers._get_function_source(coro.func)
|
| 254 |
+
if source is not None:
|
| 255 |
+
filename, lineno = source
|
| 256 |
+
if coro_frame is None:
|
| 257 |
+
coro_repr = f'{coro_name} done, defined at {filename}:{lineno}'
|
| 258 |
+
else:
|
| 259 |
+
coro_repr = f'{coro_name} running, defined at {filename}:{lineno}'
|
| 260 |
+
|
| 261 |
+
elif coro_frame is not None:
|
| 262 |
+
lineno = coro_frame.f_lineno
|
| 263 |
+
coro_repr = f'{coro_name} running at {filename}:{lineno}'
|
| 264 |
+
|
| 265 |
+
else:
|
| 266 |
+
lineno = coro_code.co_firstlineno
|
| 267 |
+
coro_repr = f'{coro_name} done, defined at {filename}:{lineno}'
|
| 268 |
+
|
| 269 |
+
return coro_repr
|
parrot/lib/python3.10/asyncio/exceptions.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""asyncio exceptions."""
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
__all__ = ('CancelledError', 'InvalidStateError', 'TimeoutError',
|
| 5 |
+
'IncompleteReadError', 'LimitOverrunError',
|
| 6 |
+
'SendfileNotAvailableError')
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class CancelledError(BaseException):
|
| 10 |
+
"""The Future or Task was cancelled."""
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TimeoutError(Exception):
|
| 14 |
+
"""The operation exceeded the given deadline."""
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class InvalidStateError(Exception):
|
| 18 |
+
"""The operation is not allowed in this state."""
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class SendfileNotAvailableError(RuntimeError):
|
| 22 |
+
"""Sendfile syscall is not available.
|
| 23 |
+
|
| 24 |
+
Raised if OS does not support sendfile syscall for given socket or
|
| 25 |
+
file type.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class IncompleteReadError(EOFError):
|
| 30 |
+
"""
|
| 31 |
+
Incomplete read error. Attributes:
|
| 32 |
+
|
| 33 |
+
- partial: read bytes string before the end of stream was reached
|
| 34 |
+
- expected: total number of expected bytes (or None if unknown)
|
| 35 |
+
"""
|
| 36 |
+
def __init__(self, partial, expected):
|
| 37 |
+
r_expected = 'undefined' if expected is None else repr(expected)
|
| 38 |
+
super().__init__(f'{len(partial)} bytes read on a total of '
|
| 39 |
+
f'{r_expected} expected bytes')
|
| 40 |
+
self.partial = partial
|
| 41 |
+
self.expected = expected
|
| 42 |
+
|
| 43 |
+
def __reduce__(self):
|
| 44 |
+
return type(self), (self.partial, self.expected)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class LimitOverrunError(Exception):
|
| 48 |
+
"""Reached the buffer limit while looking for a separator.
|
| 49 |
+
|
| 50 |
+
Attributes:
|
| 51 |
+
- consumed: total number of to be consumed bytes.
|
| 52 |
+
"""
|
| 53 |
+
def __init__(self, message, consumed):
|
| 54 |
+
super().__init__(message)
|
| 55 |
+
self.consumed = consumed
|
| 56 |
+
|
| 57 |
+
def __reduce__(self):
|
| 58 |
+
return type(self), (self.args[0], self.consumed)
|
parrot/lib/python3.10/asyncio/format_helpers.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
import inspect
|
| 3 |
+
import reprlib
|
| 4 |
+
import sys
|
| 5 |
+
import traceback
|
| 6 |
+
|
| 7 |
+
from . import constants
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _get_function_source(func):
|
| 11 |
+
func = inspect.unwrap(func)
|
| 12 |
+
if inspect.isfunction(func):
|
| 13 |
+
code = func.__code__
|
| 14 |
+
return (code.co_filename, code.co_firstlineno)
|
| 15 |
+
if isinstance(func, functools.partial):
|
| 16 |
+
return _get_function_source(func.func)
|
| 17 |
+
if isinstance(func, functools.partialmethod):
|
| 18 |
+
return _get_function_source(func.func)
|
| 19 |
+
return None
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _format_callback_source(func, args):
|
| 23 |
+
func_repr = _format_callback(func, args, None)
|
| 24 |
+
source = _get_function_source(func)
|
| 25 |
+
if source:
|
| 26 |
+
func_repr += f' at {source[0]}:{source[1]}'
|
| 27 |
+
return func_repr
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _format_args_and_kwargs(args, kwargs):
|
| 31 |
+
"""Format function arguments and keyword arguments.
|
| 32 |
+
|
| 33 |
+
Special case for a single parameter: ('hello',) is formatted as ('hello').
|
| 34 |
+
"""
|
| 35 |
+
# use reprlib to limit the length of the output
|
| 36 |
+
items = []
|
| 37 |
+
if args:
|
| 38 |
+
items.extend(reprlib.repr(arg) for arg in args)
|
| 39 |
+
if kwargs:
|
| 40 |
+
items.extend(f'{k}={reprlib.repr(v)}' for k, v in kwargs.items())
|
| 41 |
+
return '({})'.format(', '.join(items))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _format_callback(func, args, kwargs, suffix=''):
|
| 45 |
+
if isinstance(func, functools.partial):
|
| 46 |
+
suffix = _format_args_and_kwargs(args, kwargs) + suffix
|
| 47 |
+
return _format_callback(func.func, func.args, func.keywords, suffix)
|
| 48 |
+
|
| 49 |
+
if hasattr(func, '__qualname__') and func.__qualname__:
|
| 50 |
+
func_repr = func.__qualname__
|
| 51 |
+
elif hasattr(func, '__name__') and func.__name__:
|
| 52 |
+
func_repr = func.__name__
|
| 53 |
+
else:
|
| 54 |
+
func_repr = repr(func)
|
| 55 |
+
|
| 56 |
+
func_repr += _format_args_and_kwargs(args, kwargs)
|
| 57 |
+
if suffix:
|
| 58 |
+
func_repr += suffix
|
| 59 |
+
return func_repr
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def extract_stack(f=None, limit=None):
|
| 63 |
+
"""Replacement for traceback.extract_stack() that only does the
|
| 64 |
+
necessary work for asyncio debug mode.
|
| 65 |
+
"""
|
| 66 |
+
if f is None:
|
| 67 |
+
f = sys._getframe().f_back
|
| 68 |
+
if limit is None:
|
| 69 |
+
# Limit the amount of work to a reasonable amount, as extract_stack()
|
| 70 |
+
# can be called for each coroutine and future in debug mode.
|
| 71 |
+
limit = constants.DEBUG_STACK_DEPTH
|
| 72 |
+
stack = traceback.StackSummary.extract(traceback.walk_stack(f),
|
| 73 |
+
limit=limit,
|
| 74 |
+
lookup_lines=False)
|
| 75 |
+
stack.reverse()
|
| 76 |
+
return stack
|
parrot/lib/python3.10/asyncio/futures.py
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
'Future', 'wrap_future', 'isfuture',
|
| 5 |
+
)
|
| 6 |
+
|
| 7 |
+
import concurrent.futures
|
| 8 |
+
import contextvars
|
| 9 |
+
import logging
|
| 10 |
+
import sys
|
| 11 |
+
from types import GenericAlias
|
| 12 |
+
|
| 13 |
+
from . import base_futures
|
| 14 |
+
from . import events
|
| 15 |
+
from . import exceptions
|
| 16 |
+
from . import format_helpers
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
isfuture = base_futures.isfuture
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
_PENDING = base_futures._PENDING
|
| 23 |
+
_CANCELLED = base_futures._CANCELLED
|
| 24 |
+
_FINISHED = base_futures._FINISHED
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
STACK_DEBUG = logging.DEBUG - 1 # heavy-duty debugging
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Future:
|
| 31 |
+
"""This class is *almost* compatible with concurrent.futures.Future.
|
| 32 |
+
|
| 33 |
+
Differences:
|
| 34 |
+
|
| 35 |
+
- This class is not thread-safe.
|
| 36 |
+
|
| 37 |
+
- result() and exception() do not take a timeout argument and
|
| 38 |
+
raise an exception when the future isn't done yet.
|
| 39 |
+
|
| 40 |
+
- Callbacks registered with add_done_callback() are always called
|
| 41 |
+
via the event loop's call_soon().
|
| 42 |
+
|
| 43 |
+
- This class is not compatible with the wait() and as_completed()
|
| 44 |
+
methods in the concurrent.futures package.
|
| 45 |
+
|
| 46 |
+
(In Python 3.4 or later we may be able to unify the implementations.)
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
# Class variables serving as defaults for instance variables.
|
| 50 |
+
_state = _PENDING
|
| 51 |
+
_result = None
|
| 52 |
+
_exception = None
|
| 53 |
+
_loop = None
|
| 54 |
+
_source_traceback = None
|
| 55 |
+
_cancel_message = None
|
| 56 |
+
# A saved CancelledError for later chaining as an exception context.
|
| 57 |
+
_cancelled_exc = None
|
| 58 |
+
|
| 59 |
+
# This field is used for a dual purpose:
|
| 60 |
+
# - Its presence is a marker to declare that a class implements
|
| 61 |
+
# the Future protocol (i.e. is intended to be duck-type compatible).
|
| 62 |
+
# The value must also be not-None, to enable a subclass to declare
|
| 63 |
+
# that it is not compatible by setting this to None.
|
| 64 |
+
# - It is set by __iter__() below so that Task._step() can tell
|
| 65 |
+
# the difference between
|
| 66 |
+
# `await Future()` or`yield from Future()` (correct) vs.
|
| 67 |
+
# `yield Future()` (incorrect).
|
| 68 |
+
_asyncio_future_blocking = False
|
| 69 |
+
|
| 70 |
+
__log_traceback = False
|
| 71 |
+
|
| 72 |
+
def __init__(self, *, loop=None):
|
| 73 |
+
"""Initialize the future.
|
| 74 |
+
|
| 75 |
+
The optional event_loop argument allows explicitly setting the event
|
| 76 |
+
loop object used by the future. If it's not provided, the future uses
|
| 77 |
+
the default event loop.
|
| 78 |
+
"""
|
| 79 |
+
if loop is None:
|
| 80 |
+
self._loop = events._get_event_loop()
|
| 81 |
+
else:
|
| 82 |
+
self._loop = loop
|
| 83 |
+
self._callbacks = []
|
| 84 |
+
if self._loop.get_debug():
|
| 85 |
+
self._source_traceback = format_helpers.extract_stack(
|
| 86 |
+
sys._getframe(1))
|
| 87 |
+
|
| 88 |
+
_repr_info = base_futures._future_repr_info
|
| 89 |
+
|
| 90 |
+
def __repr__(self):
|
| 91 |
+
return '<{} {}>'.format(self.__class__.__name__,
|
| 92 |
+
' '.join(self._repr_info()))
|
| 93 |
+
|
| 94 |
+
def __del__(self):
|
| 95 |
+
if not self.__log_traceback:
|
| 96 |
+
# set_exception() was not called, or result() or exception()
|
| 97 |
+
# has consumed the exception
|
| 98 |
+
return
|
| 99 |
+
exc = self._exception
|
| 100 |
+
context = {
|
| 101 |
+
'message':
|
| 102 |
+
f'{self.__class__.__name__} exception was never retrieved',
|
| 103 |
+
'exception': exc,
|
| 104 |
+
'future': self,
|
| 105 |
+
}
|
| 106 |
+
if self._source_traceback:
|
| 107 |
+
context['source_traceback'] = self._source_traceback
|
| 108 |
+
self._loop.call_exception_handler(context)
|
| 109 |
+
|
| 110 |
+
__class_getitem__ = classmethod(GenericAlias)
|
| 111 |
+
|
| 112 |
+
@property
|
| 113 |
+
def _log_traceback(self):
|
| 114 |
+
return self.__log_traceback
|
| 115 |
+
|
| 116 |
+
@_log_traceback.setter
|
| 117 |
+
def _log_traceback(self, val):
|
| 118 |
+
if val:
|
| 119 |
+
raise ValueError('_log_traceback can only be set to False')
|
| 120 |
+
self.__log_traceback = False
|
| 121 |
+
|
| 122 |
+
def get_loop(self):
|
| 123 |
+
"""Return the event loop the Future is bound to."""
|
| 124 |
+
loop = self._loop
|
| 125 |
+
if loop is None:
|
| 126 |
+
raise RuntimeError("Future object is not initialized.")
|
| 127 |
+
return loop
|
| 128 |
+
|
| 129 |
+
def _make_cancelled_error(self):
|
| 130 |
+
"""Create the CancelledError to raise if the Future is cancelled.
|
| 131 |
+
|
| 132 |
+
This should only be called once when handling a cancellation since
|
| 133 |
+
it erases the saved context exception value.
|
| 134 |
+
"""
|
| 135 |
+
if self._cancel_message is None:
|
| 136 |
+
exc = exceptions.CancelledError()
|
| 137 |
+
else:
|
| 138 |
+
exc = exceptions.CancelledError(self._cancel_message)
|
| 139 |
+
exc.__context__ = self._cancelled_exc
|
| 140 |
+
# Remove the reference since we don't need this anymore.
|
| 141 |
+
self._cancelled_exc = None
|
| 142 |
+
return exc
|
| 143 |
+
|
| 144 |
+
def cancel(self, msg=None):
|
| 145 |
+
"""Cancel the future and schedule callbacks.
|
| 146 |
+
|
| 147 |
+
If the future is already done or cancelled, return False. Otherwise,
|
| 148 |
+
change the future's state to cancelled, schedule the callbacks and
|
| 149 |
+
return True.
|
| 150 |
+
"""
|
| 151 |
+
self.__log_traceback = False
|
| 152 |
+
if self._state != _PENDING:
|
| 153 |
+
return False
|
| 154 |
+
self._state = _CANCELLED
|
| 155 |
+
self._cancel_message = msg
|
| 156 |
+
self.__schedule_callbacks()
|
| 157 |
+
return True
|
| 158 |
+
|
| 159 |
+
def __schedule_callbacks(self):
|
| 160 |
+
"""Internal: Ask the event loop to call all callbacks.
|
| 161 |
+
|
| 162 |
+
The callbacks are scheduled to be called as soon as possible. Also
|
| 163 |
+
clears the callback list.
|
| 164 |
+
"""
|
| 165 |
+
callbacks = self._callbacks[:]
|
| 166 |
+
if not callbacks:
|
| 167 |
+
return
|
| 168 |
+
|
| 169 |
+
self._callbacks[:] = []
|
| 170 |
+
for callback, ctx in callbacks:
|
| 171 |
+
self._loop.call_soon(callback, self, context=ctx)
|
| 172 |
+
|
| 173 |
+
def cancelled(self):
|
| 174 |
+
"""Return True if the future was cancelled."""
|
| 175 |
+
return self._state == _CANCELLED
|
| 176 |
+
|
| 177 |
+
# Don't implement running(); see http://bugs.python.org/issue18699
|
| 178 |
+
|
| 179 |
+
def done(self):
|
| 180 |
+
"""Return True if the future is done.
|
| 181 |
+
|
| 182 |
+
Done means either that a result / exception are available, or that the
|
| 183 |
+
future was cancelled.
|
| 184 |
+
"""
|
| 185 |
+
return self._state != _PENDING
|
| 186 |
+
|
| 187 |
+
def result(self):
|
| 188 |
+
"""Return the result this future represents.
|
| 189 |
+
|
| 190 |
+
If the future has been cancelled, raises CancelledError. If the
|
| 191 |
+
future's result isn't yet available, raises InvalidStateError. If
|
| 192 |
+
the future is done and has an exception set, this exception is raised.
|
| 193 |
+
"""
|
| 194 |
+
if self._state == _CANCELLED:
|
| 195 |
+
exc = self._make_cancelled_error()
|
| 196 |
+
raise exc
|
| 197 |
+
if self._state != _FINISHED:
|
| 198 |
+
raise exceptions.InvalidStateError('Result is not ready.')
|
| 199 |
+
self.__log_traceback = False
|
| 200 |
+
if self._exception is not None:
|
| 201 |
+
raise self._exception.with_traceback(self._exception_tb)
|
| 202 |
+
return self._result
|
| 203 |
+
|
| 204 |
+
def exception(self):
|
| 205 |
+
"""Return the exception that was set on this future.
|
| 206 |
+
|
| 207 |
+
The exception (or None if no exception was set) is returned only if
|
| 208 |
+
the future is done. If the future has been cancelled, raises
|
| 209 |
+
CancelledError. If the future isn't done yet, raises
|
| 210 |
+
InvalidStateError.
|
| 211 |
+
"""
|
| 212 |
+
if self._state == _CANCELLED:
|
| 213 |
+
exc = self._make_cancelled_error()
|
| 214 |
+
raise exc
|
| 215 |
+
if self._state != _FINISHED:
|
| 216 |
+
raise exceptions.InvalidStateError('Exception is not set.')
|
| 217 |
+
self.__log_traceback = False
|
| 218 |
+
return self._exception
|
| 219 |
+
|
| 220 |
+
def add_done_callback(self, fn, *, context=None):
|
| 221 |
+
"""Add a callback to be run when the future becomes done.
|
| 222 |
+
|
| 223 |
+
The callback is called with a single argument - the future object. If
|
| 224 |
+
the future is already done when this is called, the callback is
|
| 225 |
+
scheduled with call_soon.
|
| 226 |
+
"""
|
| 227 |
+
if self._state != _PENDING:
|
| 228 |
+
self._loop.call_soon(fn, self, context=context)
|
| 229 |
+
else:
|
| 230 |
+
if context is None:
|
| 231 |
+
context = contextvars.copy_context()
|
| 232 |
+
self._callbacks.append((fn, context))
|
| 233 |
+
|
| 234 |
+
# New method not in PEP 3148.
|
| 235 |
+
|
| 236 |
+
def remove_done_callback(self, fn):
|
| 237 |
+
"""Remove all instances of a callback from the "call when done" list.
|
| 238 |
+
|
| 239 |
+
Returns the number of callbacks removed.
|
| 240 |
+
"""
|
| 241 |
+
filtered_callbacks = [(f, ctx)
|
| 242 |
+
for (f, ctx) in self._callbacks
|
| 243 |
+
if f != fn]
|
| 244 |
+
removed_count = len(self._callbacks) - len(filtered_callbacks)
|
| 245 |
+
if removed_count:
|
| 246 |
+
self._callbacks[:] = filtered_callbacks
|
| 247 |
+
return removed_count
|
| 248 |
+
|
| 249 |
+
# So-called internal methods (note: no set_running_or_notify_cancel()).
|
| 250 |
+
|
| 251 |
+
def set_result(self, result):
|
| 252 |
+
"""Mark the future done and set its result.
|
| 253 |
+
|
| 254 |
+
If the future is already done when this method is called, raises
|
| 255 |
+
InvalidStateError.
|
| 256 |
+
"""
|
| 257 |
+
if self._state != _PENDING:
|
| 258 |
+
raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
|
| 259 |
+
self._result = result
|
| 260 |
+
self._state = _FINISHED
|
| 261 |
+
self.__schedule_callbacks()
|
| 262 |
+
|
| 263 |
+
def set_exception(self, exception):
|
| 264 |
+
"""Mark the future done and set an exception.
|
| 265 |
+
|
| 266 |
+
If the future is already done when this method is called, raises
|
| 267 |
+
InvalidStateError.
|
| 268 |
+
"""
|
| 269 |
+
if self._state != _PENDING:
|
| 270 |
+
raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
|
| 271 |
+
if isinstance(exception, type):
|
| 272 |
+
exception = exception()
|
| 273 |
+
if type(exception) is StopIteration:
|
| 274 |
+
raise TypeError("StopIteration interacts badly with generators "
|
| 275 |
+
"and cannot be raised into a Future")
|
| 276 |
+
self._exception = exception
|
| 277 |
+
self._exception_tb = exception.__traceback__
|
| 278 |
+
self._state = _FINISHED
|
| 279 |
+
self.__schedule_callbacks()
|
| 280 |
+
self.__log_traceback = True
|
| 281 |
+
|
| 282 |
+
def __await__(self):
|
| 283 |
+
if not self.done():
|
| 284 |
+
self._asyncio_future_blocking = True
|
| 285 |
+
yield self # This tells Task to wait for completion.
|
| 286 |
+
if not self.done():
|
| 287 |
+
raise RuntimeError("await wasn't used with future")
|
| 288 |
+
return self.result() # May raise too.
|
| 289 |
+
|
| 290 |
+
__iter__ = __await__ # make compatible with 'yield from'.
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
# Needed for testing purposes.
|
| 294 |
+
_PyFuture = Future
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def _get_loop(fut):
|
| 298 |
+
# Tries to call Future.get_loop() if it's available.
|
| 299 |
+
# Otherwise fallbacks to using the old '_loop' property.
|
| 300 |
+
try:
|
| 301 |
+
get_loop = fut.get_loop
|
| 302 |
+
except AttributeError:
|
| 303 |
+
pass
|
| 304 |
+
else:
|
| 305 |
+
return get_loop()
|
| 306 |
+
return fut._loop
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def _set_result_unless_cancelled(fut, result):
|
| 310 |
+
"""Helper setting the result only if the future was not cancelled."""
|
| 311 |
+
if fut.cancelled():
|
| 312 |
+
return
|
| 313 |
+
fut.set_result(result)
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def _convert_future_exc(exc):
|
| 317 |
+
exc_class = type(exc)
|
| 318 |
+
if exc_class is concurrent.futures.CancelledError:
|
| 319 |
+
return exceptions.CancelledError(*exc.args)
|
| 320 |
+
elif exc_class is concurrent.futures.TimeoutError:
|
| 321 |
+
return exceptions.TimeoutError(*exc.args)
|
| 322 |
+
elif exc_class is concurrent.futures.InvalidStateError:
|
| 323 |
+
return exceptions.InvalidStateError(*exc.args)
|
| 324 |
+
else:
|
| 325 |
+
return exc
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def _set_concurrent_future_state(concurrent, source):
|
| 329 |
+
"""Copy state from a future to a concurrent.futures.Future."""
|
| 330 |
+
assert source.done()
|
| 331 |
+
if source.cancelled():
|
| 332 |
+
concurrent.cancel()
|
| 333 |
+
if not concurrent.set_running_or_notify_cancel():
|
| 334 |
+
return
|
| 335 |
+
exception = source.exception()
|
| 336 |
+
if exception is not None:
|
| 337 |
+
concurrent.set_exception(_convert_future_exc(exception))
|
| 338 |
+
else:
|
| 339 |
+
result = source.result()
|
| 340 |
+
concurrent.set_result(result)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def _copy_future_state(source, dest):
|
| 344 |
+
"""Internal helper to copy state from another Future.
|
| 345 |
+
|
| 346 |
+
The other Future may be a concurrent.futures.Future.
|
| 347 |
+
"""
|
| 348 |
+
assert source.done()
|
| 349 |
+
if dest.cancelled():
|
| 350 |
+
return
|
| 351 |
+
assert not dest.done()
|
| 352 |
+
if source.cancelled():
|
| 353 |
+
dest.cancel()
|
| 354 |
+
else:
|
| 355 |
+
exception = source.exception()
|
| 356 |
+
if exception is not None:
|
| 357 |
+
dest.set_exception(_convert_future_exc(exception))
|
| 358 |
+
else:
|
| 359 |
+
result = source.result()
|
| 360 |
+
dest.set_result(result)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def _chain_future(source, destination):
|
| 364 |
+
"""Chain two futures so that when one completes, so does the other.
|
| 365 |
+
|
| 366 |
+
The result (or exception) of source will be copied to destination.
|
| 367 |
+
If destination is cancelled, source gets cancelled too.
|
| 368 |
+
Compatible with both asyncio.Future and concurrent.futures.Future.
|
| 369 |
+
"""
|
| 370 |
+
if not isfuture(source) and not isinstance(source,
|
| 371 |
+
concurrent.futures.Future):
|
| 372 |
+
raise TypeError('A future is required for source argument')
|
| 373 |
+
if not isfuture(destination) and not isinstance(destination,
|
| 374 |
+
concurrent.futures.Future):
|
| 375 |
+
raise TypeError('A future is required for destination argument')
|
| 376 |
+
source_loop = _get_loop(source) if isfuture(source) else None
|
| 377 |
+
dest_loop = _get_loop(destination) if isfuture(destination) else None
|
| 378 |
+
|
| 379 |
+
def _set_state(future, other):
|
| 380 |
+
if isfuture(future):
|
| 381 |
+
_copy_future_state(other, future)
|
| 382 |
+
else:
|
| 383 |
+
_set_concurrent_future_state(future, other)
|
| 384 |
+
|
| 385 |
+
def _call_check_cancel(destination):
|
| 386 |
+
if destination.cancelled():
|
| 387 |
+
if source_loop is None or source_loop is dest_loop:
|
| 388 |
+
source.cancel()
|
| 389 |
+
else:
|
| 390 |
+
source_loop.call_soon_threadsafe(source.cancel)
|
| 391 |
+
|
| 392 |
+
def _call_set_state(source):
|
| 393 |
+
if (destination.cancelled() and
|
| 394 |
+
dest_loop is not None and dest_loop.is_closed()):
|
| 395 |
+
return
|
| 396 |
+
if dest_loop is None or dest_loop is source_loop:
|
| 397 |
+
_set_state(destination, source)
|
| 398 |
+
else:
|
| 399 |
+
if dest_loop.is_closed():
|
| 400 |
+
return
|
| 401 |
+
dest_loop.call_soon_threadsafe(_set_state, destination, source)
|
| 402 |
+
|
| 403 |
+
destination.add_done_callback(_call_check_cancel)
|
| 404 |
+
source.add_done_callback(_call_set_state)
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def wrap_future(future, *, loop=None):
|
| 408 |
+
"""Wrap concurrent.futures.Future object."""
|
| 409 |
+
if isfuture(future):
|
| 410 |
+
return future
|
| 411 |
+
assert isinstance(future, concurrent.futures.Future), \
|
| 412 |
+
f'concurrent.futures.Future is expected, got {future!r}'
|
| 413 |
+
if loop is None:
|
| 414 |
+
loop = events._get_event_loop()
|
| 415 |
+
new_future = loop.create_future()
|
| 416 |
+
_chain_future(future, new_future)
|
| 417 |
+
return new_future
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
try:
|
| 421 |
+
import _asyncio
|
| 422 |
+
except ImportError:
|
| 423 |
+
pass
|
| 424 |
+
else:
|
| 425 |
+
# _CFuture is needed for tests.
|
| 426 |
+
Future = _CFuture = _asyncio.Future
|
parrot/lib/python3.10/asyncio/locks.py
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 1 |
+
"""Synchronization primitives."""
|
| 2 |
+
|
| 3 |
+
__all__ = ('Lock', 'Event', 'Condition', 'Semaphore', 'BoundedSemaphore')
|
| 4 |
+
|
| 5 |
+
import collections
|
| 6 |
+
|
| 7 |
+
from . import exceptions
|
| 8 |
+
from . import mixins
|
| 9 |
+
from . import tasks
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class _ContextManagerMixin:
|
| 13 |
+
async def __aenter__(self):
|
| 14 |
+
await self.acquire()
|
| 15 |
+
# We have no use for the "as ..." clause in the with
|
| 16 |
+
# statement for locks.
|
| 17 |
+
return None
|
| 18 |
+
|
| 19 |
+
async def __aexit__(self, exc_type, exc, tb):
|
| 20 |
+
self.release()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Lock(_ContextManagerMixin, mixins._LoopBoundMixin):
|
| 24 |
+
"""Primitive lock objects.
|
| 25 |
+
|
| 26 |
+
A primitive lock is a synchronization primitive that is not owned
|
| 27 |
+
by a particular coroutine when locked. A primitive lock is in one
|
| 28 |
+
of two states, 'locked' or 'unlocked'.
|
| 29 |
+
|
| 30 |
+
It is created in the unlocked state. It has two basic methods,
|
| 31 |
+
acquire() and release(). When the state is unlocked, acquire()
|
| 32 |
+
changes the state to locked and returns immediately. When the
|
| 33 |
+
state is locked, acquire() blocks until a call to release() in
|
| 34 |
+
another coroutine changes it to unlocked, then the acquire() call
|
| 35 |
+
resets it to locked and returns. The release() method should only
|
| 36 |
+
be called in the locked state; it changes the state to unlocked
|
| 37 |
+
and returns immediately. If an attempt is made to release an
|
| 38 |
+
unlocked lock, a RuntimeError will be raised.
|
| 39 |
+
|
| 40 |
+
When more than one coroutine is blocked in acquire() waiting for
|
| 41 |
+
the state to turn to unlocked, only one coroutine proceeds when a
|
| 42 |
+
release() call resets the state to unlocked; first coroutine which
|
| 43 |
+
is blocked in acquire() is being processed.
|
| 44 |
+
|
| 45 |
+
acquire() is a coroutine and should be called with 'await'.
|
| 46 |
+
|
| 47 |
+
Locks also support the asynchronous context management protocol.
|
| 48 |
+
'async with lock' statement should be used.
|
| 49 |
+
|
| 50 |
+
Usage:
|
| 51 |
+
|
| 52 |
+
lock = Lock()
|
| 53 |
+
...
|
| 54 |
+
await lock.acquire()
|
| 55 |
+
try:
|
| 56 |
+
...
|
| 57 |
+
finally:
|
| 58 |
+
lock.release()
|
| 59 |
+
|
| 60 |
+
Context manager usage:
|
| 61 |
+
|
| 62 |
+
lock = Lock()
|
| 63 |
+
...
|
| 64 |
+
async with lock:
|
| 65 |
+
...
|
| 66 |
+
|
| 67 |
+
Lock objects can be tested for locking state:
|
| 68 |
+
|
| 69 |
+
if not lock.locked():
|
| 70 |
+
await lock.acquire()
|
| 71 |
+
else:
|
| 72 |
+
# lock is acquired
|
| 73 |
+
...
|
| 74 |
+
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
def __init__(self, *, loop=mixins._marker):
|
| 78 |
+
super().__init__(loop=loop)
|
| 79 |
+
self._waiters = None
|
| 80 |
+
self._locked = False
|
| 81 |
+
|
| 82 |
+
def __repr__(self):
|
| 83 |
+
res = super().__repr__()
|
| 84 |
+
extra = 'locked' if self._locked else 'unlocked'
|
| 85 |
+
if self._waiters:
|
| 86 |
+
extra = f'{extra}, waiters:{len(self._waiters)}'
|
| 87 |
+
return f'<{res[1:-1]} [{extra}]>'
|
| 88 |
+
|
| 89 |
+
def locked(self):
|
| 90 |
+
"""Return True if lock is acquired."""
|
| 91 |
+
return self._locked
|
| 92 |
+
|
| 93 |
+
async def acquire(self):
|
| 94 |
+
"""Acquire a lock.
|
| 95 |
+
|
| 96 |
+
This method blocks until the lock is unlocked, then sets it to
|
| 97 |
+
locked and returns True.
|
| 98 |
+
"""
|
| 99 |
+
if (not self._locked and (self._waiters is None or
|
| 100 |
+
all(w.cancelled() for w in self._waiters))):
|
| 101 |
+
self._locked = True
|
| 102 |
+
return True
|
| 103 |
+
|
| 104 |
+
if self._waiters is None:
|
| 105 |
+
self._waiters = collections.deque()
|
| 106 |
+
fut = self._get_loop().create_future()
|
| 107 |
+
self._waiters.append(fut)
|
| 108 |
+
|
| 109 |
+
# Finally block should be called before the CancelledError
|
| 110 |
+
# handling as we don't want CancelledError to call
|
| 111 |
+
# _wake_up_first() and attempt to wake up itself.
|
| 112 |
+
try:
|
| 113 |
+
try:
|
| 114 |
+
await fut
|
| 115 |
+
finally:
|
| 116 |
+
self._waiters.remove(fut)
|
| 117 |
+
except exceptions.CancelledError:
|
| 118 |
+
if not self._locked:
|
| 119 |
+
self._wake_up_first()
|
| 120 |
+
raise
|
| 121 |
+
|
| 122 |
+
self._locked = True
|
| 123 |
+
return True
|
| 124 |
+
|
| 125 |
+
def release(self):
|
| 126 |
+
"""Release a lock.
|
| 127 |
+
|
| 128 |
+
When the lock is locked, reset it to unlocked, and return.
|
| 129 |
+
If any other coroutines are blocked waiting for the lock to become
|
| 130 |
+
unlocked, allow exactly one of them to proceed.
|
| 131 |
+
|
| 132 |
+
When invoked on an unlocked lock, a RuntimeError is raised.
|
| 133 |
+
|
| 134 |
+
There is no return value.
|
| 135 |
+
"""
|
| 136 |
+
if self._locked:
|
| 137 |
+
self._locked = False
|
| 138 |
+
self._wake_up_first()
|
| 139 |
+
else:
|
| 140 |
+
raise RuntimeError('Lock is not acquired.')
|
| 141 |
+
|
| 142 |
+
def _wake_up_first(self):
|
| 143 |
+
"""Wake up the first waiter if it isn't done."""
|
| 144 |
+
if not self._waiters:
|
| 145 |
+
return
|
| 146 |
+
try:
|
| 147 |
+
fut = next(iter(self._waiters))
|
| 148 |
+
except StopIteration:
|
| 149 |
+
return
|
| 150 |
+
|
| 151 |
+
# .done() necessarily means that a waiter will wake up later on and
|
| 152 |
+
# either take the lock, or, if it was cancelled and lock wasn't
|
| 153 |
+
# taken already, will hit this again and wake up a new waiter.
|
| 154 |
+
if not fut.done():
|
| 155 |
+
fut.set_result(True)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class Event(mixins._LoopBoundMixin):
|
| 159 |
+
"""Asynchronous equivalent to threading.Event.
|
| 160 |
+
|
| 161 |
+
Class implementing event objects. An event manages a flag that can be set
|
| 162 |
+
to true with the set() method and reset to false with the clear() method.
|
| 163 |
+
The wait() method blocks until the flag is true. The flag is initially
|
| 164 |
+
false.
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
def __init__(self, *, loop=mixins._marker):
|
| 168 |
+
super().__init__(loop=loop)
|
| 169 |
+
self._waiters = collections.deque()
|
| 170 |
+
self._value = False
|
| 171 |
+
|
| 172 |
+
def __repr__(self):
|
| 173 |
+
res = super().__repr__()
|
| 174 |
+
extra = 'set' if self._value else 'unset'
|
| 175 |
+
if self._waiters:
|
| 176 |
+
extra = f'{extra}, waiters:{len(self._waiters)}'
|
| 177 |
+
return f'<{res[1:-1]} [{extra}]>'
|
| 178 |
+
|
| 179 |
+
def is_set(self):
|
| 180 |
+
"""Return True if and only if the internal flag is true."""
|
| 181 |
+
return self._value
|
| 182 |
+
|
| 183 |
+
def set(self):
|
| 184 |
+
"""Set the internal flag to true. All coroutines waiting for it to
|
| 185 |
+
become true are awakened. Coroutine that call wait() once the flag is
|
| 186 |
+
true will not block at all.
|
| 187 |
+
"""
|
| 188 |
+
if not self._value:
|
| 189 |
+
self._value = True
|
| 190 |
+
|
| 191 |
+
for fut in self._waiters:
|
| 192 |
+
if not fut.done():
|
| 193 |
+
fut.set_result(True)
|
| 194 |
+
|
| 195 |
+
def clear(self):
|
| 196 |
+
"""Reset the internal flag to false. Subsequently, coroutines calling
|
| 197 |
+
wait() will block until set() is called to set the internal flag
|
| 198 |
+
to true again."""
|
| 199 |
+
self._value = False
|
| 200 |
+
|
| 201 |
+
async def wait(self):
|
| 202 |
+
"""Block until the internal flag is true.
|
| 203 |
+
|
| 204 |
+
If the internal flag is true on entry, return True
|
| 205 |
+
immediately. Otherwise, block until another coroutine calls
|
| 206 |
+
set() to set the flag to true, then return True.
|
| 207 |
+
"""
|
| 208 |
+
if self._value:
|
| 209 |
+
return True
|
| 210 |
+
|
| 211 |
+
fut = self._get_loop().create_future()
|
| 212 |
+
self._waiters.append(fut)
|
| 213 |
+
try:
|
| 214 |
+
await fut
|
| 215 |
+
return True
|
| 216 |
+
finally:
|
| 217 |
+
self._waiters.remove(fut)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class Condition(_ContextManagerMixin, mixins._LoopBoundMixin):
|
| 221 |
+
"""Asynchronous equivalent to threading.Condition.
|
| 222 |
+
|
| 223 |
+
This class implements condition variable objects. A condition variable
|
| 224 |
+
allows one or more coroutines to wait until they are notified by another
|
| 225 |
+
coroutine.
|
| 226 |
+
|
| 227 |
+
A new Lock object is created and used as the underlying lock.
|
| 228 |
+
"""
|
| 229 |
+
|
| 230 |
+
def __init__(self, lock=None, *, loop=mixins._marker):
|
| 231 |
+
super().__init__(loop=loop)
|
| 232 |
+
if lock is None:
|
| 233 |
+
lock = Lock()
|
| 234 |
+
|
| 235 |
+
self._lock = lock
|
| 236 |
+
# Export the lock's locked(), acquire() and release() methods.
|
| 237 |
+
self.locked = lock.locked
|
| 238 |
+
self.acquire = lock.acquire
|
| 239 |
+
self.release = lock.release
|
| 240 |
+
|
| 241 |
+
self._waiters = collections.deque()
|
| 242 |
+
|
| 243 |
+
def __repr__(self):
|
| 244 |
+
res = super().__repr__()
|
| 245 |
+
extra = 'locked' if self.locked() else 'unlocked'
|
| 246 |
+
if self._waiters:
|
| 247 |
+
extra = f'{extra}, waiters:{len(self._waiters)}'
|
| 248 |
+
return f'<{res[1:-1]} [{extra}]>'
|
| 249 |
+
|
| 250 |
+
async def wait(self):
|
| 251 |
+
"""Wait until notified.
|
| 252 |
+
|
| 253 |
+
If the calling coroutine has not acquired the lock when this
|
| 254 |
+
method is called, a RuntimeError is raised.
|
| 255 |
+
|
| 256 |
+
This method releases the underlying lock, and then blocks
|
| 257 |
+
until it is awakened by a notify() or notify_all() call for
|
| 258 |
+
the same condition variable in another coroutine. Once
|
| 259 |
+
awakened, it re-acquires the lock and returns True.
|
| 260 |
+
"""
|
| 261 |
+
if not self.locked():
|
| 262 |
+
raise RuntimeError('cannot wait on un-acquired lock')
|
| 263 |
+
|
| 264 |
+
self.release()
|
| 265 |
+
try:
|
| 266 |
+
fut = self._get_loop().create_future()
|
| 267 |
+
self._waiters.append(fut)
|
| 268 |
+
try:
|
| 269 |
+
await fut
|
| 270 |
+
return True
|
| 271 |
+
finally:
|
| 272 |
+
self._waiters.remove(fut)
|
| 273 |
+
|
| 274 |
+
finally:
|
| 275 |
+
# Must reacquire lock even if wait is cancelled
|
| 276 |
+
cancelled = False
|
| 277 |
+
while True:
|
| 278 |
+
try:
|
| 279 |
+
await self.acquire()
|
| 280 |
+
break
|
| 281 |
+
except exceptions.CancelledError:
|
| 282 |
+
cancelled = True
|
| 283 |
+
|
| 284 |
+
if cancelled:
|
| 285 |
+
raise exceptions.CancelledError
|
| 286 |
+
|
| 287 |
+
async def wait_for(self, predicate):
|
| 288 |
+
"""Wait until a predicate becomes true.
|
| 289 |
+
|
| 290 |
+
The predicate should be a callable which result will be
|
| 291 |
+
interpreted as a boolean value. The final predicate value is
|
| 292 |
+
the return value.
|
| 293 |
+
"""
|
| 294 |
+
result = predicate()
|
| 295 |
+
while not result:
|
| 296 |
+
await self.wait()
|
| 297 |
+
result = predicate()
|
| 298 |
+
return result
|
| 299 |
+
|
| 300 |
+
def notify(self, n=1):
|
| 301 |
+
"""By default, wake up one coroutine waiting on this condition, if any.
|
| 302 |
+
If the calling coroutine has not acquired the lock when this method
|
| 303 |
+
is called, a RuntimeError is raised.
|
| 304 |
+
|
| 305 |
+
This method wakes up at most n of the coroutines waiting for the
|
| 306 |
+
condition variable; it is a no-op if no coroutines are waiting.
|
| 307 |
+
|
| 308 |
+
Note: an awakened coroutine does not actually return from its
|
| 309 |
+
wait() call until it can reacquire the lock. Since notify() does
|
| 310 |
+
not release the lock, its caller should.
|
| 311 |
+
"""
|
| 312 |
+
if not self.locked():
|
| 313 |
+
raise RuntimeError('cannot notify on un-acquired lock')
|
| 314 |
+
|
| 315 |
+
idx = 0
|
| 316 |
+
for fut in self._waiters:
|
| 317 |
+
if idx >= n:
|
| 318 |
+
break
|
| 319 |
+
|
| 320 |
+
if not fut.done():
|
| 321 |
+
idx += 1
|
| 322 |
+
fut.set_result(False)
|
| 323 |
+
|
| 324 |
+
def notify_all(self):
|
| 325 |
+
"""Wake up all threads waiting on this condition. This method acts
|
| 326 |
+
like notify(), but wakes up all waiting threads instead of one. If the
|
| 327 |
+
calling thread has not acquired the lock when this method is called,
|
| 328 |
+
a RuntimeError is raised.
|
| 329 |
+
"""
|
| 330 |
+
self.notify(len(self._waiters))
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
class Semaphore(_ContextManagerMixin, mixins._LoopBoundMixin):
|
| 334 |
+
"""A Semaphore implementation.
|
| 335 |
+
|
| 336 |
+
A semaphore manages an internal counter which is decremented by each
|
| 337 |
+
acquire() call and incremented by each release() call. The counter
|
| 338 |
+
can never go below zero; when acquire() finds that it is zero, it blocks,
|
| 339 |
+
waiting until some other thread calls release().
|
| 340 |
+
|
| 341 |
+
Semaphores also support the context management protocol.
|
| 342 |
+
|
| 343 |
+
The optional argument gives the initial value for the internal
|
| 344 |
+
counter; it defaults to 1. If the value given is less than 0,
|
| 345 |
+
ValueError is raised.
|
| 346 |
+
"""
|
| 347 |
+
|
| 348 |
+
def __init__(self, value=1, *, loop=mixins._marker):
|
| 349 |
+
super().__init__(loop=loop)
|
| 350 |
+
if value < 0:
|
| 351 |
+
raise ValueError("Semaphore initial value must be >= 0")
|
| 352 |
+
self._waiters = None
|
| 353 |
+
self._value = value
|
| 354 |
+
|
| 355 |
+
def __repr__(self):
|
| 356 |
+
res = super().__repr__()
|
| 357 |
+
extra = 'locked' if self.locked() else f'unlocked, value:{self._value}'
|
| 358 |
+
if self._waiters:
|
| 359 |
+
extra = f'{extra}, waiters:{len(self._waiters)}'
|
| 360 |
+
return f'<{res[1:-1]} [{extra}]>'
|
| 361 |
+
|
| 362 |
+
def locked(self):
|
| 363 |
+
"""Returns True if semaphore cannot be acquired immediately."""
|
| 364 |
+
return self._value == 0 or (
|
| 365 |
+
any(not w.cancelled() for w in (self._waiters or ())))
|
| 366 |
+
|
| 367 |
+
async def acquire(self):
|
| 368 |
+
"""Acquire a semaphore.
|
| 369 |
+
|
| 370 |
+
If the internal counter is larger than zero on entry,
|
| 371 |
+
decrement it by one and return True immediately. If it is
|
| 372 |
+
zero on entry, block, waiting until some other coroutine has
|
| 373 |
+
called release() to make it larger than 0, and then return
|
| 374 |
+
True.
|
| 375 |
+
"""
|
| 376 |
+
if not self.locked():
|
| 377 |
+
self._value -= 1
|
| 378 |
+
return True
|
| 379 |
+
|
| 380 |
+
if self._waiters is None:
|
| 381 |
+
self._waiters = collections.deque()
|
| 382 |
+
fut = self._get_loop().create_future()
|
| 383 |
+
self._waiters.append(fut)
|
| 384 |
+
|
| 385 |
+
# Finally block should be called before the CancelledError
|
| 386 |
+
# handling as we don't want CancelledError to call
|
| 387 |
+
# _wake_up_first() and attempt to wake up itself.
|
| 388 |
+
try:
|
| 389 |
+
try:
|
| 390 |
+
await fut
|
| 391 |
+
finally:
|
| 392 |
+
self._waiters.remove(fut)
|
| 393 |
+
except exceptions.CancelledError:
|
| 394 |
+
if not fut.cancelled():
|
| 395 |
+
self._value += 1
|
| 396 |
+
self._wake_up_next()
|
| 397 |
+
raise
|
| 398 |
+
|
| 399 |
+
if self._value > 0:
|
| 400 |
+
self._wake_up_next()
|
| 401 |
+
return True
|
| 402 |
+
|
| 403 |
+
def release(self):
|
| 404 |
+
"""Release a semaphore, incrementing the internal counter by one.
|
| 405 |
+
|
| 406 |
+
When it was zero on entry and another coroutine is waiting for it to
|
| 407 |
+
become larger than zero again, wake up that coroutine.
|
| 408 |
+
"""
|
| 409 |
+
self._value += 1
|
| 410 |
+
self._wake_up_next()
|
| 411 |
+
|
| 412 |
+
def _wake_up_next(self):
|
| 413 |
+
"""Wake up the first waiter that isn't done."""
|
| 414 |
+
if not self._waiters:
|
| 415 |
+
return
|
| 416 |
+
|
| 417 |
+
for fut in self._waiters:
|
| 418 |
+
if not fut.done():
|
| 419 |
+
self._value -= 1
|
| 420 |
+
fut.set_result(True)
|
| 421 |
+
return
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
class BoundedSemaphore(Semaphore):
|
| 425 |
+
"""A bounded semaphore implementation.
|
| 426 |
+
|
| 427 |
+
This raises ValueError in release() if it would increase the value
|
| 428 |
+
above the initial value.
|
| 429 |
+
"""
|
| 430 |
+
|
| 431 |
+
def __init__(self, value=1, *, loop=mixins._marker):
|
| 432 |
+
self._bound_value = value
|
| 433 |
+
super().__init__(value, loop=loop)
|
| 434 |
+
|
| 435 |
+
def release(self):
|
| 436 |
+
if self._value >= self._bound_value:
|
| 437 |
+
raise ValueError('BoundedSemaphore released too many times')
|
| 438 |
+
super().release()
|
parrot/lib/python3.10/asyncio/mixins.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Event loop mixins."""
|
| 2 |
+
|
| 3 |
+
import threading
|
| 4 |
+
from . import events
|
| 5 |
+
|
| 6 |
+
_global_lock = threading.Lock()
|
| 7 |
+
|
| 8 |
+
# Used as a sentinel for loop parameter
|
| 9 |
+
_marker = object()
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class _LoopBoundMixin:
|
| 13 |
+
_loop = None
|
| 14 |
+
|
| 15 |
+
def __init__(self, *, loop=_marker):
|
| 16 |
+
if loop is not _marker:
|
| 17 |
+
raise TypeError(
|
| 18 |
+
f'As of 3.10, the *loop* parameter was removed from '
|
| 19 |
+
f'{type(self).__name__}() since it is no longer necessary'
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
def _get_loop(self):
|
| 23 |
+
loop = events._get_running_loop()
|
| 24 |
+
|
| 25 |
+
if self._loop is None:
|
| 26 |
+
with _global_lock:
|
| 27 |
+
if self._loop is None:
|
| 28 |
+
self._loop = loop
|
| 29 |
+
if loop is not self._loop:
|
| 30 |
+
raise RuntimeError(f'{self!r} is bound to a different event loop')
|
| 31 |
+
return loop
|
parrot/lib/python3.10/asyncio/protocols.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Abstract Protocol base classes."""
|
| 2 |
+
|
| 3 |
+
__all__ = (
|
| 4 |
+
'BaseProtocol', 'Protocol', 'DatagramProtocol',
|
| 5 |
+
'SubprocessProtocol', 'BufferedProtocol',
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class BaseProtocol:
|
| 10 |
+
"""Common base class for protocol interfaces.
|
| 11 |
+
|
| 12 |
+
Usually user implements protocols that derived from BaseProtocol
|
| 13 |
+
like Protocol or ProcessProtocol.
|
| 14 |
+
|
| 15 |
+
The only case when BaseProtocol should be implemented directly is
|
| 16 |
+
write-only transport like write pipe
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
__slots__ = ()
|
| 20 |
+
|
| 21 |
+
def connection_made(self, transport):
|
| 22 |
+
"""Called when a connection is made.
|
| 23 |
+
|
| 24 |
+
The argument is the transport representing the pipe connection.
|
| 25 |
+
To receive data, wait for data_received() calls.
|
| 26 |
+
When the connection is closed, connection_lost() is called.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def connection_lost(self, exc):
|
| 30 |
+
"""Called when the connection is lost or closed.
|
| 31 |
+
|
| 32 |
+
The argument is an exception object or None (the latter
|
| 33 |
+
meaning a regular EOF is received or the connection was
|
| 34 |
+
aborted or closed).
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def pause_writing(self):
|
| 38 |
+
"""Called when the transport's buffer goes over the high-water mark.
|
| 39 |
+
|
| 40 |
+
Pause and resume calls are paired -- pause_writing() is called
|
| 41 |
+
once when the buffer goes strictly over the high-water mark
|
| 42 |
+
(even if subsequent writes increases the buffer size even
|
| 43 |
+
more), and eventually resume_writing() is called once when the
|
| 44 |
+
buffer size reaches the low-water mark.
|
| 45 |
+
|
| 46 |
+
Note that if the buffer size equals the high-water mark,
|
| 47 |
+
pause_writing() is not called -- it must go strictly over.
|
| 48 |
+
Conversely, resume_writing() is called when the buffer size is
|
| 49 |
+
equal or lower than the low-water mark. These end conditions
|
| 50 |
+
are important to ensure that things go as expected when either
|
| 51 |
+
mark is zero.
|
| 52 |
+
|
| 53 |
+
NOTE: This is the only Protocol callback that is not called
|
| 54 |
+
through EventLoop.call_soon() -- if it were, it would have no
|
| 55 |
+
effect when it's most needed (when the app keeps writing
|
| 56 |
+
without yielding until pause_writing() is called).
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def resume_writing(self):
|
| 60 |
+
"""Called when the transport's buffer drains below the low-water mark.
|
| 61 |
+
|
| 62 |
+
See pause_writing() for details.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class Protocol(BaseProtocol):
|
| 67 |
+
"""Interface for stream protocol.
|
| 68 |
+
|
| 69 |
+
The user should implement this interface. They can inherit from
|
| 70 |
+
this class but don't need to. The implementations here do
|
| 71 |
+
nothing (they don't raise exceptions).
|
| 72 |
+
|
| 73 |
+
When the user wants to requests a transport, they pass a protocol
|
| 74 |
+
factory to a utility function (e.g., EventLoop.create_connection()).
|
| 75 |
+
|
| 76 |
+
When the connection is made successfully, connection_made() is
|
| 77 |
+
called with a suitable transport object. Then data_received()
|
| 78 |
+
will be called 0 or more times with data (bytes) received from the
|
| 79 |
+
transport; finally, connection_lost() will be called exactly once
|
| 80 |
+
with either an exception object or None as an argument.
|
| 81 |
+
|
| 82 |
+
State machine of calls:
|
| 83 |
+
|
| 84 |
+
start -> CM [-> DR*] [-> ER?] -> CL -> end
|
| 85 |
+
|
| 86 |
+
* CM: connection_made()
|
| 87 |
+
* DR: data_received()
|
| 88 |
+
* ER: eof_received()
|
| 89 |
+
* CL: connection_lost()
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
__slots__ = ()
|
| 93 |
+
|
| 94 |
+
def data_received(self, data):
|
| 95 |
+
"""Called when some data is received.
|
| 96 |
+
|
| 97 |
+
The argument is a bytes object.
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
def eof_received(self):
|
| 101 |
+
"""Called when the other end calls write_eof() or equivalent.
|
| 102 |
+
|
| 103 |
+
If this returns a false value (including None), the transport
|
| 104 |
+
will close itself. If it returns a true value, closing the
|
| 105 |
+
transport is up to the protocol.
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class BufferedProtocol(BaseProtocol):
|
| 110 |
+
"""Interface for stream protocol with manual buffer control.
|
| 111 |
+
|
| 112 |
+
Event methods, such as `create_server` and `create_connection`,
|
| 113 |
+
accept factories that return protocols that implement this interface.
|
| 114 |
+
|
| 115 |
+
The idea of BufferedProtocol is that it allows to manually allocate
|
| 116 |
+
and control the receive buffer. Event loops can then use the buffer
|
| 117 |
+
provided by the protocol to avoid unnecessary data copies. This
|
| 118 |
+
can result in noticeable performance improvement for protocols that
|
| 119 |
+
receive big amounts of data. Sophisticated protocols can allocate
|
| 120 |
+
the buffer only once at creation time.
|
| 121 |
+
|
| 122 |
+
State machine of calls:
|
| 123 |
+
|
| 124 |
+
start -> CM [-> GB [-> BU?]]* [-> ER?] -> CL -> end
|
| 125 |
+
|
| 126 |
+
* CM: connection_made()
|
| 127 |
+
* GB: get_buffer()
|
| 128 |
+
* BU: buffer_updated()
|
| 129 |
+
* ER: eof_received()
|
| 130 |
+
* CL: connection_lost()
|
| 131 |
+
"""
|
| 132 |
+
|
| 133 |
+
__slots__ = ()
|
| 134 |
+
|
| 135 |
+
def get_buffer(self, sizehint):
|
| 136 |
+
"""Called to allocate a new receive buffer.
|
| 137 |
+
|
| 138 |
+
*sizehint* is a recommended minimal size for the returned
|
| 139 |
+
buffer. When set to -1, the buffer size can be arbitrary.
|
| 140 |
+
|
| 141 |
+
Must return an object that implements the
|
| 142 |
+
:ref:`buffer protocol <bufferobjects>`.
|
| 143 |
+
It is an error to return a zero-sized buffer.
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
def buffer_updated(self, nbytes):
|
| 147 |
+
"""Called when the buffer was updated with the received data.
|
| 148 |
+
|
| 149 |
+
*nbytes* is the total number of bytes that were written to
|
| 150 |
+
the buffer.
|
| 151 |
+
"""
|
| 152 |
+
|
| 153 |
+
def eof_received(self):
|
| 154 |
+
"""Called when the other end calls write_eof() or equivalent.
|
| 155 |
+
|
| 156 |
+
If this returns a false value (including None), the transport
|
| 157 |
+
will close itself. If it returns a true value, closing the
|
| 158 |
+
transport is up to the protocol.
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class DatagramProtocol(BaseProtocol):
|
| 163 |
+
"""Interface for datagram protocol."""
|
| 164 |
+
|
| 165 |
+
__slots__ = ()
|
| 166 |
+
|
| 167 |
+
def datagram_received(self, data, addr):
|
| 168 |
+
"""Called when some datagram is received."""
|
| 169 |
+
|
| 170 |
+
def error_received(self, exc):
|
| 171 |
+
"""Called when a send or receive operation raises an OSError.
|
| 172 |
+
|
| 173 |
+
(Other than BlockingIOError or InterruptedError.)
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class SubprocessProtocol(BaseProtocol):
|
| 178 |
+
"""Interface for protocol for subprocess calls."""
|
| 179 |
+
|
| 180 |
+
__slots__ = ()
|
| 181 |
+
|
| 182 |
+
def pipe_data_received(self, fd, data):
|
| 183 |
+
"""Called when the subprocess writes data into stdout/stderr pipe.
|
| 184 |
+
|
| 185 |
+
fd is int file descriptor.
|
| 186 |
+
data is bytes object.
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
def pipe_connection_lost(self, fd, exc):
|
| 190 |
+
"""Called when a file descriptor associated with the child process is
|
| 191 |
+
closed.
|
| 192 |
+
|
| 193 |
+
fd is the int file descriptor that was closed.
|
| 194 |
+
"""
|
| 195 |
+
|
| 196 |
+
def process_exited(self):
|
| 197 |
+
"""Called when subprocess has exited."""
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def _feed_data_to_buffered_proto(proto, data):
|
| 201 |
+
data_len = len(data)
|
| 202 |
+
while data_len:
|
| 203 |
+
buf = proto.get_buffer(data_len)
|
| 204 |
+
buf_len = len(buf)
|
| 205 |
+
if not buf_len:
|
| 206 |
+
raise RuntimeError('get_buffer() returned an empty buffer')
|
| 207 |
+
|
| 208 |
+
if buf_len >= data_len:
|
| 209 |
+
buf[:data_len] = data
|
| 210 |
+
proto.buffer_updated(data_len)
|
| 211 |
+
return
|
| 212 |
+
else:
|
| 213 |
+
buf[:buf_len] = data[:buf_len]
|
| 214 |
+
proto.buffer_updated(buf_len)
|
| 215 |
+
data = data[buf_len:]
|
| 216 |
+
data_len = len(data)
|
parrot/lib/python3.10/asyncio/runners.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__all__ = 'run',
|
| 2 |
+
|
| 3 |
+
from . import coroutines
|
| 4 |
+
from . import events
|
| 5 |
+
from . import tasks
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def run(main, *, debug=None):
|
| 9 |
+
"""Execute the coroutine and return the result.
|
| 10 |
+
|
| 11 |
+
This function runs the passed coroutine, taking care of
|
| 12 |
+
managing the asyncio event loop and finalizing asynchronous
|
| 13 |
+
generators.
|
| 14 |
+
|
| 15 |
+
This function cannot be called when another asyncio event loop is
|
| 16 |
+
running in the same thread.
|
| 17 |
+
|
| 18 |
+
If debug is True, the event loop will be run in debug mode.
|
| 19 |
+
|
| 20 |
+
This function always creates a new event loop and closes it at the end.
|
| 21 |
+
It should be used as a main entry point for asyncio programs, and should
|
| 22 |
+
ideally only be called once.
|
| 23 |
+
|
| 24 |
+
Example:
|
| 25 |
+
|
| 26 |
+
async def main():
|
| 27 |
+
await asyncio.sleep(1)
|
| 28 |
+
print('hello')
|
| 29 |
+
|
| 30 |
+
asyncio.run(main())
|
| 31 |
+
"""
|
| 32 |
+
if events._get_running_loop() is not None:
|
| 33 |
+
raise RuntimeError(
|
| 34 |
+
"asyncio.run() cannot be called from a running event loop")
|
| 35 |
+
|
| 36 |
+
if not coroutines.iscoroutine(main):
|
| 37 |
+
raise ValueError("a coroutine was expected, got {!r}".format(main))
|
| 38 |
+
|
| 39 |
+
loop = events.new_event_loop()
|
| 40 |
+
try:
|
| 41 |
+
events.set_event_loop(loop)
|
| 42 |
+
if debug is not None:
|
| 43 |
+
loop.set_debug(debug)
|
| 44 |
+
return loop.run_until_complete(main)
|
| 45 |
+
finally:
|
| 46 |
+
try:
|
| 47 |
+
_cancel_all_tasks(loop)
|
| 48 |
+
loop.run_until_complete(loop.shutdown_asyncgens())
|
| 49 |
+
loop.run_until_complete(loop.shutdown_default_executor())
|
| 50 |
+
finally:
|
| 51 |
+
events.set_event_loop(None)
|
| 52 |
+
loop.close()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _cancel_all_tasks(loop):
|
| 56 |
+
to_cancel = tasks.all_tasks(loop)
|
| 57 |
+
if not to_cancel:
|
| 58 |
+
return
|
| 59 |
+
|
| 60 |
+
for task in to_cancel:
|
| 61 |
+
task.cancel()
|
| 62 |
+
|
| 63 |
+
loop.run_until_complete(tasks.gather(*to_cancel, return_exceptions=True))
|
| 64 |
+
|
| 65 |
+
for task in to_cancel:
|
| 66 |
+
if task.cancelled():
|
| 67 |
+
continue
|
| 68 |
+
if task.exception() is not None:
|
| 69 |
+
loop.call_exception_handler({
|
| 70 |
+
'message': 'unhandled exception during asyncio.run() shutdown',
|
| 71 |
+
'exception': task.exception(),
|
| 72 |
+
'task': task,
|
| 73 |
+
})
|
parrot/lib/python3.10/asyncio/selector_events.py
ADDED
|
@@ -0,0 +1,1105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Event loop using a selector and related classes.
|
| 2 |
+
|
| 3 |
+
A selector is a "notify-when-ready" multiplexer. For a subclass which
|
| 4 |
+
also includes support for signal handling, see the unix_events sub-module.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
__all__ = 'BaseSelectorEventLoop',
|
| 8 |
+
|
| 9 |
+
import collections
|
| 10 |
+
import errno
|
| 11 |
+
import functools
|
| 12 |
+
import selectors
|
| 13 |
+
import socket
|
| 14 |
+
import warnings
|
| 15 |
+
import weakref
|
| 16 |
+
try:
|
| 17 |
+
import ssl
|
| 18 |
+
except ImportError: # pragma: no cover
|
| 19 |
+
ssl = None
|
| 20 |
+
|
| 21 |
+
from . import base_events
|
| 22 |
+
from . import constants
|
| 23 |
+
from . import events
|
| 24 |
+
from . import futures
|
| 25 |
+
from . import protocols
|
| 26 |
+
from . import sslproto
|
| 27 |
+
from . import transports
|
| 28 |
+
from . import trsock
|
| 29 |
+
from .log import logger
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _test_selector_event(selector, fd, event):
|
| 33 |
+
# Test if the selector is monitoring 'event' events
|
| 34 |
+
# for the file descriptor 'fd'.
|
| 35 |
+
try:
|
| 36 |
+
key = selector.get_key(fd)
|
| 37 |
+
except KeyError:
|
| 38 |
+
return False
|
| 39 |
+
else:
|
| 40 |
+
return bool(key.events & event)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class BaseSelectorEventLoop(base_events.BaseEventLoop):
|
| 44 |
+
"""Selector event loop.
|
| 45 |
+
|
| 46 |
+
See events.EventLoop for API specification.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
def __init__(self, selector=None):
|
| 50 |
+
super().__init__()
|
| 51 |
+
|
| 52 |
+
if selector is None:
|
| 53 |
+
selector = selectors.DefaultSelector()
|
| 54 |
+
logger.debug('Using selector: %s', selector.__class__.__name__)
|
| 55 |
+
self._selector = selector
|
| 56 |
+
self._make_self_pipe()
|
| 57 |
+
self._transports = weakref.WeakValueDictionary()
|
| 58 |
+
|
| 59 |
+
def _make_socket_transport(self, sock, protocol, waiter=None, *,
|
| 60 |
+
extra=None, server=None):
|
| 61 |
+
return _SelectorSocketTransport(self, sock, protocol, waiter,
|
| 62 |
+
extra, server)
|
| 63 |
+
|
| 64 |
+
def _make_ssl_transport(
|
| 65 |
+
self, rawsock, protocol, sslcontext, waiter=None,
|
| 66 |
+
*, server_side=False, server_hostname=None,
|
| 67 |
+
extra=None, server=None,
|
| 68 |
+
ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT):
|
| 69 |
+
ssl_protocol = sslproto.SSLProtocol(
|
| 70 |
+
self, protocol, sslcontext, waiter,
|
| 71 |
+
server_side, server_hostname,
|
| 72 |
+
ssl_handshake_timeout=ssl_handshake_timeout)
|
| 73 |
+
_SelectorSocketTransport(self, rawsock, ssl_protocol,
|
| 74 |
+
extra=extra, server=server)
|
| 75 |
+
return ssl_protocol._app_transport
|
| 76 |
+
|
| 77 |
+
def _make_datagram_transport(self, sock, protocol,
|
| 78 |
+
address=None, waiter=None, extra=None):
|
| 79 |
+
return _SelectorDatagramTransport(self, sock, protocol,
|
| 80 |
+
address, waiter, extra)
|
| 81 |
+
|
| 82 |
+
def close(self):
|
| 83 |
+
if self.is_running():
|
| 84 |
+
raise RuntimeError("Cannot close a running event loop")
|
| 85 |
+
if self.is_closed():
|
| 86 |
+
return
|
| 87 |
+
self._close_self_pipe()
|
| 88 |
+
super().close()
|
| 89 |
+
if self._selector is not None:
|
| 90 |
+
self._selector.close()
|
| 91 |
+
self._selector = None
|
| 92 |
+
|
| 93 |
+
def _close_self_pipe(self):
|
| 94 |
+
self._remove_reader(self._ssock.fileno())
|
| 95 |
+
self._ssock.close()
|
| 96 |
+
self._ssock = None
|
| 97 |
+
self._csock.close()
|
| 98 |
+
self._csock = None
|
| 99 |
+
self._internal_fds -= 1
|
| 100 |
+
|
| 101 |
+
def _make_self_pipe(self):
|
| 102 |
+
# A self-socket, really. :-)
|
| 103 |
+
self._ssock, self._csock = socket.socketpair()
|
| 104 |
+
self._ssock.setblocking(False)
|
| 105 |
+
self._csock.setblocking(False)
|
| 106 |
+
self._internal_fds += 1
|
| 107 |
+
self._add_reader(self._ssock.fileno(), self._read_from_self)
|
| 108 |
+
|
| 109 |
+
def _process_self_data(self, data):
|
| 110 |
+
pass
|
| 111 |
+
|
| 112 |
+
def _read_from_self(self):
|
| 113 |
+
while True:
|
| 114 |
+
try:
|
| 115 |
+
data = self._ssock.recv(4096)
|
| 116 |
+
if not data:
|
| 117 |
+
break
|
| 118 |
+
self._process_self_data(data)
|
| 119 |
+
except InterruptedError:
|
| 120 |
+
continue
|
| 121 |
+
except BlockingIOError:
|
| 122 |
+
break
|
| 123 |
+
|
| 124 |
+
def _write_to_self(self):
|
| 125 |
+
# This may be called from a different thread, possibly after
|
| 126 |
+
# _close_self_pipe() has been called or even while it is
|
| 127 |
+
# running. Guard for self._csock being None or closed. When
|
| 128 |
+
# a socket is closed, send() raises OSError (with errno set to
|
| 129 |
+
# EBADF, but let's not rely on the exact error code).
|
| 130 |
+
csock = self._csock
|
| 131 |
+
if csock is None:
|
| 132 |
+
return
|
| 133 |
+
|
| 134 |
+
try:
|
| 135 |
+
csock.send(b'\0')
|
| 136 |
+
except OSError:
|
| 137 |
+
if self._debug:
|
| 138 |
+
logger.debug("Fail to write a null byte into the "
|
| 139 |
+
"self-pipe socket",
|
| 140 |
+
exc_info=True)
|
| 141 |
+
|
| 142 |
+
def _start_serving(self, protocol_factory, sock,
|
| 143 |
+
sslcontext=None, server=None, backlog=100,
|
| 144 |
+
ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT):
|
| 145 |
+
self._add_reader(sock.fileno(), self._accept_connection,
|
| 146 |
+
protocol_factory, sock, sslcontext, server, backlog,
|
| 147 |
+
ssl_handshake_timeout)
|
| 148 |
+
|
| 149 |
+
def _accept_connection(
|
| 150 |
+
self, protocol_factory, sock,
|
| 151 |
+
sslcontext=None, server=None, backlog=100,
|
| 152 |
+
ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT):
|
| 153 |
+
# This method is only called once for each event loop tick where the
|
| 154 |
+
# listening socket has triggered an EVENT_READ. There may be multiple
|
| 155 |
+
# connections waiting for an .accept() so it is called in a loop.
|
| 156 |
+
# See https://bugs.python.org/issue27906 for more details.
|
| 157 |
+
for _ in range(backlog):
|
| 158 |
+
try:
|
| 159 |
+
conn, addr = sock.accept()
|
| 160 |
+
if self._debug:
|
| 161 |
+
logger.debug("%r got a new connection from %r: %r",
|
| 162 |
+
server, addr, conn)
|
| 163 |
+
conn.setblocking(False)
|
| 164 |
+
except (BlockingIOError, InterruptedError, ConnectionAbortedError):
|
| 165 |
+
# Early exit because the socket accept buffer is empty.
|
| 166 |
+
return None
|
| 167 |
+
except OSError as exc:
|
| 168 |
+
# There's nowhere to send the error, so just log it.
|
| 169 |
+
if exc.errno in (errno.EMFILE, errno.ENFILE,
|
| 170 |
+
errno.ENOBUFS, errno.ENOMEM):
|
| 171 |
+
# Some platforms (e.g. Linux keep reporting the FD as
|
| 172 |
+
# ready, so we remove the read handler temporarily.
|
| 173 |
+
# We'll try again in a while.
|
| 174 |
+
self.call_exception_handler({
|
| 175 |
+
'message': 'socket.accept() out of system resource',
|
| 176 |
+
'exception': exc,
|
| 177 |
+
'socket': trsock.TransportSocket(sock),
|
| 178 |
+
})
|
| 179 |
+
self._remove_reader(sock.fileno())
|
| 180 |
+
self.call_later(constants.ACCEPT_RETRY_DELAY,
|
| 181 |
+
self._start_serving,
|
| 182 |
+
protocol_factory, sock, sslcontext, server,
|
| 183 |
+
backlog, ssl_handshake_timeout)
|
| 184 |
+
else:
|
| 185 |
+
raise # The event loop will catch, log and ignore it.
|
| 186 |
+
else:
|
| 187 |
+
extra = {'peername': addr}
|
| 188 |
+
accept = self._accept_connection2(
|
| 189 |
+
protocol_factory, conn, extra, sslcontext, server,
|
| 190 |
+
ssl_handshake_timeout)
|
| 191 |
+
self.create_task(accept)
|
| 192 |
+
|
| 193 |
+
async def _accept_connection2(
|
| 194 |
+
self, protocol_factory, conn, extra,
|
| 195 |
+
sslcontext=None, server=None,
|
| 196 |
+
ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT):
|
| 197 |
+
protocol = None
|
| 198 |
+
transport = None
|
| 199 |
+
try:
|
| 200 |
+
protocol = protocol_factory()
|
| 201 |
+
waiter = self.create_future()
|
| 202 |
+
if sslcontext:
|
| 203 |
+
transport = self._make_ssl_transport(
|
| 204 |
+
conn, protocol, sslcontext, waiter=waiter,
|
| 205 |
+
server_side=True, extra=extra, server=server,
|
| 206 |
+
ssl_handshake_timeout=ssl_handshake_timeout)
|
| 207 |
+
else:
|
| 208 |
+
transport = self._make_socket_transport(
|
| 209 |
+
conn, protocol, waiter=waiter, extra=extra,
|
| 210 |
+
server=server)
|
| 211 |
+
|
| 212 |
+
try:
|
| 213 |
+
await waiter
|
| 214 |
+
except BaseException:
|
| 215 |
+
transport.close()
|
| 216 |
+
raise
|
| 217 |
+
# It's now up to the protocol to handle the connection.
|
| 218 |
+
|
| 219 |
+
except (SystemExit, KeyboardInterrupt):
|
| 220 |
+
raise
|
| 221 |
+
except BaseException as exc:
|
| 222 |
+
if self._debug:
|
| 223 |
+
context = {
|
| 224 |
+
'message':
|
| 225 |
+
'Error on transport creation for incoming connection',
|
| 226 |
+
'exception': exc,
|
| 227 |
+
}
|
| 228 |
+
if protocol is not None:
|
| 229 |
+
context['protocol'] = protocol
|
| 230 |
+
if transport is not None:
|
| 231 |
+
context['transport'] = transport
|
| 232 |
+
self.call_exception_handler(context)
|
| 233 |
+
|
| 234 |
+
def _ensure_fd_no_transport(self, fd):
|
| 235 |
+
fileno = fd
|
| 236 |
+
if not isinstance(fileno, int):
|
| 237 |
+
try:
|
| 238 |
+
fileno = int(fileno.fileno())
|
| 239 |
+
except (AttributeError, TypeError, ValueError):
|
| 240 |
+
# This code matches selectors._fileobj_to_fd function.
|
| 241 |
+
raise ValueError(f"Invalid file object: {fd!r}") from None
|
| 242 |
+
try:
|
| 243 |
+
transport = self._transports[fileno]
|
| 244 |
+
except KeyError:
|
| 245 |
+
pass
|
| 246 |
+
else:
|
| 247 |
+
if not transport.is_closing():
|
| 248 |
+
raise RuntimeError(
|
| 249 |
+
f'File descriptor {fd!r} is used by transport '
|
| 250 |
+
f'{transport!r}')
|
| 251 |
+
|
| 252 |
+
def _add_reader(self, fd, callback, *args):
|
| 253 |
+
self._check_closed()
|
| 254 |
+
handle = events.Handle(callback, args, self, None)
|
| 255 |
+
try:
|
| 256 |
+
key = self._selector.get_key(fd)
|
| 257 |
+
except KeyError:
|
| 258 |
+
self._selector.register(fd, selectors.EVENT_READ,
|
| 259 |
+
(handle, None))
|
| 260 |
+
else:
|
| 261 |
+
mask, (reader, writer) = key.events, key.data
|
| 262 |
+
self._selector.modify(fd, mask | selectors.EVENT_READ,
|
| 263 |
+
(handle, writer))
|
| 264 |
+
if reader is not None:
|
| 265 |
+
reader.cancel()
|
| 266 |
+
return handle
|
| 267 |
+
|
| 268 |
+
def _remove_reader(self, fd):
|
| 269 |
+
if self.is_closed():
|
| 270 |
+
return False
|
| 271 |
+
try:
|
| 272 |
+
key = self._selector.get_key(fd)
|
| 273 |
+
except KeyError:
|
| 274 |
+
return False
|
| 275 |
+
else:
|
| 276 |
+
mask, (reader, writer) = key.events, key.data
|
| 277 |
+
mask &= ~selectors.EVENT_READ
|
| 278 |
+
if not mask:
|
| 279 |
+
self._selector.unregister(fd)
|
| 280 |
+
else:
|
| 281 |
+
self._selector.modify(fd, mask, (None, writer))
|
| 282 |
+
|
| 283 |
+
if reader is not None:
|
| 284 |
+
reader.cancel()
|
| 285 |
+
return True
|
| 286 |
+
else:
|
| 287 |
+
return False
|
| 288 |
+
|
| 289 |
+
def _add_writer(self, fd, callback, *args):
|
| 290 |
+
self._check_closed()
|
| 291 |
+
handle = events.Handle(callback, args, self, None)
|
| 292 |
+
try:
|
| 293 |
+
key = self._selector.get_key(fd)
|
| 294 |
+
except KeyError:
|
| 295 |
+
self._selector.register(fd, selectors.EVENT_WRITE,
|
| 296 |
+
(None, handle))
|
| 297 |
+
else:
|
| 298 |
+
mask, (reader, writer) = key.events, key.data
|
| 299 |
+
self._selector.modify(fd, mask | selectors.EVENT_WRITE,
|
| 300 |
+
(reader, handle))
|
| 301 |
+
if writer is not None:
|
| 302 |
+
writer.cancel()
|
| 303 |
+
return handle
|
| 304 |
+
|
| 305 |
+
def _remove_writer(self, fd):
|
| 306 |
+
"""Remove a writer callback."""
|
| 307 |
+
if self.is_closed():
|
| 308 |
+
return False
|
| 309 |
+
try:
|
| 310 |
+
key = self._selector.get_key(fd)
|
| 311 |
+
except KeyError:
|
| 312 |
+
return False
|
| 313 |
+
else:
|
| 314 |
+
mask, (reader, writer) = key.events, key.data
|
| 315 |
+
# Remove both writer and connector.
|
| 316 |
+
mask &= ~selectors.EVENT_WRITE
|
| 317 |
+
if not mask:
|
| 318 |
+
self._selector.unregister(fd)
|
| 319 |
+
else:
|
| 320 |
+
self._selector.modify(fd, mask, (reader, None))
|
| 321 |
+
|
| 322 |
+
if writer is not None:
|
| 323 |
+
writer.cancel()
|
| 324 |
+
return True
|
| 325 |
+
else:
|
| 326 |
+
return False
|
| 327 |
+
|
| 328 |
+
def add_reader(self, fd, callback, *args):
|
| 329 |
+
"""Add a reader callback."""
|
| 330 |
+
self._ensure_fd_no_transport(fd)
|
| 331 |
+
self._add_reader(fd, callback, *args)
|
| 332 |
+
|
| 333 |
+
def remove_reader(self, fd):
|
| 334 |
+
"""Remove a reader callback."""
|
| 335 |
+
self._ensure_fd_no_transport(fd)
|
| 336 |
+
return self._remove_reader(fd)
|
| 337 |
+
|
| 338 |
+
def add_writer(self, fd, callback, *args):
|
| 339 |
+
"""Add a writer callback.."""
|
| 340 |
+
self._ensure_fd_no_transport(fd)
|
| 341 |
+
self._add_writer(fd, callback, *args)
|
| 342 |
+
|
| 343 |
+
def remove_writer(self, fd):
|
| 344 |
+
"""Remove a writer callback."""
|
| 345 |
+
self._ensure_fd_no_transport(fd)
|
| 346 |
+
return self._remove_writer(fd)
|
| 347 |
+
|
| 348 |
+
async def sock_recv(self, sock, n):
|
| 349 |
+
"""Receive data from the socket.
|
| 350 |
+
|
| 351 |
+
The return value is a bytes object representing the data received.
|
| 352 |
+
The maximum amount of data to be received at once is specified by
|
| 353 |
+
nbytes.
|
| 354 |
+
"""
|
| 355 |
+
base_events._check_ssl_socket(sock)
|
| 356 |
+
if self._debug and sock.gettimeout() != 0:
|
| 357 |
+
raise ValueError("the socket must be non-blocking")
|
| 358 |
+
try:
|
| 359 |
+
return sock.recv(n)
|
| 360 |
+
except (BlockingIOError, InterruptedError):
|
| 361 |
+
pass
|
| 362 |
+
fut = self.create_future()
|
| 363 |
+
fd = sock.fileno()
|
| 364 |
+
self._ensure_fd_no_transport(fd)
|
| 365 |
+
handle = self._add_reader(fd, self._sock_recv, fut, sock, n)
|
| 366 |
+
fut.add_done_callback(
|
| 367 |
+
functools.partial(self._sock_read_done, fd, handle=handle))
|
| 368 |
+
return await fut
|
| 369 |
+
|
| 370 |
+
def _sock_read_done(self, fd, fut, handle=None):
|
| 371 |
+
if handle is None or not handle.cancelled():
|
| 372 |
+
self.remove_reader(fd)
|
| 373 |
+
|
| 374 |
+
def _sock_recv(self, fut, sock, n):
|
| 375 |
+
# _sock_recv() can add itself as an I/O callback if the operation can't
|
| 376 |
+
# be done immediately. Don't use it directly, call sock_recv().
|
| 377 |
+
if fut.done():
|
| 378 |
+
return
|
| 379 |
+
try:
|
| 380 |
+
data = sock.recv(n)
|
| 381 |
+
except (BlockingIOError, InterruptedError):
|
| 382 |
+
return # try again next time
|
| 383 |
+
except (SystemExit, KeyboardInterrupt):
|
| 384 |
+
raise
|
| 385 |
+
except BaseException as exc:
|
| 386 |
+
fut.set_exception(exc)
|
| 387 |
+
else:
|
| 388 |
+
fut.set_result(data)
|
| 389 |
+
|
| 390 |
+
async def sock_recv_into(self, sock, buf):
|
| 391 |
+
"""Receive data from the socket.
|
| 392 |
+
|
| 393 |
+
The received data is written into *buf* (a writable buffer).
|
| 394 |
+
The return value is the number of bytes written.
|
| 395 |
+
"""
|
| 396 |
+
base_events._check_ssl_socket(sock)
|
| 397 |
+
if self._debug and sock.gettimeout() != 0:
|
| 398 |
+
raise ValueError("the socket must be non-blocking")
|
| 399 |
+
try:
|
| 400 |
+
return sock.recv_into(buf)
|
| 401 |
+
except (BlockingIOError, InterruptedError):
|
| 402 |
+
pass
|
| 403 |
+
fut = self.create_future()
|
| 404 |
+
fd = sock.fileno()
|
| 405 |
+
self._ensure_fd_no_transport(fd)
|
| 406 |
+
handle = self._add_reader(fd, self._sock_recv_into, fut, sock, buf)
|
| 407 |
+
fut.add_done_callback(
|
| 408 |
+
functools.partial(self._sock_read_done, fd, handle=handle))
|
| 409 |
+
return await fut
|
| 410 |
+
|
| 411 |
+
def _sock_recv_into(self, fut, sock, buf):
|
| 412 |
+
# _sock_recv_into() can add itself as an I/O callback if the operation
|
| 413 |
+
# can't be done immediately. Don't use it directly, call
|
| 414 |
+
# sock_recv_into().
|
| 415 |
+
if fut.done():
|
| 416 |
+
return
|
| 417 |
+
try:
|
| 418 |
+
nbytes = sock.recv_into(buf)
|
| 419 |
+
except (BlockingIOError, InterruptedError):
|
| 420 |
+
return # try again next time
|
| 421 |
+
except (SystemExit, KeyboardInterrupt):
|
| 422 |
+
raise
|
| 423 |
+
except BaseException as exc:
|
| 424 |
+
fut.set_exception(exc)
|
| 425 |
+
else:
|
| 426 |
+
fut.set_result(nbytes)
|
| 427 |
+
|
| 428 |
+
async def sock_sendall(self, sock, data):
|
| 429 |
+
"""Send data to the socket.
|
| 430 |
+
|
| 431 |
+
The socket must be connected to a remote socket. This method continues
|
| 432 |
+
to send data from data until either all data has been sent or an
|
| 433 |
+
error occurs. None is returned on success. On error, an exception is
|
| 434 |
+
raised, and there is no way to determine how much data, if any, was
|
| 435 |
+
successfully processed by the receiving end of the connection.
|
| 436 |
+
"""
|
| 437 |
+
base_events._check_ssl_socket(sock)
|
| 438 |
+
if self._debug and sock.gettimeout() != 0:
|
| 439 |
+
raise ValueError("the socket must be non-blocking")
|
| 440 |
+
try:
|
| 441 |
+
n = sock.send(data)
|
| 442 |
+
except (BlockingIOError, InterruptedError):
|
| 443 |
+
n = 0
|
| 444 |
+
|
| 445 |
+
if n == len(data):
|
| 446 |
+
# all data sent
|
| 447 |
+
return
|
| 448 |
+
|
| 449 |
+
fut = self.create_future()
|
| 450 |
+
fd = sock.fileno()
|
| 451 |
+
self._ensure_fd_no_transport(fd)
|
| 452 |
+
# use a trick with a list in closure to store a mutable state
|
| 453 |
+
handle = self._add_writer(fd, self._sock_sendall, fut, sock,
|
| 454 |
+
memoryview(data), [n])
|
| 455 |
+
fut.add_done_callback(
|
| 456 |
+
functools.partial(self._sock_write_done, fd, handle=handle))
|
| 457 |
+
return await fut
|
| 458 |
+
|
| 459 |
+
def _sock_sendall(self, fut, sock, view, pos):
|
| 460 |
+
if fut.done():
|
| 461 |
+
# Future cancellation can be scheduled on previous loop iteration
|
| 462 |
+
return
|
| 463 |
+
start = pos[0]
|
| 464 |
+
try:
|
| 465 |
+
n = sock.send(view[start:])
|
| 466 |
+
except (BlockingIOError, InterruptedError):
|
| 467 |
+
return
|
| 468 |
+
except (SystemExit, KeyboardInterrupt):
|
| 469 |
+
raise
|
| 470 |
+
except BaseException as exc:
|
| 471 |
+
fut.set_exception(exc)
|
| 472 |
+
return
|
| 473 |
+
|
| 474 |
+
start += n
|
| 475 |
+
|
| 476 |
+
if start == len(view):
|
| 477 |
+
fut.set_result(None)
|
| 478 |
+
else:
|
| 479 |
+
pos[0] = start
|
| 480 |
+
|
| 481 |
+
async def sock_connect(self, sock, address):
|
| 482 |
+
"""Connect to a remote socket at address.
|
| 483 |
+
|
| 484 |
+
This method is a coroutine.
|
| 485 |
+
"""
|
| 486 |
+
base_events._check_ssl_socket(sock)
|
| 487 |
+
if self._debug and sock.gettimeout() != 0:
|
| 488 |
+
raise ValueError("the socket must be non-blocking")
|
| 489 |
+
|
| 490 |
+
if sock.family == socket.AF_INET or (
|
| 491 |
+
base_events._HAS_IPv6 and sock.family == socket.AF_INET6):
|
| 492 |
+
resolved = await self._ensure_resolved(
|
| 493 |
+
address, family=sock.family, type=sock.type, proto=sock.proto,
|
| 494 |
+
loop=self,
|
| 495 |
+
)
|
| 496 |
+
_, _, _, _, address = resolved[0]
|
| 497 |
+
|
| 498 |
+
fut = self.create_future()
|
| 499 |
+
self._sock_connect(fut, sock, address)
|
| 500 |
+
try:
|
| 501 |
+
return await fut
|
| 502 |
+
finally:
|
| 503 |
+
# Needed to break cycles when an exception occurs.
|
| 504 |
+
fut = None
|
| 505 |
+
|
| 506 |
+
def _sock_connect(self, fut, sock, address):
|
| 507 |
+
fd = sock.fileno()
|
| 508 |
+
try:
|
| 509 |
+
sock.connect(address)
|
| 510 |
+
except (BlockingIOError, InterruptedError):
|
| 511 |
+
# Issue #23618: When the C function connect() fails with EINTR, the
|
| 512 |
+
# connection runs in background. We have to wait until the socket
|
| 513 |
+
# becomes writable to be notified when the connection succeed or
|
| 514 |
+
# fails.
|
| 515 |
+
self._ensure_fd_no_transport(fd)
|
| 516 |
+
handle = self._add_writer(
|
| 517 |
+
fd, self._sock_connect_cb, fut, sock, address)
|
| 518 |
+
fut.add_done_callback(
|
| 519 |
+
functools.partial(self._sock_write_done, fd, handle=handle))
|
| 520 |
+
except (SystemExit, KeyboardInterrupt):
|
| 521 |
+
raise
|
| 522 |
+
except BaseException as exc:
|
| 523 |
+
fut.set_exception(exc)
|
| 524 |
+
else:
|
| 525 |
+
fut.set_result(None)
|
| 526 |
+
finally:
|
| 527 |
+
fut = None
|
| 528 |
+
|
| 529 |
+
def _sock_write_done(self, fd, fut, handle=None):
|
| 530 |
+
if handle is None or not handle.cancelled():
|
| 531 |
+
self.remove_writer(fd)
|
| 532 |
+
|
| 533 |
+
def _sock_connect_cb(self, fut, sock, address):
|
| 534 |
+
if fut.done():
|
| 535 |
+
return
|
| 536 |
+
|
| 537 |
+
try:
|
| 538 |
+
err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
|
| 539 |
+
if err != 0:
|
| 540 |
+
# Jump to any except clause below.
|
| 541 |
+
raise OSError(err, f'Connect call failed {address}')
|
| 542 |
+
except (BlockingIOError, InterruptedError):
|
| 543 |
+
# socket is still registered, the callback will be retried later
|
| 544 |
+
pass
|
| 545 |
+
except (SystemExit, KeyboardInterrupt):
|
| 546 |
+
raise
|
| 547 |
+
except BaseException as exc:
|
| 548 |
+
fut.set_exception(exc)
|
| 549 |
+
else:
|
| 550 |
+
fut.set_result(None)
|
| 551 |
+
finally:
|
| 552 |
+
fut = None
|
| 553 |
+
|
| 554 |
+
async def sock_accept(self, sock):
|
| 555 |
+
"""Accept a connection.
|
| 556 |
+
|
| 557 |
+
The socket must be bound to an address and listening for connections.
|
| 558 |
+
The return value is a pair (conn, address) where conn is a new socket
|
| 559 |
+
object usable to send and receive data on the connection, and address
|
| 560 |
+
is the address bound to the socket on the other end of the connection.
|
| 561 |
+
"""
|
| 562 |
+
base_events._check_ssl_socket(sock)
|
| 563 |
+
if self._debug and sock.gettimeout() != 0:
|
| 564 |
+
raise ValueError("the socket must be non-blocking")
|
| 565 |
+
fut = self.create_future()
|
| 566 |
+
self._sock_accept(fut, sock)
|
| 567 |
+
return await fut
|
| 568 |
+
|
| 569 |
+
def _sock_accept(self, fut, sock):
|
| 570 |
+
fd = sock.fileno()
|
| 571 |
+
try:
|
| 572 |
+
conn, address = sock.accept()
|
| 573 |
+
conn.setblocking(False)
|
| 574 |
+
except (BlockingIOError, InterruptedError):
|
| 575 |
+
self._ensure_fd_no_transport(fd)
|
| 576 |
+
handle = self._add_reader(fd, self._sock_accept, fut, sock)
|
| 577 |
+
fut.add_done_callback(
|
| 578 |
+
functools.partial(self._sock_read_done, fd, handle=handle))
|
| 579 |
+
except (SystemExit, KeyboardInterrupt):
|
| 580 |
+
raise
|
| 581 |
+
except BaseException as exc:
|
| 582 |
+
fut.set_exception(exc)
|
| 583 |
+
else:
|
| 584 |
+
fut.set_result((conn, address))
|
| 585 |
+
|
| 586 |
+
async def _sendfile_native(self, transp, file, offset, count):
|
| 587 |
+
del self._transports[transp._sock_fd]
|
| 588 |
+
resume_reading = transp.is_reading()
|
| 589 |
+
transp.pause_reading()
|
| 590 |
+
await transp._make_empty_waiter()
|
| 591 |
+
try:
|
| 592 |
+
return await self.sock_sendfile(transp._sock, file, offset, count,
|
| 593 |
+
fallback=False)
|
| 594 |
+
finally:
|
| 595 |
+
transp._reset_empty_waiter()
|
| 596 |
+
if resume_reading:
|
| 597 |
+
transp.resume_reading()
|
| 598 |
+
self._transports[transp._sock_fd] = transp
|
| 599 |
+
|
| 600 |
+
def _process_events(self, event_list):
|
| 601 |
+
for key, mask in event_list:
|
| 602 |
+
fileobj, (reader, writer) = key.fileobj, key.data
|
| 603 |
+
if mask & selectors.EVENT_READ and reader is not None:
|
| 604 |
+
if reader._cancelled:
|
| 605 |
+
self._remove_reader(fileobj)
|
| 606 |
+
else:
|
| 607 |
+
self._add_callback(reader)
|
| 608 |
+
if mask & selectors.EVENT_WRITE and writer is not None:
|
| 609 |
+
if writer._cancelled:
|
| 610 |
+
self._remove_writer(fileobj)
|
| 611 |
+
else:
|
| 612 |
+
self._add_callback(writer)
|
| 613 |
+
|
| 614 |
+
def _stop_serving(self, sock):
|
| 615 |
+
self._remove_reader(sock.fileno())
|
| 616 |
+
sock.close()
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
class _SelectorTransport(transports._FlowControlMixin,
|
| 620 |
+
transports.Transport):
|
| 621 |
+
|
| 622 |
+
max_size = 256 * 1024 # Buffer size passed to recv().
|
| 623 |
+
|
| 624 |
+
_buffer_factory = bytearray # Constructs initial value for self._buffer.
|
| 625 |
+
|
| 626 |
+
# Attribute used in the destructor: it must be set even if the constructor
|
| 627 |
+
# is not called (see _SelectorSslTransport which may start by raising an
|
| 628 |
+
# exception)
|
| 629 |
+
_sock = None
|
| 630 |
+
|
| 631 |
+
def __init__(self, loop, sock, protocol, extra=None, server=None):
|
| 632 |
+
super().__init__(extra, loop)
|
| 633 |
+
self._extra['socket'] = trsock.TransportSocket(sock)
|
| 634 |
+
try:
|
| 635 |
+
self._extra['sockname'] = sock.getsockname()
|
| 636 |
+
except OSError:
|
| 637 |
+
self._extra['sockname'] = None
|
| 638 |
+
if 'peername' not in self._extra:
|
| 639 |
+
try:
|
| 640 |
+
self._extra['peername'] = sock.getpeername()
|
| 641 |
+
except socket.error:
|
| 642 |
+
self._extra['peername'] = None
|
| 643 |
+
self._sock = sock
|
| 644 |
+
self._sock_fd = sock.fileno()
|
| 645 |
+
|
| 646 |
+
self._protocol_connected = False
|
| 647 |
+
self.set_protocol(protocol)
|
| 648 |
+
|
| 649 |
+
self._server = server
|
| 650 |
+
self._buffer = self._buffer_factory()
|
| 651 |
+
self._conn_lost = 0 # Set when call to connection_lost scheduled.
|
| 652 |
+
self._closing = False # Set when close() called.
|
| 653 |
+
if self._server is not None:
|
| 654 |
+
self._server._attach()
|
| 655 |
+
loop._transports[self._sock_fd] = self
|
| 656 |
+
|
| 657 |
+
def __repr__(self):
|
| 658 |
+
info = [self.__class__.__name__]
|
| 659 |
+
if self._sock is None:
|
| 660 |
+
info.append('closed')
|
| 661 |
+
elif self._closing:
|
| 662 |
+
info.append('closing')
|
| 663 |
+
info.append(f'fd={self._sock_fd}')
|
| 664 |
+
# test if the transport was closed
|
| 665 |
+
if self._loop is not None and not self._loop.is_closed():
|
| 666 |
+
polling = _test_selector_event(self._loop._selector,
|
| 667 |
+
self._sock_fd, selectors.EVENT_READ)
|
| 668 |
+
if polling:
|
| 669 |
+
info.append('read=polling')
|
| 670 |
+
else:
|
| 671 |
+
info.append('read=idle')
|
| 672 |
+
|
| 673 |
+
polling = _test_selector_event(self._loop._selector,
|
| 674 |
+
self._sock_fd,
|
| 675 |
+
selectors.EVENT_WRITE)
|
| 676 |
+
if polling:
|
| 677 |
+
state = 'polling'
|
| 678 |
+
else:
|
| 679 |
+
state = 'idle'
|
| 680 |
+
|
| 681 |
+
bufsize = self.get_write_buffer_size()
|
| 682 |
+
info.append(f'write=<{state}, bufsize={bufsize}>')
|
| 683 |
+
return '<{}>'.format(' '.join(info))
|
| 684 |
+
|
| 685 |
+
def abort(self):
|
| 686 |
+
self._force_close(None)
|
| 687 |
+
|
| 688 |
+
def set_protocol(self, protocol):
|
| 689 |
+
self._protocol = protocol
|
| 690 |
+
self._protocol_connected = True
|
| 691 |
+
|
| 692 |
+
def get_protocol(self):
|
| 693 |
+
return self._protocol
|
| 694 |
+
|
| 695 |
+
def is_closing(self):
|
| 696 |
+
return self._closing
|
| 697 |
+
|
| 698 |
+
def close(self):
|
| 699 |
+
if self._closing:
|
| 700 |
+
return
|
| 701 |
+
self._closing = True
|
| 702 |
+
self._loop._remove_reader(self._sock_fd)
|
| 703 |
+
if not self._buffer:
|
| 704 |
+
self._conn_lost += 1
|
| 705 |
+
self._loop._remove_writer(self._sock_fd)
|
| 706 |
+
self._loop.call_soon(self._call_connection_lost, None)
|
| 707 |
+
|
| 708 |
+
def __del__(self, _warn=warnings.warn):
|
| 709 |
+
if self._sock is not None:
|
| 710 |
+
_warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
|
| 711 |
+
self._sock.close()
|
| 712 |
+
|
| 713 |
+
def _fatal_error(self, exc, message='Fatal error on transport'):
|
| 714 |
+
# Should be called from exception handler only.
|
| 715 |
+
if isinstance(exc, OSError):
|
| 716 |
+
if self._loop.get_debug():
|
| 717 |
+
logger.debug("%r: %s", self, message, exc_info=True)
|
| 718 |
+
else:
|
| 719 |
+
self._loop.call_exception_handler({
|
| 720 |
+
'message': message,
|
| 721 |
+
'exception': exc,
|
| 722 |
+
'transport': self,
|
| 723 |
+
'protocol': self._protocol,
|
| 724 |
+
})
|
| 725 |
+
self._force_close(exc)
|
| 726 |
+
|
| 727 |
+
def _force_close(self, exc):
|
| 728 |
+
if self._conn_lost:
|
| 729 |
+
return
|
| 730 |
+
if self._buffer:
|
| 731 |
+
self._buffer.clear()
|
| 732 |
+
self._loop._remove_writer(self._sock_fd)
|
| 733 |
+
if not self._closing:
|
| 734 |
+
self._closing = True
|
| 735 |
+
self._loop._remove_reader(self._sock_fd)
|
| 736 |
+
self._conn_lost += 1
|
| 737 |
+
self._loop.call_soon(self._call_connection_lost, exc)
|
| 738 |
+
|
| 739 |
+
def _call_connection_lost(self, exc):
|
| 740 |
+
try:
|
| 741 |
+
if self._protocol_connected:
|
| 742 |
+
self._protocol.connection_lost(exc)
|
| 743 |
+
finally:
|
| 744 |
+
self._sock.close()
|
| 745 |
+
self._sock = None
|
| 746 |
+
self._protocol = None
|
| 747 |
+
self._loop = None
|
| 748 |
+
server = self._server
|
| 749 |
+
if server is not None:
|
| 750 |
+
server._detach()
|
| 751 |
+
self._server = None
|
| 752 |
+
|
| 753 |
+
def get_write_buffer_size(self):
|
| 754 |
+
return len(self._buffer)
|
| 755 |
+
|
| 756 |
+
def _add_reader(self, fd, callback, *args):
|
| 757 |
+
if self._closing:
|
| 758 |
+
return
|
| 759 |
+
|
| 760 |
+
self._loop._add_reader(fd, callback, *args)
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
class _SelectorSocketTransport(_SelectorTransport):
|
| 764 |
+
|
| 765 |
+
_start_tls_compatible = True
|
| 766 |
+
_sendfile_compatible = constants._SendfileMode.TRY_NATIVE
|
| 767 |
+
|
| 768 |
+
def __init__(self, loop, sock, protocol, waiter=None,
|
| 769 |
+
extra=None, server=None):
|
| 770 |
+
|
| 771 |
+
self._read_ready_cb = None
|
| 772 |
+
super().__init__(loop, sock, protocol, extra, server)
|
| 773 |
+
self._eof = False
|
| 774 |
+
self._paused = False
|
| 775 |
+
self._empty_waiter = None
|
| 776 |
+
|
| 777 |
+
# Disable the Nagle algorithm -- small writes will be
|
| 778 |
+
# sent without waiting for the TCP ACK. This generally
|
| 779 |
+
# decreases the latency (in some cases significantly.)
|
| 780 |
+
base_events._set_nodelay(self._sock)
|
| 781 |
+
|
| 782 |
+
self._loop.call_soon(self._protocol.connection_made, self)
|
| 783 |
+
# only start reading when connection_made() has been called
|
| 784 |
+
self._loop.call_soon(self._add_reader,
|
| 785 |
+
self._sock_fd, self._read_ready)
|
| 786 |
+
if waiter is not None:
|
| 787 |
+
# only wake up the waiter when connection_made() has been called
|
| 788 |
+
self._loop.call_soon(futures._set_result_unless_cancelled,
|
| 789 |
+
waiter, None)
|
| 790 |
+
|
| 791 |
+
def set_protocol(self, protocol):
|
| 792 |
+
if isinstance(protocol, protocols.BufferedProtocol):
|
| 793 |
+
self._read_ready_cb = self._read_ready__get_buffer
|
| 794 |
+
else:
|
| 795 |
+
self._read_ready_cb = self._read_ready__data_received
|
| 796 |
+
|
| 797 |
+
super().set_protocol(protocol)
|
| 798 |
+
|
| 799 |
+
def is_reading(self):
|
| 800 |
+
return not self._paused and not self._closing
|
| 801 |
+
|
| 802 |
+
def pause_reading(self):
|
| 803 |
+
if self._closing or self._paused:
|
| 804 |
+
return
|
| 805 |
+
self._paused = True
|
| 806 |
+
self._loop._remove_reader(self._sock_fd)
|
| 807 |
+
if self._loop.get_debug():
|
| 808 |
+
logger.debug("%r pauses reading", self)
|
| 809 |
+
|
| 810 |
+
def resume_reading(self):
|
| 811 |
+
if self._closing or not self._paused:
|
| 812 |
+
return
|
| 813 |
+
self._paused = False
|
| 814 |
+
self._add_reader(self._sock_fd, self._read_ready)
|
| 815 |
+
if self._loop.get_debug():
|
| 816 |
+
logger.debug("%r resumes reading", self)
|
| 817 |
+
|
| 818 |
+
def _read_ready(self):
|
| 819 |
+
self._read_ready_cb()
|
| 820 |
+
|
| 821 |
+
def _read_ready__get_buffer(self):
|
| 822 |
+
if self._conn_lost:
|
| 823 |
+
return
|
| 824 |
+
|
| 825 |
+
try:
|
| 826 |
+
buf = self._protocol.get_buffer(-1)
|
| 827 |
+
if not len(buf):
|
| 828 |
+
raise RuntimeError('get_buffer() returned an empty buffer')
|
| 829 |
+
except (SystemExit, KeyboardInterrupt):
|
| 830 |
+
raise
|
| 831 |
+
except BaseException as exc:
|
| 832 |
+
self._fatal_error(
|
| 833 |
+
exc, 'Fatal error: protocol.get_buffer() call failed.')
|
| 834 |
+
return
|
| 835 |
+
|
| 836 |
+
try:
|
| 837 |
+
nbytes = self._sock.recv_into(buf)
|
| 838 |
+
except (BlockingIOError, InterruptedError):
|
| 839 |
+
return
|
| 840 |
+
except (SystemExit, KeyboardInterrupt):
|
| 841 |
+
raise
|
| 842 |
+
except BaseException as exc:
|
| 843 |
+
self._fatal_error(exc, 'Fatal read error on socket transport')
|
| 844 |
+
return
|
| 845 |
+
|
| 846 |
+
if not nbytes:
|
| 847 |
+
self._read_ready__on_eof()
|
| 848 |
+
return
|
| 849 |
+
|
| 850 |
+
try:
|
| 851 |
+
self._protocol.buffer_updated(nbytes)
|
| 852 |
+
except (SystemExit, KeyboardInterrupt):
|
| 853 |
+
raise
|
| 854 |
+
except BaseException as exc:
|
| 855 |
+
self._fatal_error(
|
| 856 |
+
exc, 'Fatal error: protocol.buffer_updated() call failed.')
|
| 857 |
+
|
| 858 |
+
def _read_ready__data_received(self):
|
| 859 |
+
if self._conn_lost:
|
| 860 |
+
return
|
| 861 |
+
try:
|
| 862 |
+
data = self._sock.recv(self.max_size)
|
| 863 |
+
except (BlockingIOError, InterruptedError):
|
| 864 |
+
return
|
| 865 |
+
except (SystemExit, KeyboardInterrupt):
|
| 866 |
+
raise
|
| 867 |
+
except BaseException as exc:
|
| 868 |
+
self._fatal_error(exc, 'Fatal read error on socket transport')
|
| 869 |
+
return
|
| 870 |
+
|
| 871 |
+
if not data:
|
| 872 |
+
self._read_ready__on_eof()
|
| 873 |
+
return
|
| 874 |
+
|
| 875 |
+
try:
|
| 876 |
+
self._protocol.data_received(data)
|
| 877 |
+
except (SystemExit, KeyboardInterrupt):
|
| 878 |
+
raise
|
| 879 |
+
except BaseException as exc:
|
| 880 |
+
self._fatal_error(
|
| 881 |
+
exc, 'Fatal error: protocol.data_received() call failed.')
|
| 882 |
+
|
| 883 |
+
def _read_ready__on_eof(self):
|
| 884 |
+
if self._loop.get_debug():
|
| 885 |
+
logger.debug("%r received EOF", self)
|
| 886 |
+
|
| 887 |
+
try:
|
| 888 |
+
keep_open = self._protocol.eof_received()
|
| 889 |
+
except (SystemExit, KeyboardInterrupt):
|
| 890 |
+
raise
|
| 891 |
+
except BaseException as exc:
|
| 892 |
+
self._fatal_error(
|
| 893 |
+
exc, 'Fatal error: protocol.eof_received() call failed.')
|
| 894 |
+
return
|
| 895 |
+
|
| 896 |
+
if keep_open:
|
| 897 |
+
# We're keeping the connection open so the
|
| 898 |
+
# protocol can write more, but we still can't
|
| 899 |
+
# receive more, so remove the reader callback.
|
| 900 |
+
self._loop._remove_reader(self._sock_fd)
|
| 901 |
+
else:
|
| 902 |
+
self.close()
|
| 903 |
+
|
| 904 |
+
def write(self, data):
|
| 905 |
+
if not isinstance(data, (bytes, bytearray, memoryview)):
|
| 906 |
+
raise TypeError(f'data argument must be a bytes-like object, '
|
| 907 |
+
f'not {type(data).__name__!r}')
|
| 908 |
+
if self._eof:
|
| 909 |
+
raise RuntimeError('Cannot call write() after write_eof()')
|
| 910 |
+
if self._empty_waiter is not None:
|
| 911 |
+
raise RuntimeError('unable to write; sendfile is in progress')
|
| 912 |
+
if not data:
|
| 913 |
+
return
|
| 914 |
+
|
| 915 |
+
if self._conn_lost:
|
| 916 |
+
if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
|
| 917 |
+
logger.warning('socket.send() raised exception.')
|
| 918 |
+
self._conn_lost += 1
|
| 919 |
+
return
|
| 920 |
+
|
| 921 |
+
if not self._buffer:
|
| 922 |
+
# Optimization: try to send now.
|
| 923 |
+
try:
|
| 924 |
+
n = self._sock.send(data)
|
| 925 |
+
except (BlockingIOError, InterruptedError):
|
| 926 |
+
pass
|
| 927 |
+
except (SystemExit, KeyboardInterrupt):
|
| 928 |
+
raise
|
| 929 |
+
except BaseException as exc:
|
| 930 |
+
self._fatal_error(exc, 'Fatal write error on socket transport')
|
| 931 |
+
return
|
| 932 |
+
else:
|
| 933 |
+
data = data[n:]
|
| 934 |
+
if not data:
|
| 935 |
+
return
|
| 936 |
+
# Not all was written; register write handler.
|
| 937 |
+
self._loop._add_writer(self._sock_fd, self._write_ready)
|
| 938 |
+
|
| 939 |
+
# Add it to the buffer.
|
| 940 |
+
self._buffer.extend(data)
|
| 941 |
+
self._maybe_pause_protocol()
|
| 942 |
+
|
| 943 |
+
def _write_ready(self):
|
| 944 |
+
assert self._buffer, 'Data should not be empty'
|
| 945 |
+
|
| 946 |
+
if self._conn_lost:
|
| 947 |
+
return
|
| 948 |
+
try:
|
| 949 |
+
n = self._sock.send(self._buffer)
|
| 950 |
+
except (BlockingIOError, InterruptedError):
|
| 951 |
+
pass
|
| 952 |
+
except (SystemExit, KeyboardInterrupt):
|
| 953 |
+
raise
|
| 954 |
+
except BaseException as exc:
|
| 955 |
+
self._loop._remove_writer(self._sock_fd)
|
| 956 |
+
self._buffer.clear()
|
| 957 |
+
self._fatal_error(exc, 'Fatal write error on socket transport')
|
| 958 |
+
if self._empty_waiter is not None:
|
| 959 |
+
self._empty_waiter.set_exception(exc)
|
| 960 |
+
else:
|
| 961 |
+
if n:
|
| 962 |
+
del self._buffer[:n]
|
| 963 |
+
self._maybe_resume_protocol() # May append to buffer.
|
| 964 |
+
if not self._buffer:
|
| 965 |
+
self._loop._remove_writer(self._sock_fd)
|
| 966 |
+
if self._empty_waiter is not None:
|
| 967 |
+
self._empty_waiter.set_result(None)
|
| 968 |
+
if self._closing:
|
| 969 |
+
self._call_connection_lost(None)
|
| 970 |
+
elif self._eof:
|
| 971 |
+
self._sock.shutdown(socket.SHUT_WR)
|
| 972 |
+
|
| 973 |
+
def write_eof(self):
|
| 974 |
+
if self._closing or self._eof:
|
| 975 |
+
return
|
| 976 |
+
self._eof = True
|
| 977 |
+
if not self._buffer:
|
| 978 |
+
self._sock.shutdown(socket.SHUT_WR)
|
| 979 |
+
|
| 980 |
+
def can_write_eof(self):
|
| 981 |
+
return True
|
| 982 |
+
|
| 983 |
+
def _call_connection_lost(self, exc):
|
| 984 |
+
super()._call_connection_lost(exc)
|
| 985 |
+
if self._empty_waiter is not None:
|
| 986 |
+
self._empty_waiter.set_exception(
|
| 987 |
+
ConnectionError("Connection is closed by peer"))
|
| 988 |
+
|
| 989 |
+
def _make_empty_waiter(self):
|
| 990 |
+
if self._empty_waiter is not None:
|
| 991 |
+
raise RuntimeError("Empty waiter is already set")
|
| 992 |
+
self._empty_waiter = self._loop.create_future()
|
| 993 |
+
if not self._buffer:
|
| 994 |
+
self._empty_waiter.set_result(None)
|
| 995 |
+
return self._empty_waiter
|
| 996 |
+
|
| 997 |
+
def _reset_empty_waiter(self):
|
| 998 |
+
self._empty_waiter = None
|
| 999 |
+
|
| 1000 |
+
|
| 1001 |
+
class _SelectorDatagramTransport(_SelectorTransport):
|
| 1002 |
+
|
| 1003 |
+
_buffer_factory = collections.deque
|
| 1004 |
+
|
| 1005 |
+
def __init__(self, loop, sock, protocol, address=None,
|
| 1006 |
+
waiter=None, extra=None):
|
| 1007 |
+
super().__init__(loop, sock, protocol, extra)
|
| 1008 |
+
self._address = address
|
| 1009 |
+
self._loop.call_soon(self._protocol.connection_made, self)
|
| 1010 |
+
# only start reading when connection_made() has been called
|
| 1011 |
+
self._loop.call_soon(self._add_reader,
|
| 1012 |
+
self._sock_fd, self._read_ready)
|
| 1013 |
+
if waiter is not None:
|
| 1014 |
+
# only wake up the waiter when connection_made() has been called
|
| 1015 |
+
self._loop.call_soon(futures._set_result_unless_cancelled,
|
| 1016 |
+
waiter, None)
|
| 1017 |
+
|
| 1018 |
+
def get_write_buffer_size(self):
|
| 1019 |
+
return sum(len(data) for data, _ in self._buffer)
|
| 1020 |
+
|
| 1021 |
+
def _read_ready(self):
|
| 1022 |
+
if self._conn_lost:
|
| 1023 |
+
return
|
| 1024 |
+
try:
|
| 1025 |
+
data, addr = self._sock.recvfrom(self.max_size)
|
| 1026 |
+
except (BlockingIOError, InterruptedError):
|
| 1027 |
+
pass
|
| 1028 |
+
except OSError as exc:
|
| 1029 |
+
self._protocol.error_received(exc)
|
| 1030 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1031 |
+
raise
|
| 1032 |
+
except BaseException as exc:
|
| 1033 |
+
self._fatal_error(exc, 'Fatal read error on datagram transport')
|
| 1034 |
+
else:
|
| 1035 |
+
self._protocol.datagram_received(data, addr)
|
| 1036 |
+
|
| 1037 |
+
def sendto(self, data, addr=None):
|
| 1038 |
+
if not isinstance(data, (bytes, bytearray, memoryview)):
|
| 1039 |
+
raise TypeError(f'data argument must be a bytes-like object, '
|
| 1040 |
+
f'not {type(data).__name__!r}')
|
| 1041 |
+
if not data:
|
| 1042 |
+
return
|
| 1043 |
+
|
| 1044 |
+
if self._address:
|
| 1045 |
+
if addr not in (None, self._address):
|
| 1046 |
+
raise ValueError(
|
| 1047 |
+
f'Invalid address: must be None or {self._address}')
|
| 1048 |
+
addr = self._address
|
| 1049 |
+
|
| 1050 |
+
if self._conn_lost and self._address:
|
| 1051 |
+
if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
|
| 1052 |
+
logger.warning('socket.send() raised exception.')
|
| 1053 |
+
self._conn_lost += 1
|
| 1054 |
+
return
|
| 1055 |
+
|
| 1056 |
+
if not self._buffer:
|
| 1057 |
+
# Attempt to send it right away first.
|
| 1058 |
+
try:
|
| 1059 |
+
if self._extra['peername']:
|
| 1060 |
+
self._sock.send(data)
|
| 1061 |
+
else:
|
| 1062 |
+
self._sock.sendto(data, addr)
|
| 1063 |
+
return
|
| 1064 |
+
except (BlockingIOError, InterruptedError):
|
| 1065 |
+
self._loop._add_writer(self._sock_fd, self._sendto_ready)
|
| 1066 |
+
except OSError as exc:
|
| 1067 |
+
self._protocol.error_received(exc)
|
| 1068 |
+
return
|
| 1069 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1070 |
+
raise
|
| 1071 |
+
except BaseException as exc:
|
| 1072 |
+
self._fatal_error(
|
| 1073 |
+
exc, 'Fatal write error on datagram transport')
|
| 1074 |
+
return
|
| 1075 |
+
|
| 1076 |
+
# Ensure that what we buffer is immutable.
|
| 1077 |
+
self._buffer.append((bytes(data), addr))
|
| 1078 |
+
self._maybe_pause_protocol()
|
| 1079 |
+
|
| 1080 |
+
def _sendto_ready(self):
|
| 1081 |
+
while self._buffer:
|
| 1082 |
+
data, addr = self._buffer.popleft()
|
| 1083 |
+
try:
|
| 1084 |
+
if self._extra['peername']:
|
| 1085 |
+
self._sock.send(data)
|
| 1086 |
+
else:
|
| 1087 |
+
self._sock.sendto(data, addr)
|
| 1088 |
+
except (BlockingIOError, InterruptedError):
|
| 1089 |
+
self._buffer.appendleft((data, addr)) # Try again later.
|
| 1090 |
+
break
|
| 1091 |
+
except OSError as exc:
|
| 1092 |
+
self._protocol.error_received(exc)
|
| 1093 |
+
return
|
| 1094 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1095 |
+
raise
|
| 1096 |
+
except BaseException as exc:
|
| 1097 |
+
self._fatal_error(
|
| 1098 |
+
exc, 'Fatal write error on datagram transport')
|
| 1099 |
+
return
|
| 1100 |
+
|
| 1101 |
+
self._maybe_resume_protocol() # May append to buffer.
|
| 1102 |
+
if not self._buffer:
|
| 1103 |
+
self._loop._remove_writer(self._sock_fd)
|
| 1104 |
+
if self._closing:
|
| 1105 |
+
self._call_connection_lost(None)
|
parrot/lib/python3.10/asyncio/subprocess.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__all__ = 'create_subprocess_exec', 'create_subprocess_shell'
|
| 2 |
+
|
| 3 |
+
import subprocess
|
| 4 |
+
|
| 5 |
+
from . import events
|
| 6 |
+
from . import protocols
|
| 7 |
+
from . import streams
|
| 8 |
+
from . import tasks
|
| 9 |
+
from .log import logger
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
PIPE = subprocess.PIPE
|
| 13 |
+
STDOUT = subprocess.STDOUT
|
| 14 |
+
DEVNULL = subprocess.DEVNULL
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class SubprocessStreamProtocol(streams.FlowControlMixin,
|
| 18 |
+
protocols.SubprocessProtocol):
|
| 19 |
+
"""Like StreamReaderProtocol, but for a subprocess."""
|
| 20 |
+
|
| 21 |
+
def __init__(self, limit, loop):
|
| 22 |
+
super().__init__(loop=loop)
|
| 23 |
+
self._limit = limit
|
| 24 |
+
self.stdin = self.stdout = self.stderr = None
|
| 25 |
+
self._transport = None
|
| 26 |
+
self._process_exited = False
|
| 27 |
+
self._pipe_fds = []
|
| 28 |
+
self._stdin_closed = self._loop.create_future()
|
| 29 |
+
|
| 30 |
+
def __repr__(self):
|
| 31 |
+
info = [self.__class__.__name__]
|
| 32 |
+
if self.stdin is not None:
|
| 33 |
+
info.append(f'stdin={self.stdin!r}')
|
| 34 |
+
if self.stdout is not None:
|
| 35 |
+
info.append(f'stdout={self.stdout!r}')
|
| 36 |
+
if self.stderr is not None:
|
| 37 |
+
info.append(f'stderr={self.stderr!r}')
|
| 38 |
+
return '<{}>'.format(' '.join(info))
|
| 39 |
+
|
| 40 |
+
def connection_made(self, transport):
|
| 41 |
+
self._transport = transport
|
| 42 |
+
|
| 43 |
+
stdout_transport = transport.get_pipe_transport(1)
|
| 44 |
+
if stdout_transport is not None:
|
| 45 |
+
self.stdout = streams.StreamReader(limit=self._limit,
|
| 46 |
+
loop=self._loop)
|
| 47 |
+
self.stdout.set_transport(stdout_transport)
|
| 48 |
+
self._pipe_fds.append(1)
|
| 49 |
+
|
| 50 |
+
stderr_transport = transport.get_pipe_transport(2)
|
| 51 |
+
if stderr_transport is not None:
|
| 52 |
+
self.stderr = streams.StreamReader(limit=self._limit,
|
| 53 |
+
loop=self._loop)
|
| 54 |
+
self.stderr.set_transport(stderr_transport)
|
| 55 |
+
self._pipe_fds.append(2)
|
| 56 |
+
|
| 57 |
+
stdin_transport = transport.get_pipe_transport(0)
|
| 58 |
+
if stdin_transport is not None:
|
| 59 |
+
self.stdin = streams.StreamWriter(stdin_transport,
|
| 60 |
+
protocol=self,
|
| 61 |
+
reader=None,
|
| 62 |
+
loop=self._loop)
|
| 63 |
+
|
| 64 |
+
def pipe_data_received(self, fd, data):
|
| 65 |
+
if fd == 1:
|
| 66 |
+
reader = self.stdout
|
| 67 |
+
elif fd == 2:
|
| 68 |
+
reader = self.stderr
|
| 69 |
+
else:
|
| 70 |
+
reader = None
|
| 71 |
+
if reader is not None:
|
| 72 |
+
reader.feed_data(data)
|
| 73 |
+
|
| 74 |
+
def pipe_connection_lost(self, fd, exc):
|
| 75 |
+
if fd == 0:
|
| 76 |
+
pipe = self.stdin
|
| 77 |
+
if pipe is not None:
|
| 78 |
+
pipe.close()
|
| 79 |
+
self.connection_lost(exc)
|
| 80 |
+
if exc is None:
|
| 81 |
+
self._stdin_closed.set_result(None)
|
| 82 |
+
else:
|
| 83 |
+
self._stdin_closed.set_exception(exc)
|
| 84 |
+
return
|
| 85 |
+
if fd == 1:
|
| 86 |
+
reader = self.stdout
|
| 87 |
+
elif fd == 2:
|
| 88 |
+
reader = self.stderr
|
| 89 |
+
else:
|
| 90 |
+
reader = None
|
| 91 |
+
if reader is not None:
|
| 92 |
+
if exc is None:
|
| 93 |
+
reader.feed_eof()
|
| 94 |
+
else:
|
| 95 |
+
reader.set_exception(exc)
|
| 96 |
+
|
| 97 |
+
if fd in self._pipe_fds:
|
| 98 |
+
self._pipe_fds.remove(fd)
|
| 99 |
+
self._maybe_close_transport()
|
| 100 |
+
|
| 101 |
+
def process_exited(self):
|
| 102 |
+
self._process_exited = True
|
| 103 |
+
self._maybe_close_transport()
|
| 104 |
+
|
| 105 |
+
def _maybe_close_transport(self):
|
| 106 |
+
if len(self._pipe_fds) == 0 and self._process_exited:
|
| 107 |
+
self._transport.close()
|
| 108 |
+
self._transport = None
|
| 109 |
+
|
| 110 |
+
def _get_close_waiter(self, stream):
|
| 111 |
+
if stream is self.stdin:
|
| 112 |
+
return self._stdin_closed
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class Process:
|
| 116 |
+
def __init__(self, transport, protocol, loop):
|
| 117 |
+
self._transport = transport
|
| 118 |
+
self._protocol = protocol
|
| 119 |
+
self._loop = loop
|
| 120 |
+
self.stdin = protocol.stdin
|
| 121 |
+
self.stdout = protocol.stdout
|
| 122 |
+
self.stderr = protocol.stderr
|
| 123 |
+
self.pid = transport.get_pid()
|
| 124 |
+
|
| 125 |
+
def __repr__(self):
|
| 126 |
+
return f'<{self.__class__.__name__} {self.pid}>'
|
| 127 |
+
|
| 128 |
+
@property
|
| 129 |
+
def returncode(self):
|
| 130 |
+
return self._transport.get_returncode()
|
| 131 |
+
|
| 132 |
+
async def wait(self):
|
| 133 |
+
"""Wait until the process exit and return the process return code."""
|
| 134 |
+
return await self._transport._wait()
|
| 135 |
+
|
| 136 |
+
def send_signal(self, signal):
|
| 137 |
+
self._transport.send_signal(signal)
|
| 138 |
+
|
| 139 |
+
def terminate(self):
|
| 140 |
+
self._transport.terminate()
|
| 141 |
+
|
| 142 |
+
def kill(self):
|
| 143 |
+
self._transport.kill()
|
| 144 |
+
|
| 145 |
+
async def _feed_stdin(self, input):
|
| 146 |
+
debug = self._loop.get_debug()
|
| 147 |
+
self.stdin.write(input)
|
| 148 |
+
if debug:
|
| 149 |
+
logger.debug(
|
| 150 |
+
'%r communicate: feed stdin (%s bytes)', self, len(input))
|
| 151 |
+
try:
|
| 152 |
+
await self.stdin.drain()
|
| 153 |
+
except (BrokenPipeError, ConnectionResetError) as exc:
|
| 154 |
+
# communicate() ignores BrokenPipeError and ConnectionResetError
|
| 155 |
+
if debug:
|
| 156 |
+
logger.debug('%r communicate: stdin got %r', self, exc)
|
| 157 |
+
|
| 158 |
+
if debug:
|
| 159 |
+
logger.debug('%r communicate: close stdin', self)
|
| 160 |
+
self.stdin.close()
|
| 161 |
+
|
| 162 |
+
async def _noop(self):
|
| 163 |
+
return None
|
| 164 |
+
|
| 165 |
+
async def _read_stream(self, fd):
|
| 166 |
+
transport = self._transport.get_pipe_transport(fd)
|
| 167 |
+
if fd == 2:
|
| 168 |
+
stream = self.stderr
|
| 169 |
+
else:
|
| 170 |
+
assert fd == 1
|
| 171 |
+
stream = self.stdout
|
| 172 |
+
if self._loop.get_debug():
|
| 173 |
+
name = 'stdout' if fd == 1 else 'stderr'
|
| 174 |
+
logger.debug('%r communicate: read %s', self, name)
|
| 175 |
+
output = await stream.read()
|
| 176 |
+
if self._loop.get_debug():
|
| 177 |
+
name = 'stdout' if fd == 1 else 'stderr'
|
| 178 |
+
logger.debug('%r communicate: close %s', self, name)
|
| 179 |
+
transport.close()
|
| 180 |
+
return output
|
| 181 |
+
|
| 182 |
+
async def communicate(self, input=None):
|
| 183 |
+
if input is not None:
|
| 184 |
+
stdin = self._feed_stdin(input)
|
| 185 |
+
else:
|
| 186 |
+
stdin = self._noop()
|
| 187 |
+
if self.stdout is not None:
|
| 188 |
+
stdout = self._read_stream(1)
|
| 189 |
+
else:
|
| 190 |
+
stdout = self._noop()
|
| 191 |
+
if self.stderr is not None:
|
| 192 |
+
stderr = self._read_stream(2)
|
| 193 |
+
else:
|
| 194 |
+
stderr = self._noop()
|
| 195 |
+
stdin, stdout, stderr = await tasks.gather(stdin, stdout, stderr)
|
| 196 |
+
await self.wait()
|
| 197 |
+
return (stdout, stderr)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
async def create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None,
|
| 201 |
+
limit=streams._DEFAULT_LIMIT, **kwds):
|
| 202 |
+
loop = events.get_running_loop()
|
| 203 |
+
protocol_factory = lambda: SubprocessStreamProtocol(limit=limit,
|
| 204 |
+
loop=loop)
|
| 205 |
+
transport, protocol = await loop.subprocess_shell(
|
| 206 |
+
protocol_factory,
|
| 207 |
+
cmd, stdin=stdin, stdout=stdout,
|
| 208 |
+
stderr=stderr, **kwds)
|
| 209 |
+
return Process(transport, protocol, loop)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
async def create_subprocess_exec(program, *args, stdin=None, stdout=None,
|
| 213 |
+
stderr=None, limit=streams._DEFAULT_LIMIT,
|
| 214 |
+
**kwds):
|
| 215 |
+
loop = events.get_running_loop()
|
| 216 |
+
protocol_factory = lambda: SubprocessStreamProtocol(limit=limit,
|
| 217 |
+
loop=loop)
|
| 218 |
+
transport, protocol = await loop.subprocess_exec(
|
| 219 |
+
protocol_factory,
|
| 220 |
+
program, *args,
|
| 221 |
+
stdin=stdin, stdout=stdout,
|
| 222 |
+
stderr=stderr, **kwds)
|
| 223 |
+
return Process(transport, protocol, loop)
|
parrot/lib/python3.10/asyncio/tasks.py
ADDED
|
@@ -0,0 +1,946 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Support for tasks, coroutines and the scheduler."""
|
| 2 |
+
|
| 3 |
+
__all__ = (
|
| 4 |
+
'Task', 'create_task',
|
| 5 |
+
'FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED',
|
| 6 |
+
'wait', 'wait_for', 'as_completed', 'sleep',
|
| 7 |
+
'gather', 'shield', 'ensure_future', 'run_coroutine_threadsafe',
|
| 8 |
+
'current_task', 'all_tasks',
|
| 9 |
+
'_register_task', '_unregister_task', '_enter_task', '_leave_task',
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
import concurrent.futures
|
| 13 |
+
import contextvars
|
| 14 |
+
import functools
|
| 15 |
+
import inspect
|
| 16 |
+
import itertools
|
| 17 |
+
import types
|
| 18 |
+
import warnings
|
| 19 |
+
import weakref
|
| 20 |
+
from types import GenericAlias
|
| 21 |
+
|
| 22 |
+
from . import base_tasks
|
| 23 |
+
from . import coroutines
|
| 24 |
+
from . import events
|
| 25 |
+
from . import exceptions
|
| 26 |
+
from . import futures
|
| 27 |
+
from .coroutines import _is_coroutine
|
| 28 |
+
|
| 29 |
+
# Helper to generate new task names
|
| 30 |
+
# This uses itertools.count() instead of a "+= 1" operation because the latter
|
| 31 |
+
# is not thread safe. See bpo-11866 for a longer explanation.
|
| 32 |
+
_task_name_counter = itertools.count(1).__next__
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def current_task(loop=None):
|
| 36 |
+
"""Return a currently executed task."""
|
| 37 |
+
if loop is None:
|
| 38 |
+
loop = events.get_running_loop()
|
| 39 |
+
return _current_tasks.get(loop)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def all_tasks(loop=None):
|
| 43 |
+
"""Return a set of all tasks for the loop."""
|
| 44 |
+
if loop is None:
|
| 45 |
+
loop = events.get_running_loop()
|
| 46 |
+
# Looping over a WeakSet (_all_tasks) isn't safe as it can be updated from another
|
| 47 |
+
# thread while we do so. Therefore we cast it to list prior to filtering. The list
|
| 48 |
+
# cast itself requires iteration, so we repeat it several times ignoring
|
| 49 |
+
# RuntimeErrors (which are not very likely to occur). See issues 34970 and 36607 for
|
| 50 |
+
# details.
|
| 51 |
+
i = 0
|
| 52 |
+
while True:
|
| 53 |
+
try:
|
| 54 |
+
tasks = list(_all_tasks)
|
| 55 |
+
except RuntimeError:
|
| 56 |
+
i += 1
|
| 57 |
+
if i >= 1000:
|
| 58 |
+
raise
|
| 59 |
+
else:
|
| 60 |
+
break
|
| 61 |
+
return {t for t in tasks
|
| 62 |
+
if futures._get_loop(t) is loop and not t.done()}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _set_task_name(task, name):
|
| 66 |
+
if name is not None:
|
| 67 |
+
try:
|
| 68 |
+
set_name = task.set_name
|
| 69 |
+
except AttributeError:
|
| 70 |
+
pass
|
| 71 |
+
else:
|
| 72 |
+
set_name(name)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class Task(futures._PyFuture): # Inherit Python Task implementation
|
| 76 |
+
# from a Python Future implementation.
|
| 77 |
+
|
| 78 |
+
"""A coroutine wrapped in a Future."""
|
| 79 |
+
|
| 80 |
+
# An important invariant maintained while a Task not done:
|
| 81 |
+
#
|
| 82 |
+
# - Either _fut_waiter is None, and _step() is scheduled;
|
| 83 |
+
# - or _fut_waiter is some Future, and _step() is *not* scheduled.
|
| 84 |
+
#
|
| 85 |
+
# The only transition from the latter to the former is through
|
| 86 |
+
# _wakeup(). When _fut_waiter is not None, one of its callbacks
|
| 87 |
+
# must be _wakeup().
|
| 88 |
+
|
| 89 |
+
# If False, don't log a message if the task is destroyed whereas its
|
| 90 |
+
# status is still pending
|
| 91 |
+
_log_destroy_pending = True
|
| 92 |
+
|
| 93 |
+
def __init__(self, coro, *, loop=None, name=None):
|
| 94 |
+
super().__init__(loop=loop)
|
| 95 |
+
if self._source_traceback:
|
| 96 |
+
del self._source_traceback[-1]
|
| 97 |
+
if not coroutines.iscoroutine(coro):
|
| 98 |
+
# raise after Future.__init__(), attrs are required for __del__
|
| 99 |
+
# prevent logging for pending task in __del__
|
| 100 |
+
self._log_destroy_pending = False
|
| 101 |
+
raise TypeError(f"a coroutine was expected, got {coro!r}")
|
| 102 |
+
|
| 103 |
+
if name is None:
|
| 104 |
+
self._name = f'Task-{_task_name_counter()}'
|
| 105 |
+
else:
|
| 106 |
+
self._name = str(name)
|
| 107 |
+
|
| 108 |
+
self._must_cancel = False
|
| 109 |
+
self._fut_waiter = None
|
| 110 |
+
self._coro = coro
|
| 111 |
+
self._context = contextvars.copy_context()
|
| 112 |
+
|
| 113 |
+
self._loop.call_soon(self.__step, context=self._context)
|
| 114 |
+
_register_task(self)
|
| 115 |
+
|
| 116 |
+
def __del__(self):
|
| 117 |
+
if self._state == futures._PENDING and self._log_destroy_pending:
|
| 118 |
+
context = {
|
| 119 |
+
'task': self,
|
| 120 |
+
'message': 'Task was destroyed but it is pending!',
|
| 121 |
+
}
|
| 122 |
+
if self._source_traceback:
|
| 123 |
+
context['source_traceback'] = self._source_traceback
|
| 124 |
+
self._loop.call_exception_handler(context)
|
| 125 |
+
super().__del__()
|
| 126 |
+
|
| 127 |
+
__class_getitem__ = classmethod(GenericAlias)
|
| 128 |
+
|
| 129 |
+
def _repr_info(self):
|
| 130 |
+
return base_tasks._task_repr_info(self)
|
| 131 |
+
|
| 132 |
+
def get_coro(self):
|
| 133 |
+
return self._coro
|
| 134 |
+
|
| 135 |
+
def get_name(self):
|
| 136 |
+
return self._name
|
| 137 |
+
|
| 138 |
+
def set_name(self, value):
|
| 139 |
+
self._name = str(value)
|
| 140 |
+
|
| 141 |
+
def set_result(self, result):
|
| 142 |
+
raise RuntimeError('Task does not support set_result operation')
|
| 143 |
+
|
| 144 |
+
def set_exception(self, exception):
|
| 145 |
+
raise RuntimeError('Task does not support set_exception operation')
|
| 146 |
+
|
| 147 |
+
def get_stack(self, *, limit=None):
|
| 148 |
+
"""Return the list of stack frames for this task's coroutine.
|
| 149 |
+
|
| 150 |
+
If the coroutine is not done, this returns the stack where it is
|
| 151 |
+
suspended. If the coroutine has completed successfully or was
|
| 152 |
+
cancelled, this returns an empty list. If the coroutine was
|
| 153 |
+
terminated by an exception, this returns the list of traceback
|
| 154 |
+
frames.
|
| 155 |
+
|
| 156 |
+
The frames are always ordered from oldest to newest.
|
| 157 |
+
|
| 158 |
+
The optional limit gives the maximum number of frames to
|
| 159 |
+
return; by default all available frames are returned. Its
|
| 160 |
+
meaning differs depending on whether a stack or a traceback is
|
| 161 |
+
returned: the newest frames of a stack are returned, but the
|
| 162 |
+
oldest frames of a traceback are returned. (This matches the
|
| 163 |
+
behavior of the traceback module.)
|
| 164 |
+
|
| 165 |
+
For reasons beyond our control, only one stack frame is
|
| 166 |
+
returned for a suspended coroutine.
|
| 167 |
+
"""
|
| 168 |
+
return base_tasks._task_get_stack(self, limit)
|
| 169 |
+
|
| 170 |
+
def print_stack(self, *, limit=None, file=None):
|
| 171 |
+
"""Print the stack or traceback for this task's coroutine.
|
| 172 |
+
|
| 173 |
+
This produces output similar to that of the traceback module,
|
| 174 |
+
for the frames retrieved by get_stack(). The limit argument
|
| 175 |
+
is passed to get_stack(). The file argument is an I/O stream
|
| 176 |
+
to which the output is written; by default output is written
|
| 177 |
+
to sys.stderr.
|
| 178 |
+
"""
|
| 179 |
+
return base_tasks._task_print_stack(self, limit, file)
|
| 180 |
+
|
| 181 |
+
def cancel(self, msg=None):
|
| 182 |
+
"""Request that this task cancel itself.
|
| 183 |
+
|
| 184 |
+
This arranges for a CancelledError to be thrown into the
|
| 185 |
+
wrapped coroutine on the next cycle through the event loop.
|
| 186 |
+
The coroutine then has a chance to clean up or even deny
|
| 187 |
+
the request using try/except/finally.
|
| 188 |
+
|
| 189 |
+
Unlike Future.cancel, this does not guarantee that the
|
| 190 |
+
task will be cancelled: the exception might be caught and
|
| 191 |
+
acted upon, delaying cancellation of the task or preventing
|
| 192 |
+
cancellation completely. The task may also return a value or
|
| 193 |
+
raise a different exception.
|
| 194 |
+
|
| 195 |
+
Immediately after this method is called, Task.cancelled() will
|
| 196 |
+
not return True (unless the task was already cancelled). A
|
| 197 |
+
task will be marked as cancelled when the wrapped coroutine
|
| 198 |
+
terminates with a CancelledError exception (even if cancel()
|
| 199 |
+
was not called).
|
| 200 |
+
"""
|
| 201 |
+
self._log_traceback = False
|
| 202 |
+
if self.done():
|
| 203 |
+
return False
|
| 204 |
+
if self._fut_waiter is not None:
|
| 205 |
+
if self._fut_waiter.cancel(msg=msg):
|
| 206 |
+
# Leave self._fut_waiter; it may be a Task that
|
| 207 |
+
# catches and ignores the cancellation so we may have
|
| 208 |
+
# to cancel it again later.
|
| 209 |
+
return True
|
| 210 |
+
# It must be the case that self.__step is already scheduled.
|
| 211 |
+
self._must_cancel = True
|
| 212 |
+
self._cancel_message = msg
|
| 213 |
+
return True
|
| 214 |
+
|
| 215 |
+
def __step(self, exc=None):
|
| 216 |
+
if self.done():
|
| 217 |
+
raise exceptions.InvalidStateError(
|
| 218 |
+
f'_step(): already done: {self!r}, {exc!r}')
|
| 219 |
+
if self._must_cancel:
|
| 220 |
+
if not isinstance(exc, exceptions.CancelledError):
|
| 221 |
+
exc = self._make_cancelled_error()
|
| 222 |
+
self._must_cancel = False
|
| 223 |
+
coro = self._coro
|
| 224 |
+
self._fut_waiter = None
|
| 225 |
+
|
| 226 |
+
_enter_task(self._loop, self)
|
| 227 |
+
# Call either coro.throw(exc) or coro.send(None).
|
| 228 |
+
try:
|
| 229 |
+
if exc is None:
|
| 230 |
+
# We use the `send` method directly, because coroutines
|
| 231 |
+
# don't have `__iter__` and `__next__` methods.
|
| 232 |
+
result = coro.send(None)
|
| 233 |
+
else:
|
| 234 |
+
result = coro.throw(exc)
|
| 235 |
+
except StopIteration as exc:
|
| 236 |
+
if self._must_cancel:
|
| 237 |
+
# Task is cancelled right before coro stops.
|
| 238 |
+
self._must_cancel = False
|
| 239 |
+
super().cancel(msg=self._cancel_message)
|
| 240 |
+
else:
|
| 241 |
+
super().set_result(exc.value)
|
| 242 |
+
except exceptions.CancelledError as exc:
|
| 243 |
+
# Save the original exception so we can chain it later.
|
| 244 |
+
self._cancelled_exc = exc
|
| 245 |
+
super().cancel() # I.e., Future.cancel(self).
|
| 246 |
+
except (KeyboardInterrupt, SystemExit) as exc:
|
| 247 |
+
super().set_exception(exc)
|
| 248 |
+
raise
|
| 249 |
+
except BaseException as exc:
|
| 250 |
+
super().set_exception(exc)
|
| 251 |
+
else:
|
| 252 |
+
blocking = getattr(result, '_asyncio_future_blocking', None)
|
| 253 |
+
if blocking is not None:
|
| 254 |
+
# Yielded Future must come from Future.__iter__().
|
| 255 |
+
if futures._get_loop(result) is not self._loop:
|
| 256 |
+
new_exc = RuntimeError(
|
| 257 |
+
f'Task {self!r} got Future '
|
| 258 |
+
f'{result!r} attached to a different loop')
|
| 259 |
+
self._loop.call_soon(
|
| 260 |
+
self.__step, new_exc, context=self._context)
|
| 261 |
+
elif blocking:
|
| 262 |
+
if result is self:
|
| 263 |
+
new_exc = RuntimeError(
|
| 264 |
+
f'Task cannot await on itself: {self!r}')
|
| 265 |
+
self._loop.call_soon(
|
| 266 |
+
self.__step, new_exc, context=self._context)
|
| 267 |
+
else:
|
| 268 |
+
result._asyncio_future_blocking = False
|
| 269 |
+
result.add_done_callback(
|
| 270 |
+
self.__wakeup, context=self._context)
|
| 271 |
+
self._fut_waiter = result
|
| 272 |
+
if self._must_cancel:
|
| 273 |
+
if self._fut_waiter.cancel(
|
| 274 |
+
msg=self._cancel_message):
|
| 275 |
+
self._must_cancel = False
|
| 276 |
+
else:
|
| 277 |
+
new_exc = RuntimeError(
|
| 278 |
+
f'yield was used instead of yield from '
|
| 279 |
+
f'in task {self!r} with {result!r}')
|
| 280 |
+
self._loop.call_soon(
|
| 281 |
+
self.__step, new_exc, context=self._context)
|
| 282 |
+
|
| 283 |
+
elif result is None:
|
| 284 |
+
# Bare yield relinquishes control for one event loop iteration.
|
| 285 |
+
self._loop.call_soon(self.__step, context=self._context)
|
| 286 |
+
elif inspect.isgenerator(result):
|
| 287 |
+
# Yielding a generator is just wrong.
|
| 288 |
+
new_exc = RuntimeError(
|
| 289 |
+
f'yield was used instead of yield from for '
|
| 290 |
+
f'generator in task {self!r} with {result!r}')
|
| 291 |
+
self._loop.call_soon(
|
| 292 |
+
self.__step, new_exc, context=self._context)
|
| 293 |
+
else:
|
| 294 |
+
# Yielding something else is an error.
|
| 295 |
+
new_exc = RuntimeError(f'Task got bad yield: {result!r}')
|
| 296 |
+
self._loop.call_soon(
|
| 297 |
+
self.__step, new_exc, context=self._context)
|
| 298 |
+
finally:
|
| 299 |
+
_leave_task(self._loop, self)
|
| 300 |
+
self = None # Needed to break cycles when an exception occurs.
|
| 301 |
+
|
| 302 |
+
def __wakeup(self, future):
|
| 303 |
+
try:
|
| 304 |
+
future.result()
|
| 305 |
+
except BaseException as exc:
|
| 306 |
+
# This may also be a cancellation.
|
| 307 |
+
self.__step(exc)
|
| 308 |
+
else:
|
| 309 |
+
# Don't pass the value of `future.result()` explicitly,
|
| 310 |
+
# as `Future.__iter__` and `Future.__await__` don't need it.
|
| 311 |
+
# If we call `_step(value, None)` instead of `_step()`,
|
| 312 |
+
# Python eval loop would use `.send(value)` method call,
|
| 313 |
+
# instead of `__next__()`, which is slower for futures
|
| 314 |
+
# that return non-generator iterators from their `__iter__`.
|
| 315 |
+
self.__step()
|
| 316 |
+
self = None # Needed to break cycles when an exception occurs.
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
_PyTask = Task
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
try:
|
| 323 |
+
import _asyncio
|
| 324 |
+
except ImportError:
|
| 325 |
+
pass
|
| 326 |
+
else:
|
| 327 |
+
# _CTask is needed for tests.
|
| 328 |
+
Task = _CTask = _asyncio.Task
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def create_task(coro, *, name=None):
|
| 332 |
+
"""Schedule the execution of a coroutine object in a spawn task.
|
| 333 |
+
|
| 334 |
+
Return a Task object.
|
| 335 |
+
"""
|
| 336 |
+
loop = events.get_running_loop()
|
| 337 |
+
task = loop.create_task(coro)
|
| 338 |
+
_set_task_name(task, name)
|
| 339 |
+
return task
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
# wait() and as_completed() similar to those in PEP 3148.
|
| 343 |
+
|
| 344 |
+
FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED
|
| 345 |
+
FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION
|
| 346 |
+
ALL_COMPLETED = concurrent.futures.ALL_COMPLETED
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
async def wait(fs, *, timeout=None, return_when=ALL_COMPLETED):
|
| 350 |
+
"""Wait for the Futures and coroutines given by fs to complete.
|
| 351 |
+
|
| 352 |
+
The fs iterable must not be empty.
|
| 353 |
+
|
| 354 |
+
Coroutines will be wrapped in Tasks.
|
| 355 |
+
|
| 356 |
+
Returns two sets of Future: (done, pending).
|
| 357 |
+
|
| 358 |
+
Usage:
|
| 359 |
+
|
| 360 |
+
done, pending = await asyncio.wait(fs)
|
| 361 |
+
|
| 362 |
+
Note: This does not raise TimeoutError! Futures that aren't done
|
| 363 |
+
when the timeout occurs are returned in the second set.
|
| 364 |
+
"""
|
| 365 |
+
if futures.isfuture(fs) or coroutines.iscoroutine(fs):
|
| 366 |
+
raise TypeError(f"expect a list of futures, not {type(fs).__name__}")
|
| 367 |
+
if not fs:
|
| 368 |
+
raise ValueError('Set of coroutines/Futures is empty.')
|
| 369 |
+
if return_when not in (FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED):
|
| 370 |
+
raise ValueError(f'Invalid return_when value: {return_when}')
|
| 371 |
+
|
| 372 |
+
loop = events.get_running_loop()
|
| 373 |
+
|
| 374 |
+
fs = set(fs)
|
| 375 |
+
|
| 376 |
+
if any(coroutines.iscoroutine(f) for f in fs):
|
| 377 |
+
warnings.warn("The explicit passing of coroutine objects to "
|
| 378 |
+
"asyncio.wait() is deprecated since Python 3.8, and "
|
| 379 |
+
"scheduled for removal in Python 3.11.",
|
| 380 |
+
DeprecationWarning, stacklevel=2)
|
| 381 |
+
|
| 382 |
+
fs = {ensure_future(f, loop=loop) for f in fs}
|
| 383 |
+
|
| 384 |
+
return await _wait(fs, timeout, return_when, loop)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def _release_waiter(waiter, *args):
|
| 388 |
+
if not waiter.done():
|
| 389 |
+
waiter.set_result(None)
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
async def wait_for(fut, timeout):
|
| 393 |
+
"""Wait for the single Future or coroutine to complete, with timeout.
|
| 394 |
+
|
| 395 |
+
Coroutine will be wrapped in Task.
|
| 396 |
+
|
| 397 |
+
Returns result of the Future or coroutine. When a timeout occurs,
|
| 398 |
+
it cancels the task and raises TimeoutError. To avoid the task
|
| 399 |
+
cancellation, wrap it in shield().
|
| 400 |
+
|
| 401 |
+
If the wait is cancelled, the task is also cancelled.
|
| 402 |
+
|
| 403 |
+
This function is a coroutine.
|
| 404 |
+
"""
|
| 405 |
+
loop = events.get_running_loop()
|
| 406 |
+
|
| 407 |
+
if timeout is None:
|
| 408 |
+
return await fut
|
| 409 |
+
|
| 410 |
+
if timeout <= 0:
|
| 411 |
+
fut = ensure_future(fut, loop=loop)
|
| 412 |
+
|
| 413 |
+
if fut.done():
|
| 414 |
+
return fut.result()
|
| 415 |
+
|
| 416 |
+
await _cancel_and_wait(fut, loop=loop)
|
| 417 |
+
try:
|
| 418 |
+
return fut.result()
|
| 419 |
+
except exceptions.CancelledError as exc:
|
| 420 |
+
raise exceptions.TimeoutError() from exc
|
| 421 |
+
|
| 422 |
+
waiter = loop.create_future()
|
| 423 |
+
timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
|
| 424 |
+
cb = functools.partial(_release_waiter, waiter)
|
| 425 |
+
|
| 426 |
+
fut = ensure_future(fut, loop=loop)
|
| 427 |
+
fut.add_done_callback(cb)
|
| 428 |
+
|
| 429 |
+
try:
|
| 430 |
+
# wait until the future completes or the timeout
|
| 431 |
+
try:
|
| 432 |
+
await waiter
|
| 433 |
+
except exceptions.CancelledError:
|
| 434 |
+
if fut.done():
|
| 435 |
+
return fut.result()
|
| 436 |
+
else:
|
| 437 |
+
fut.remove_done_callback(cb)
|
| 438 |
+
# We must ensure that the task is not running
|
| 439 |
+
# after wait_for() returns.
|
| 440 |
+
# See https://bugs.python.org/issue32751
|
| 441 |
+
await _cancel_and_wait(fut, loop=loop)
|
| 442 |
+
raise
|
| 443 |
+
|
| 444 |
+
if fut.done():
|
| 445 |
+
return fut.result()
|
| 446 |
+
else:
|
| 447 |
+
fut.remove_done_callback(cb)
|
| 448 |
+
# We must ensure that the task is not running
|
| 449 |
+
# after wait_for() returns.
|
| 450 |
+
# See https://bugs.python.org/issue32751
|
| 451 |
+
await _cancel_and_wait(fut, loop=loop)
|
| 452 |
+
# In case task cancellation failed with some
|
| 453 |
+
# exception, we should re-raise it
|
| 454 |
+
# See https://bugs.python.org/issue40607
|
| 455 |
+
try:
|
| 456 |
+
return fut.result()
|
| 457 |
+
except exceptions.CancelledError as exc:
|
| 458 |
+
raise exceptions.TimeoutError() from exc
|
| 459 |
+
finally:
|
| 460 |
+
timeout_handle.cancel()
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
async def _wait(fs, timeout, return_when, loop):
|
| 464 |
+
"""Internal helper for wait().
|
| 465 |
+
|
| 466 |
+
The fs argument must be a collection of Futures.
|
| 467 |
+
"""
|
| 468 |
+
assert fs, 'Set of Futures is empty.'
|
| 469 |
+
waiter = loop.create_future()
|
| 470 |
+
timeout_handle = None
|
| 471 |
+
if timeout is not None:
|
| 472 |
+
timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
|
| 473 |
+
counter = len(fs)
|
| 474 |
+
|
| 475 |
+
def _on_completion(f):
|
| 476 |
+
nonlocal counter
|
| 477 |
+
counter -= 1
|
| 478 |
+
if (counter <= 0 or
|
| 479 |
+
return_when == FIRST_COMPLETED or
|
| 480 |
+
return_when == FIRST_EXCEPTION and (not f.cancelled() and
|
| 481 |
+
f.exception() is not None)):
|
| 482 |
+
if timeout_handle is not None:
|
| 483 |
+
timeout_handle.cancel()
|
| 484 |
+
if not waiter.done():
|
| 485 |
+
waiter.set_result(None)
|
| 486 |
+
|
| 487 |
+
for f in fs:
|
| 488 |
+
f.add_done_callback(_on_completion)
|
| 489 |
+
|
| 490 |
+
try:
|
| 491 |
+
await waiter
|
| 492 |
+
finally:
|
| 493 |
+
if timeout_handle is not None:
|
| 494 |
+
timeout_handle.cancel()
|
| 495 |
+
for f in fs:
|
| 496 |
+
f.remove_done_callback(_on_completion)
|
| 497 |
+
|
| 498 |
+
done, pending = set(), set()
|
| 499 |
+
for f in fs:
|
| 500 |
+
if f.done():
|
| 501 |
+
done.add(f)
|
| 502 |
+
else:
|
| 503 |
+
pending.add(f)
|
| 504 |
+
return done, pending
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
async def _cancel_and_wait(fut, loop):
|
| 508 |
+
"""Cancel the *fut* future or task and wait until it completes."""
|
| 509 |
+
|
| 510 |
+
waiter = loop.create_future()
|
| 511 |
+
cb = functools.partial(_release_waiter, waiter)
|
| 512 |
+
fut.add_done_callback(cb)
|
| 513 |
+
|
| 514 |
+
try:
|
| 515 |
+
fut.cancel()
|
| 516 |
+
# We cannot wait on *fut* directly to make
|
| 517 |
+
# sure _cancel_and_wait itself is reliably cancellable.
|
| 518 |
+
await waiter
|
| 519 |
+
finally:
|
| 520 |
+
fut.remove_done_callback(cb)
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
# This is *not* a @coroutine! It is just an iterator (yielding Futures).
|
| 524 |
+
def as_completed(fs, *, timeout=None):
|
| 525 |
+
"""Return an iterator whose values are coroutines.
|
| 526 |
+
|
| 527 |
+
When waiting for the yielded coroutines you'll get the results (or
|
| 528 |
+
exceptions!) of the original Futures (or coroutines), in the order
|
| 529 |
+
in which and as soon as they complete.
|
| 530 |
+
|
| 531 |
+
This differs from PEP 3148; the proper way to use this is:
|
| 532 |
+
|
| 533 |
+
for f in as_completed(fs):
|
| 534 |
+
result = await f # The 'await' may raise.
|
| 535 |
+
# Use result.
|
| 536 |
+
|
| 537 |
+
If a timeout is specified, the 'await' will raise
|
| 538 |
+
TimeoutError when the timeout occurs before all Futures are done.
|
| 539 |
+
|
| 540 |
+
Note: The futures 'f' are not necessarily members of fs.
|
| 541 |
+
"""
|
| 542 |
+
if futures.isfuture(fs) or coroutines.iscoroutine(fs):
|
| 543 |
+
raise TypeError(f"expect an iterable of futures, not {type(fs).__name__}")
|
| 544 |
+
|
| 545 |
+
from .queues import Queue # Import here to avoid circular import problem.
|
| 546 |
+
done = Queue()
|
| 547 |
+
|
| 548 |
+
loop = events._get_event_loop()
|
| 549 |
+
todo = {ensure_future(f, loop=loop) for f in set(fs)}
|
| 550 |
+
timeout_handle = None
|
| 551 |
+
|
| 552 |
+
def _on_timeout():
|
| 553 |
+
for f in todo:
|
| 554 |
+
f.remove_done_callback(_on_completion)
|
| 555 |
+
done.put_nowait(None) # Queue a dummy value for _wait_for_one().
|
| 556 |
+
todo.clear() # Can't do todo.remove(f) in the loop.
|
| 557 |
+
|
| 558 |
+
def _on_completion(f):
|
| 559 |
+
if not todo:
|
| 560 |
+
return # _on_timeout() was here first.
|
| 561 |
+
todo.remove(f)
|
| 562 |
+
done.put_nowait(f)
|
| 563 |
+
if not todo and timeout_handle is not None:
|
| 564 |
+
timeout_handle.cancel()
|
| 565 |
+
|
| 566 |
+
async def _wait_for_one():
|
| 567 |
+
f = await done.get()
|
| 568 |
+
if f is None:
|
| 569 |
+
# Dummy value from _on_timeout().
|
| 570 |
+
raise exceptions.TimeoutError
|
| 571 |
+
return f.result() # May raise f.exception().
|
| 572 |
+
|
| 573 |
+
for f in todo:
|
| 574 |
+
f.add_done_callback(_on_completion)
|
| 575 |
+
if todo and timeout is not None:
|
| 576 |
+
timeout_handle = loop.call_later(timeout, _on_timeout)
|
| 577 |
+
for _ in range(len(todo)):
|
| 578 |
+
yield _wait_for_one()
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
@types.coroutine
|
| 582 |
+
def __sleep0():
|
| 583 |
+
"""Skip one event loop run cycle.
|
| 584 |
+
|
| 585 |
+
This is a private helper for 'asyncio.sleep()', used
|
| 586 |
+
when the 'delay' is set to 0. It uses a bare 'yield'
|
| 587 |
+
expression (which Task.__step knows how to handle)
|
| 588 |
+
instead of creating a Future object.
|
| 589 |
+
"""
|
| 590 |
+
yield
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
async def sleep(delay, result=None):
|
| 594 |
+
"""Coroutine that completes after a given time (in seconds)."""
|
| 595 |
+
if delay <= 0:
|
| 596 |
+
await __sleep0()
|
| 597 |
+
return result
|
| 598 |
+
|
| 599 |
+
loop = events.get_running_loop()
|
| 600 |
+
future = loop.create_future()
|
| 601 |
+
h = loop.call_later(delay,
|
| 602 |
+
futures._set_result_unless_cancelled,
|
| 603 |
+
future, result)
|
| 604 |
+
try:
|
| 605 |
+
return await future
|
| 606 |
+
finally:
|
| 607 |
+
h.cancel()
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def ensure_future(coro_or_future, *, loop=None):
|
| 611 |
+
"""Wrap a coroutine or an awaitable in a future.
|
| 612 |
+
|
| 613 |
+
If the argument is a Future, it is returned directly.
|
| 614 |
+
"""
|
| 615 |
+
return _ensure_future(coro_or_future, loop=loop)
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
def _ensure_future(coro_or_future, *, loop=None):
|
| 619 |
+
if futures.isfuture(coro_or_future):
|
| 620 |
+
if loop is not None and loop is not futures._get_loop(coro_or_future):
|
| 621 |
+
raise ValueError('The future belongs to a different loop than '
|
| 622 |
+
'the one specified as the loop argument')
|
| 623 |
+
return coro_or_future
|
| 624 |
+
called_wrap_awaitable = False
|
| 625 |
+
if not coroutines.iscoroutine(coro_or_future):
|
| 626 |
+
if inspect.isawaitable(coro_or_future):
|
| 627 |
+
coro_or_future = _wrap_awaitable(coro_or_future)
|
| 628 |
+
called_wrap_awaitable = True
|
| 629 |
+
else:
|
| 630 |
+
raise TypeError('An asyncio.Future, a coroutine or an awaitable '
|
| 631 |
+
'is required')
|
| 632 |
+
|
| 633 |
+
if loop is None:
|
| 634 |
+
loop = events._get_event_loop(stacklevel=4)
|
| 635 |
+
try:
|
| 636 |
+
return loop.create_task(coro_or_future)
|
| 637 |
+
except RuntimeError:
|
| 638 |
+
if not called_wrap_awaitable:
|
| 639 |
+
coro_or_future.close()
|
| 640 |
+
raise
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
@types.coroutine
|
| 644 |
+
def _wrap_awaitable(awaitable):
|
| 645 |
+
"""Helper for asyncio.ensure_future().
|
| 646 |
+
|
| 647 |
+
Wraps awaitable (an object with __await__) into a coroutine
|
| 648 |
+
that will later be wrapped in a Task by ensure_future().
|
| 649 |
+
"""
|
| 650 |
+
return (yield from awaitable.__await__())
|
| 651 |
+
|
| 652 |
+
_wrap_awaitable._is_coroutine = _is_coroutine
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
class _GatheringFuture(futures.Future):
|
| 656 |
+
"""Helper for gather().
|
| 657 |
+
|
| 658 |
+
This overrides cancel() to cancel all the children and act more
|
| 659 |
+
like Task.cancel(), which doesn't immediately mark itself as
|
| 660 |
+
cancelled.
|
| 661 |
+
"""
|
| 662 |
+
|
| 663 |
+
def __init__(self, children, *, loop):
|
| 664 |
+
assert loop is not None
|
| 665 |
+
super().__init__(loop=loop)
|
| 666 |
+
self._children = children
|
| 667 |
+
self._cancel_requested = False
|
| 668 |
+
|
| 669 |
+
def cancel(self, msg=None):
|
| 670 |
+
if self.done():
|
| 671 |
+
return False
|
| 672 |
+
ret = False
|
| 673 |
+
for child in self._children:
|
| 674 |
+
if child.cancel(msg=msg):
|
| 675 |
+
ret = True
|
| 676 |
+
if ret:
|
| 677 |
+
# If any child tasks were actually cancelled, we should
|
| 678 |
+
# propagate the cancellation request regardless of
|
| 679 |
+
# *return_exceptions* argument. See issue 32684.
|
| 680 |
+
self._cancel_requested = True
|
| 681 |
+
return ret
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def gather(*coros_or_futures, return_exceptions=False):
|
| 685 |
+
"""Return a future aggregating results from the given coroutines/futures.
|
| 686 |
+
|
| 687 |
+
Coroutines will be wrapped in a future and scheduled in the event
|
| 688 |
+
loop. They will not necessarily be scheduled in the same order as
|
| 689 |
+
passed in.
|
| 690 |
+
|
| 691 |
+
All futures must share the same event loop. If all the tasks are
|
| 692 |
+
done successfully, the returned future's result is the list of
|
| 693 |
+
results (in the order of the original sequence, not necessarily
|
| 694 |
+
the order of results arrival). If *return_exceptions* is True,
|
| 695 |
+
exceptions in the tasks are treated the same as successful
|
| 696 |
+
results, and gathered in the result list; otherwise, the first
|
| 697 |
+
raised exception will be immediately propagated to the returned
|
| 698 |
+
future.
|
| 699 |
+
|
| 700 |
+
Cancellation: if the outer Future is cancelled, all children (that
|
| 701 |
+
have not completed yet) are also cancelled. If any child is
|
| 702 |
+
cancelled, this is treated as if it raised CancelledError --
|
| 703 |
+
the outer Future is *not* cancelled in this case. (This is to
|
| 704 |
+
prevent the cancellation of one child to cause other children to
|
| 705 |
+
be cancelled.)
|
| 706 |
+
|
| 707 |
+
If *return_exceptions* is False, cancelling gather() after it
|
| 708 |
+
has been marked done won't cancel any submitted awaitables.
|
| 709 |
+
For instance, gather can be marked done after propagating an
|
| 710 |
+
exception to the caller, therefore, calling ``gather.cancel()``
|
| 711 |
+
after catching an exception (raised by one of the awaitables) from
|
| 712 |
+
gather won't cancel any other awaitables.
|
| 713 |
+
"""
|
| 714 |
+
if not coros_or_futures:
|
| 715 |
+
loop = events._get_event_loop()
|
| 716 |
+
outer = loop.create_future()
|
| 717 |
+
outer.set_result([])
|
| 718 |
+
return outer
|
| 719 |
+
|
| 720 |
+
def _done_callback(fut):
|
| 721 |
+
nonlocal nfinished
|
| 722 |
+
nfinished += 1
|
| 723 |
+
|
| 724 |
+
if outer is None or outer.done():
|
| 725 |
+
if not fut.cancelled():
|
| 726 |
+
# Mark exception retrieved.
|
| 727 |
+
fut.exception()
|
| 728 |
+
return
|
| 729 |
+
|
| 730 |
+
if not return_exceptions:
|
| 731 |
+
if fut.cancelled():
|
| 732 |
+
# Check if 'fut' is cancelled first, as
|
| 733 |
+
# 'fut.exception()' will *raise* a CancelledError
|
| 734 |
+
# instead of returning it.
|
| 735 |
+
exc = fut._make_cancelled_error()
|
| 736 |
+
outer.set_exception(exc)
|
| 737 |
+
return
|
| 738 |
+
else:
|
| 739 |
+
exc = fut.exception()
|
| 740 |
+
if exc is not None:
|
| 741 |
+
outer.set_exception(exc)
|
| 742 |
+
return
|
| 743 |
+
|
| 744 |
+
if nfinished == nfuts:
|
| 745 |
+
# All futures are done; create a list of results
|
| 746 |
+
# and set it to the 'outer' future.
|
| 747 |
+
results = []
|
| 748 |
+
|
| 749 |
+
for fut in children:
|
| 750 |
+
if fut.cancelled():
|
| 751 |
+
# Check if 'fut' is cancelled first, as 'fut.exception()'
|
| 752 |
+
# will *raise* a CancelledError instead of returning it.
|
| 753 |
+
# Also, since we're adding the exception return value
|
| 754 |
+
# to 'results' instead of raising it, don't bother
|
| 755 |
+
# setting __context__. This also lets us preserve
|
| 756 |
+
# calling '_make_cancelled_error()' at most once.
|
| 757 |
+
res = exceptions.CancelledError(
|
| 758 |
+
'' if fut._cancel_message is None else
|
| 759 |
+
fut._cancel_message)
|
| 760 |
+
else:
|
| 761 |
+
res = fut.exception()
|
| 762 |
+
if res is None:
|
| 763 |
+
res = fut.result()
|
| 764 |
+
results.append(res)
|
| 765 |
+
|
| 766 |
+
if outer._cancel_requested:
|
| 767 |
+
# If gather is being cancelled we must propagate the
|
| 768 |
+
# cancellation regardless of *return_exceptions* argument.
|
| 769 |
+
# See issue 32684.
|
| 770 |
+
exc = fut._make_cancelled_error()
|
| 771 |
+
outer.set_exception(exc)
|
| 772 |
+
else:
|
| 773 |
+
outer.set_result(results)
|
| 774 |
+
|
| 775 |
+
arg_to_fut = {}
|
| 776 |
+
children = []
|
| 777 |
+
nfuts = 0
|
| 778 |
+
nfinished = 0
|
| 779 |
+
loop = None
|
| 780 |
+
outer = None # bpo-46672
|
| 781 |
+
for arg in coros_or_futures:
|
| 782 |
+
if arg not in arg_to_fut:
|
| 783 |
+
fut = _ensure_future(arg, loop=loop)
|
| 784 |
+
if loop is None:
|
| 785 |
+
loop = futures._get_loop(fut)
|
| 786 |
+
if fut is not arg:
|
| 787 |
+
# 'arg' was not a Future, therefore, 'fut' is a new
|
| 788 |
+
# Future created specifically for 'arg'. Since the caller
|
| 789 |
+
# can't control it, disable the "destroy pending task"
|
| 790 |
+
# warning.
|
| 791 |
+
fut._log_destroy_pending = False
|
| 792 |
+
|
| 793 |
+
nfuts += 1
|
| 794 |
+
arg_to_fut[arg] = fut
|
| 795 |
+
fut.add_done_callback(_done_callback)
|
| 796 |
+
|
| 797 |
+
else:
|
| 798 |
+
# There's a duplicate Future object in coros_or_futures.
|
| 799 |
+
fut = arg_to_fut[arg]
|
| 800 |
+
|
| 801 |
+
children.append(fut)
|
| 802 |
+
|
| 803 |
+
outer = _GatheringFuture(children, loop=loop)
|
| 804 |
+
return outer
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
def shield(arg):
|
| 808 |
+
"""Wait for a future, shielding it from cancellation.
|
| 809 |
+
|
| 810 |
+
The statement
|
| 811 |
+
|
| 812 |
+
task = asyncio.create_task(something())
|
| 813 |
+
res = await shield(task)
|
| 814 |
+
|
| 815 |
+
is exactly equivalent to the statement
|
| 816 |
+
|
| 817 |
+
res = await something()
|
| 818 |
+
|
| 819 |
+
*except* that if the coroutine containing it is cancelled, the
|
| 820 |
+
task running in something() is not cancelled. From the POV of
|
| 821 |
+
something(), the cancellation did not happen. But its caller is
|
| 822 |
+
still cancelled, so the yield-from expression still raises
|
| 823 |
+
CancelledError. Note: If something() is cancelled by other means
|
| 824 |
+
this will still cancel shield().
|
| 825 |
+
|
| 826 |
+
If you want to completely ignore cancellation (not recommended)
|
| 827 |
+
you can combine shield() with a try/except clause, as follows:
|
| 828 |
+
|
| 829 |
+
task = asyncio.create_task(something())
|
| 830 |
+
try:
|
| 831 |
+
res = await shield(task)
|
| 832 |
+
except CancelledError:
|
| 833 |
+
res = None
|
| 834 |
+
|
| 835 |
+
Save a reference to tasks passed to this function, to avoid
|
| 836 |
+
a task disappearing mid-execution. The event loop only keeps
|
| 837 |
+
weak references to tasks. A task that isn't referenced elsewhere
|
| 838 |
+
may get garbage collected at any time, even before it's done.
|
| 839 |
+
"""
|
| 840 |
+
inner = _ensure_future(arg)
|
| 841 |
+
if inner.done():
|
| 842 |
+
# Shortcut.
|
| 843 |
+
return inner
|
| 844 |
+
loop = futures._get_loop(inner)
|
| 845 |
+
outer = loop.create_future()
|
| 846 |
+
|
| 847 |
+
def _inner_done_callback(inner):
|
| 848 |
+
if outer.cancelled():
|
| 849 |
+
if not inner.cancelled():
|
| 850 |
+
# Mark inner's result as retrieved.
|
| 851 |
+
inner.exception()
|
| 852 |
+
return
|
| 853 |
+
|
| 854 |
+
if inner.cancelled():
|
| 855 |
+
outer.cancel()
|
| 856 |
+
else:
|
| 857 |
+
exc = inner.exception()
|
| 858 |
+
if exc is not None:
|
| 859 |
+
outer.set_exception(exc)
|
| 860 |
+
else:
|
| 861 |
+
outer.set_result(inner.result())
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
def _outer_done_callback(outer):
|
| 865 |
+
if not inner.done():
|
| 866 |
+
inner.remove_done_callback(_inner_done_callback)
|
| 867 |
+
|
| 868 |
+
inner.add_done_callback(_inner_done_callback)
|
| 869 |
+
outer.add_done_callback(_outer_done_callback)
|
| 870 |
+
return outer
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
def run_coroutine_threadsafe(coro, loop):
|
| 874 |
+
"""Submit a coroutine object to a given event loop.
|
| 875 |
+
|
| 876 |
+
Return a concurrent.futures.Future to access the result.
|
| 877 |
+
"""
|
| 878 |
+
if not coroutines.iscoroutine(coro):
|
| 879 |
+
raise TypeError('A coroutine object is required')
|
| 880 |
+
future = concurrent.futures.Future()
|
| 881 |
+
|
| 882 |
+
def callback():
|
| 883 |
+
try:
|
| 884 |
+
futures._chain_future(ensure_future(coro, loop=loop), future)
|
| 885 |
+
except (SystemExit, KeyboardInterrupt):
|
| 886 |
+
raise
|
| 887 |
+
except BaseException as exc:
|
| 888 |
+
if future.set_running_or_notify_cancel():
|
| 889 |
+
future.set_exception(exc)
|
| 890 |
+
raise
|
| 891 |
+
|
| 892 |
+
loop.call_soon_threadsafe(callback)
|
| 893 |
+
return future
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
# WeakSet containing all alive tasks.
|
| 897 |
+
_all_tasks = weakref.WeakSet()
|
| 898 |
+
|
| 899 |
+
# Dictionary containing tasks that are currently active in
|
| 900 |
+
# all running event loops. {EventLoop: Task}
|
| 901 |
+
_current_tasks = {}
|
| 902 |
+
|
| 903 |
+
|
| 904 |
+
def _register_task(task):
|
| 905 |
+
"""Register a new task in asyncio as executed by loop."""
|
| 906 |
+
_all_tasks.add(task)
|
| 907 |
+
|
| 908 |
+
|
| 909 |
+
def _enter_task(loop, task):
|
| 910 |
+
current_task = _current_tasks.get(loop)
|
| 911 |
+
if current_task is not None:
|
| 912 |
+
raise RuntimeError(f"Cannot enter into task {task!r} while another "
|
| 913 |
+
f"task {current_task!r} is being executed.")
|
| 914 |
+
_current_tasks[loop] = task
|
| 915 |
+
|
| 916 |
+
|
| 917 |
+
def _leave_task(loop, task):
|
| 918 |
+
current_task = _current_tasks.get(loop)
|
| 919 |
+
if current_task is not task:
|
| 920 |
+
raise RuntimeError(f"Leaving task {task!r} does not match "
|
| 921 |
+
f"the current task {current_task!r}.")
|
| 922 |
+
del _current_tasks[loop]
|
| 923 |
+
|
| 924 |
+
|
| 925 |
+
def _unregister_task(task):
|
| 926 |
+
"""Unregister a task."""
|
| 927 |
+
_all_tasks.discard(task)
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
_py_register_task = _register_task
|
| 931 |
+
_py_unregister_task = _unregister_task
|
| 932 |
+
_py_enter_task = _enter_task
|
| 933 |
+
_py_leave_task = _leave_task
|
| 934 |
+
|
| 935 |
+
|
| 936 |
+
try:
|
| 937 |
+
from _asyncio import (_register_task, _unregister_task,
|
| 938 |
+
_enter_task, _leave_task,
|
| 939 |
+
_all_tasks, _current_tasks)
|
| 940 |
+
except ImportError:
|
| 941 |
+
pass
|
| 942 |
+
else:
|
| 943 |
+
_c_register_task = _register_task
|
| 944 |
+
_c_unregister_task = _unregister_task
|
| 945 |
+
_c_enter_task = _enter_task
|
| 946 |
+
_c_leave_task = _leave_task
|
parrot/lib/python3.10/asyncio/threads.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""High-level support for working with threads in asyncio"""
|
| 2 |
+
|
| 3 |
+
import functools
|
| 4 |
+
import contextvars
|
| 5 |
+
|
| 6 |
+
from . import events
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
__all__ = "to_thread",
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
async def to_thread(func, /, *args, **kwargs):
|
| 13 |
+
"""Asynchronously run function *func* in a separate thread.
|
| 14 |
+
|
| 15 |
+
Any *args and **kwargs supplied for this function are directly passed
|
| 16 |
+
to *func*. Also, the current :class:`contextvars.Context` is propagated,
|
| 17 |
+
allowing context variables from the main thread to be accessed in the
|
| 18 |
+
separate thread.
|
| 19 |
+
|
| 20 |
+
Return a coroutine that can be awaited to get the eventual result of *func*.
|
| 21 |
+
"""
|
| 22 |
+
loop = events.get_running_loop()
|
| 23 |
+
ctx = contextvars.copy_context()
|
| 24 |
+
func_call = functools.partial(ctx.run, func, *args, **kwargs)
|
| 25 |
+
return await loop.run_in_executor(None, func_call)
|
parrot/lib/python3.10/asyncio/windows_utils.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Various Windows specific bits and pieces."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
if sys.platform != 'win32': # pragma: no cover
|
| 6 |
+
raise ImportError('win32 only')
|
| 7 |
+
|
| 8 |
+
import _winapi
|
| 9 |
+
import itertools
|
| 10 |
+
import msvcrt
|
| 11 |
+
import os
|
| 12 |
+
import subprocess
|
| 13 |
+
import tempfile
|
| 14 |
+
import warnings
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
__all__ = 'pipe', 'Popen', 'PIPE', 'PipeHandle'
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# Constants/globals
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
BUFSIZE = 8192
|
| 24 |
+
PIPE = subprocess.PIPE
|
| 25 |
+
STDOUT = subprocess.STDOUT
|
| 26 |
+
_mmap_counter = itertools.count()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# Replacement for os.pipe() using handles instead of fds
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def pipe(*, duplex=False, overlapped=(True, True), bufsize=BUFSIZE):
|
| 33 |
+
"""Like os.pipe() but with overlapped support and using handles not fds."""
|
| 34 |
+
address = tempfile.mktemp(
|
| 35 |
+
prefix=r'\\.\pipe\python-pipe-{:d}-{:d}-'.format(
|
| 36 |
+
os.getpid(), next(_mmap_counter)))
|
| 37 |
+
|
| 38 |
+
if duplex:
|
| 39 |
+
openmode = _winapi.PIPE_ACCESS_DUPLEX
|
| 40 |
+
access = _winapi.GENERIC_READ | _winapi.GENERIC_WRITE
|
| 41 |
+
obsize, ibsize = bufsize, bufsize
|
| 42 |
+
else:
|
| 43 |
+
openmode = _winapi.PIPE_ACCESS_INBOUND
|
| 44 |
+
access = _winapi.GENERIC_WRITE
|
| 45 |
+
obsize, ibsize = 0, bufsize
|
| 46 |
+
|
| 47 |
+
openmode |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE
|
| 48 |
+
|
| 49 |
+
if overlapped[0]:
|
| 50 |
+
openmode |= _winapi.FILE_FLAG_OVERLAPPED
|
| 51 |
+
|
| 52 |
+
if overlapped[1]:
|
| 53 |
+
flags_and_attribs = _winapi.FILE_FLAG_OVERLAPPED
|
| 54 |
+
else:
|
| 55 |
+
flags_and_attribs = 0
|
| 56 |
+
|
| 57 |
+
h1 = h2 = None
|
| 58 |
+
try:
|
| 59 |
+
h1 = _winapi.CreateNamedPipe(
|
| 60 |
+
address, openmode, _winapi.PIPE_WAIT,
|
| 61 |
+
1, obsize, ibsize, _winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL)
|
| 62 |
+
|
| 63 |
+
h2 = _winapi.CreateFile(
|
| 64 |
+
address, access, 0, _winapi.NULL, _winapi.OPEN_EXISTING,
|
| 65 |
+
flags_and_attribs, _winapi.NULL)
|
| 66 |
+
|
| 67 |
+
ov = _winapi.ConnectNamedPipe(h1, overlapped=True)
|
| 68 |
+
ov.GetOverlappedResult(True)
|
| 69 |
+
return h1, h2
|
| 70 |
+
except:
|
| 71 |
+
if h1 is not None:
|
| 72 |
+
_winapi.CloseHandle(h1)
|
| 73 |
+
if h2 is not None:
|
| 74 |
+
_winapi.CloseHandle(h2)
|
| 75 |
+
raise
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# Wrapper for a pipe handle
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class PipeHandle:
|
| 82 |
+
"""Wrapper for an overlapped pipe handle which is vaguely file-object like.
|
| 83 |
+
|
| 84 |
+
The IOCP event loop can use these instead of socket objects.
|
| 85 |
+
"""
|
| 86 |
+
def __init__(self, handle):
|
| 87 |
+
self._handle = handle
|
| 88 |
+
|
| 89 |
+
def __repr__(self):
|
| 90 |
+
if self._handle is not None:
|
| 91 |
+
handle = f'handle={self._handle!r}'
|
| 92 |
+
else:
|
| 93 |
+
handle = 'closed'
|
| 94 |
+
return f'<{self.__class__.__name__} {handle}>'
|
| 95 |
+
|
| 96 |
+
@property
|
| 97 |
+
def handle(self):
|
| 98 |
+
return self._handle
|
| 99 |
+
|
| 100 |
+
def fileno(self):
|
| 101 |
+
if self._handle is None:
|
| 102 |
+
raise ValueError("I/O operation on closed pipe")
|
| 103 |
+
return self._handle
|
| 104 |
+
|
| 105 |
+
def close(self, *, CloseHandle=_winapi.CloseHandle):
|
| 106 |
+
if self._handle is not None:
|
| 107 |
+
CloseHandle(self._handle)
|
| 108 |
+
self._handle = None
|
| 109 |
+
|
| 110 |
+
def __del__(self, _warn=warnings.warn):
|
| 111 |
+
if self._handle is not None:
|
| 112 |
+
_warn(f"unclosed {self!r}", ResourceWarning, source=self)
|
| 113 |
+
self.close()
|
| 114 |
+
|
| 115 |
+
def __enter__(self):
|
| 116 |
+
return self
|
| 117 |
+
|
| 118 |
+
def __exit__(self, t, v, tb):
|
| 119 |
+
self.close()
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# Replacement for subprocess.Popen using overlapped pipe handles
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class Popen(subprocess.Popen):
|
| 126 |
+
"""Replacement for subprocess.Popen using overlapped pipe handles.
|
| 127 |
+
|
| 128 |
+
The stdin, stdout, stderr are None or instances of PipeHandle.
|
| 129 |
+
"""
|
| 130 |
+
def __init__(self, args, stdin=None, stdout=None, stderr=None, **kwds):
|
| 131 |
+
assert not kwds.get('universal_newlines')
|
| 132 |
+
assert kwds.get('bufsize', 0) == 0
|
| 133 |
+
stdin_rfd = stdout_wfd = stderr_wfd = None
|
| 134 |
+
stdin_wh = stdout_rh = stderr_rh = None
|
| 135 |
+
if stdin == PIPE:
|
| 136 |
+
stdin_rh, stdin_wh = pipe(overlapped=(False, True), duplex=True)
|
| 137 |
+
stdin_rfd = msvcrt.open_osfhandle(stdin_rh, os.O_RDONLY)
|
| 138 |
+
else:
|
| 139 |
+
stdin_rfd = stdin
|
| 140 |
+
if stdout == PIPE:
|
| 141 |
+
stdout_rh, stdout_wh = pipe(overlapped=(True, False))
|
| 142 |
+
stdout_wfd = msvcrt.open_osfhandle(stdout_wh, 0)
|
| 143 |
+
else:
|
| 144 |
+
stdout_wfd = stdout
|
| 145 |
+
if stderr == PIPE:
|
| 146 |
+
stderr_rh, stderr_wh = pipe(overlapped=(True, False))
|
| 147 |
+
stderr_wfd = msvcrt.open_osfhandle(stderr_wh, 0)
|
| 148 |
+
elif stderr == STDOUT:
|
| 149 |
+
stderr_wfd = stdout_wfd
|
| 150 |
+
else:
|
| 151 |
+
stderr_wfd = stderr
|
| 152 |
+
try:
|
| 153 |
+
super().__init__(args, stdin=stdin_rfd, stdout=stdout_wfd,
|
| 154 |
+
stderr=stderr_wfd, **kwds)
|
| 155 |
+
except:
|
| 156 |
+
for h in (stdin_wh, stdout_rh, stderr_rh):
|
| 157 |
+
if h is not None:
|
| 158 |
+
_winapi.CloseHandle(h)
|
| 159 |
+
raise
|
| 160 |
+
else:
|
| 161 |
+
if stdin_wh is not None:
|
| 162 |
+
self.stdin = PipeHandle(stdin_wh)
|
| 163 |
+
if stdout_rh is not None:
|
| 164 |
+
self.stdout = PipeHandle(stdout_rh)
|
| 165 |
+
if stderr_rh is not None:
|
| 166 |
+
self.stderr = PipeHandle(stderr_rh)
|
| 167 |
+
finally:
|
| 168 |
+
if stdin == PIPE:
|
| 169 |
+
os.close(stdin_rfd)
|
| 170 |
+
if stdout == PIPE:
|
| 171 |
+
os.close(stdout_wfd)
|
| 172 |
+
if stderr == PIPE:
|
| 173 |
+
os.close(stderr_wfd)
|
parrot/lib/python3.10/site-packages/fire-0.6.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
parrot/lib/python3.10/site-packages/fire-0.6.0.dist-info/LICENSE
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright 2017 Google Inc. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
you may not use this file except in compliance with the License.
|
| 5 |
+
You may obtain a copy of the License at
|
| 6 |
+
|
| 7 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
|
| 9 |
+
Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
See the License for the specific language governing permissions and
|
| 13 |
+
limitations under the License.
|
parrot/lib/python3.10/site-packages/fire-0.6.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fire-0.6.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
fire-0.6.0.dist-info/LICENSE,sha256=pd53tiJmvKC7l78FiZLwsPMIqDqMpV7hD79r2O2PftA,573
|
| 3 |
+
fire-0.6.0.dist-info/METADATA,sha256=qD8PSB7hZN-8d361I8FkymUFY5IDjvt-LLEqNEbEC40,1885
|
| 4 |
+
fire-0.6.0.dist-info/RECORD,,
|
| 5 |
+
fire-0.6.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 6 |
+
fire-0.6.0.dist-info/WHEEL,sha256=9Hm2OB-j1QcCUq9Jguht7ayGIIZBRTdOXD1qg9cCgPM,109
|
| 7 |
+
fire-0.6.0.dist-info/top_level.txt,sha256=y463xaVSW7PORTz4SuTbtFVLuW7MAT2-3cbSk1E8wR8,5
|
| 8 |
+
fire/__init__.py,sha256=wr1oug-Y_X9v5pqcJWlyuT4p5op33Bw2Mtg5RU2vFtM,786
|
| 9 |
+
fire/__main__.py,sha256=CCzw1dZ8CwD6zEurTzql4gRcJv5hzfFBnARintWna6I,4491
|
| 10 |
+
fire/__pycache__/__init__.cpython-310.pyc,,
|
| 11 |
+
fire/__pycache__/__main__.cpython-310.pyc,,
|
| 12 |
+
fire/__pycache__/completion.cpython-310.pyc,,
|
| 13 |
+
fire/__pycache__/completion_test.cpython-310.pyc,,
|
| 14 |
+
fire/__pycache__/core.cpython-310.pyc,,
|
| 15 |
+
fire/__pycache__/core_test.cpython-310.pyc,,
|
| 16 |
+
fire/__pycache__/custom_descriptions.cpython-310.pyc,,
|
| 17 |
+
fire/__pycache__/custom_descriptions_test.cpython-310.pyc,,
|
| 18 |
+
fire/__pycache__/decorators.cpython-310.pyc,,
|
| 19 |
+
fire/__pycache__/decorators_test.cpython-310.pyc,,
|
| 20 |
+
fire/__pycache__/docstrings.cpython-310.pyc,,
|
| 21 |
+
fire/__pycache__/docstrings_fuzz_test.cpython-310.pyc,,
|
| 22 |
+
fire/__pycache__/docstrings_test.cpython-310.pyc,,
|
| 23 |
+
fire/__pycache__/fire_import_test.cpython-310.pyc,,
|
| 24 |
+
fire/__pycache__/fire_test.cpython-310.pyc,,
|
| 25 |
+
fire/__pycache__/formatting.cpython-310.pyc,,
|
| 26 |
+
fire/__pycache__/formatting_test.cpython-310.pyc,,
|
| 27 |
+
fire/__pycache__/formatting_windows.cpython-310.pyc,,
|
| 28 |
+
fire/__pycache__/helptext.cpython-310.pyc,,
|
| 29 |
+
fire/__pycache__/helptext_test.cpython-310.pyc,,
|
| 30 |
+
fire/__pycache__/inspectutils.cpython-310.pyc,,
|
| 31 |
+
fire/__pycache__/inspectutils_test.cpython-310.pyc,,
|
| 32 |
+
fire/__pycache__/interact.cpython-310.pyc,,
|
| 33 |
+
fire/__pycache__/interact_test.cpython-310.pyc,,
|
| 34 |
+
fire/__pycache__/main_test.cpython-310.pyc,,
|
| 35 |
+
fire/__pycache__/parser.cpython-310.pyc,,
|
| 36 |
+
fire/__pycache__/parser_fuzz_test.cpython-310.pyc,,
|
| 37 |
+
fire/__pycache__/parser_test.cpython-310.pyc,,
|
| 38 |
+
fire/__pycache__/test_components.cpython-310.pyc,,
|
| 39 |
+
fire/__pycache__/test_components_bin.cpython-310.pyc,,
|
| 40 |
+
fire/__pycache__/test_components_py3.cpython-310.pyc,,
|
| 41 |
+
fire/__pycache__/test_components_test.cpython-310.pyc,,
|
| 42 |
+
fire/__pycache__/testutils.cpython-310.pyc,,
|
| 43 |
+
fire/__pycache__/testutils_test.cpython-310.pyc,,
|
| 44 |
+
fire/__pycache__/trace.cpython-310.pyc,,
|
| 45 |
+
fire/__pycache__/trace_test.cpython-310.pyc,,
|
| 46 |
+
fire/__pycache__/value_types.cpython-310.pyc,,
|
| 47 |
+
fire/completion.py,sha256=i6PXwLwhyli9J2OFK0E-RS2IPSIvEN6gPAPDtztQbcQ,16411
|
| 48 |
+
fire/completion_test.py,sha256=_wj8dJSxBFcYhOZJafgCeaDJJFPWhw3VeFYBSnWGJbI,6437
|
| 49 |
+
fire/console/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 50 |
+
fire/console/__pycache__/__init__.cpython-310.pyc,,
|
| 51 |
+
fire/console/__pycache__/console_attr.cpython-310.pyc,,
|
| 52 |
+
fire/console/__pycache__/console_attr_os.cpython-310.pyc,,
|
| 53 |
+
fire/console/__pycache__/console_io.cpython-310.pyc,,
|
| 54 |
+
fire/console/__pycache__/console_pager.cpython-310.pyc,,
|
| 55 |
+
fire/console/__pycache__/encoding.cpython-310.pyc,,
|
| 56 |
+
fire/console/__pycache__/files.cpython-310.pyc,,
|
| 57 |
+
fire/console/__pycache__/platforms.cpython-310.pyc,,
|
| 58 |
+
fire/console/__pycache__/text.cpython-310.pyc,,
|
| 59 |
+
fire/console/console_attr.py,sha256=ElNEyM5AImJyUTzsasXwvn6Xvo7pRSWnQQH6rMus3Gg,23668
|
| 60 |
+
fire/console/console_attr_os.py,sha256=r4BC7-8ifbu26RS_VkT0gAT3yQQnfxetaSSReKl9kEg,7565
|
| 61 |
+
fire/console/console_io.py,sha256=Jsd78YWVxGfjjRosscYj7NK4rhw3aCcyO_AWpUvdKiY,4259
|
| 62 |
+
fire/console/console_pager.py,sha256=G-rD2lgOB2_ZvxDCxFES5-dhRTkfjVCFy9ytqG1PVMc,9563
|
| 63 |
+
fire/console/encoding.py,sha256=TWQUFdvmXUdox3lOml14nG5jK5nUv0qJ2jLHzpULgJU,7008
|
| 64 |
+
fire/console/files.py,sha256=csLhCj6lf5WbpT7gk1FRH6LbgGI5ALZJX9uY1DDy62U,4081
|
| 65 |
+
fire/console/platforms.py,sha256=DcWAZicS3XGnUp0SIOQcDPWgcHi8rWhNcymg8d3WMMs,16420
|
| 66 |
+
fire/console/text.py,sha256=DxqVltezneaw_Qnsg2CSzd5AUSjoltCaNo4k3gNwuPs,2776
|
| 67 |
+
fire/core.py,sha256=81aRyUwfBn9L3_gqOmW-N92RRthifQRXaB55lZmNOnI,37051
|
| 68 |
+
fire/core_test.py,sha256=iK9zldIaHVnQiApIkNqeAHeDDEnc-EVcFJ3wNAlUGwQ,9902
|
| 69 |
+
fire/custom_descriptions.py,sha256=dljGNnDgdwh8xqfJDImwo0LJcul9oRLXMIeXu1VTyqs,5481
|
| 70 |
+
fire/custom_descriptions_test.py,sha256=w326Msp44tzGcsy_Dj8VQDPp2t6XriYqwan1K6xi8lk,2764
|
| 71 |
+
fire/decorators.py,sha256=MTtOCixcOGpRnaLKJFXK-VVxyhUyWWvNavRhoDKswEE,3689
|
| 72 |
+
fire/decorators_test.py,sha256=ySslVNlkcKvUq8L_4eBxjEDFjxW1zS0nQdKrtgtdWL4,5740
|
| 73 |
+
fire/docstrings.py,sha256=hUte73TIFh0GOMObY7OIlt_gJRrs2kKKSj7fK9t5PI4,25168
|
| 74 |
+
fire/docstrings_fuzz_test.py,sha256=vj0uA4IIwxI2CZcNDhISJ5JFpONVgyG9oCkrjp-eXvk,1210
|
| 75 |
+
fire/docstrings_test.py,sha256=hFtiLsfD0kpA-uxj4n2hGftYRh9CfRc3jsa7xPUhLJA,12394
|
| 76 |
+
fire/fire_import_test.py,sha256=LiRF4SrUl8_6Vzab5RpNsreWXQGOVdQl44g8h5GetEg,1093
|
| 77 |
+
fire/fire_test.py,sha256=Uw0UmKKARoX_X1amAzvC3dRCwpnUqXbhkNWlc9Xiwpo,29595
|
| 78 |
+
fire/formatting.py,sha256=qzSoLeFQI_LtCsPoWYxMSnh_RG2TF6aT9fmxNbf-Hgw,2826
|
| 79 |
+
fire/formatting_test.py,sha256=fpL8nUzhxEkRQJIMF6Yi5fc3Fbk926niqZyitDwVGow,2757
|
| 80 |
+
fire/formatting_windows.py,sha256=0nLNgkc2snyBTmmudyjkkgFRxHJn2E4iGqcL-HKnzV0,2189
|
| 81 |
+
fire/helptext.py,sha256=R4nEbQbaLReTRzqlh4gChjZu4Ipe3qDTYs1ixAJgoDA,28076
|
| 82 |
+
fire/helptext_test.py,sha256=hCbeVa9Q8wX_bT0NchOvkNH-qAqeWkbWEFSBFShiwa4,23858
|
| 83 |
+
fire/inspectutils.py,sha256=WTMMxCECIKJ_ciUAEuAsyJ6_doEos7_o-5xaKw1VE6U,12584
|
| 84 |
+
fire/inspectutils_test.py,sha256=Pc22wzv1f6P6Hf72hG9zMjbbAMYnm0hbfr6MzSrfPh0,5285
|
| 85 |
+
fire/interact.py,sha256=AQh2X42gLUe1Ga5H3PMtvX_ijcXwMo4CPDytSPRS48g,3157
|
| 86 |
+
fire/interact_test.py,sha256=sOgM_7X54U7cQyeMeY_mMOl7xjKD1EB3E98SBnWxqIo,1532
|
| 87 |
+
fire/main_test.py,sha256=65FWWxljKVe8H9kT4XFI0NQFJDQFI2aPIhyE0nqZSVA,3377
|
| 88 |
+
fire/parser.py,sha256=FsgS-cN2EIvQztG59p8JfTVmMp1nehtiLdNKKH1fyF4,4654
|
| 89 |
+
fire/parser_fuzz_test.py,sha256=94qG2l3XSIvY-qeDzaJ5Tph1DJRIcIhut0CHxfjKesI,3196
|
| 90 |
+
fire/parser_test.py,sha256=D81TbWgqNRQH5osrpbMdVrpGYiUQhYNyn5Quns0Tndo,6489
|
| 91 |
+
fire/test_components.py,sha256=o5aaOmZtJIjZ3QlIY8JAZW71kD8J5Sc9ygO6FEmbWjc,12123
|
| 92 |
+
fire/test_components_bin.py,sha256=QV1utpGK7bXjjTLavqXM6qW8iaz_EwlMuu6vSAgwsuE,917
|
| 93 |
+
fire/test_components_py3.py,sha256=KTAzulmX4h8YEkY1Mzjy4tY54RtKtX6eYttVIgr6EFc,2434
|
| 94 |
+
fire/test_components_test.py,sha256=8DUlUmfOUl6u1Yv_G5YNzABRyX-oheE_0v_Hfz5hF40,1340
|
| 95 |
+
fire/testutils.py,sha256=gcWpXVbnesdgtc9vPFnNtbMHels3EmhmaEt7zX4yr6E,3906
|
| 96 |
+
fire/testutils_test.py,sha256=Jt4NiIg-MQuO1iFcUHT52HD0cD-ZAc4EwcG7A9p84Fo,1890
|
| 97 |
+
fire/trace.py,sha256=Wb3gn1OyWthu-V7voblKlWRaf6dzQNmonrXlHODPgd4,10593
|
| 98 |
+
fire/trace_test.py,sha256=su0iGoB_IRUCsqTXWEqnWAuonzS_ah8p0ze3A-yq9Oc,5222
|
| 99 |
+
fire/value_types.py,sha256=-c9rG7uoBTCYSwYLyQ0cXDIDNjVt0FtKkNKHlMXnlec,2756
|
parrot/lib/python3.10/site-packages/fire-0.6.0.dist-info/REQUESTED
ADDED
|
File without changes
|
parrot/lib/python3.10/site-packages/fire-0.6.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (75.8.0)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py2-none-any
|
| 5 |
+
Tag: py3-none-any
|
| 6 |
+
|
parrot/lib/python3.10/site-packages/fire-0.6.0.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
fire
|
parrot/lib/python3.10/site-packages/jsonschema_specifications-2023.12.1.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
parrot/lib/python3.10/site-packages/jsonschema_specifications-2023.12.1.dist-info/METADATA
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: jsonschema-specifications
|
| 3 |
+
Version: 2023.12.1
|
| 4 |
+
Summary: The JSON Schema meta-schemas and vocabularies, exposed as a Registry
|
| 5 |
+
Project-URL: Documentation, https://jsonschema-specifications.readthedocs.io/
|
| 6 |
+
Project-URL: Homepage, https://github.com/python-jsonschema/jsonschema-specifications
|
| 7 |
+
Project-URL: Issues, https://github.com/python-jsonschema/jsonschema-specifications/issues/
|
| 8 |
+
Project-URL: Funding, https://github.com/sponsors/Julian
|
| 9 |
+
Project-URL: Tidelift, https://tidelift.com/subscription/pkg/pypi-jsonschema-specifications?utm_source=pypi-jsonschema-specifications&utm_medium=referral&utm_campaign=pypi-link
|
| 10 |
+
Project-URL: Source, https://github.com/python-jsonschema/jsonschema-specifications
|
| 11 |
+
Author: Julian Berman
|
| 12 |
+
Author-email: Julian+jsonschema-specifications@GrayVines.com
|
| 13 |
+
License: MIT
|
| 14 |
+
License-File: COPYING
|
| 15 |
+
Keywords: data validation,json,json schema,jsonschema,validation
|
| 16 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 17 |
+
Classifier: Intended Audience :: Developers
|
| 18 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 19 |
+
Classifier: Operating System :: OS Independent
|
| 20 |
+
Classifier: Programming Language :: Python
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 25 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 26 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 27 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 28 |
+
Classifier: Topic :: File Formats :: JSON :: JSON Schema
|
| 29 |
+
Requires-Python: >=3.8
|
| 30 |
+
Requires-Dist: importlib-resources>=1.4.0; python_version < '3.9'
|
| 31 |
+
Requires-Dist: referencing>=0.31.0
|
| 32 |
+
Description-Content-Type: text/x-rst
|
| 33 |
+
|
| 34 |
+
=============================
|
| 35 |
+
``jsonschema-specifications``
|
| 36 |
+
=============================
|
| 37 |
+
|
| 38 |
+
|PyPI| |Pythons| |CI| |ReadTheDocs|
|
| 39 |
+
|
| 40 |
+
JSON support files from the `JSON Schema Specifications <https://json-schema.org/specification.html>`_ (metaschemas, vocabularies, etc.), packaged for runtime access from Python as a `referencing-based Schema Registry <https://referencing.readthedocs.io/en/stable/api/#referencing.Registry>`_.
|
| 41 |
+
|
| 42 |
+
.. |PyPI| image:: https://img.shields.io/pypi/v/jsonschema-specifications.svg
|
| 43 |
+
:alt: PyPI version
|
| 44 |
+
:target: https://pypi.org/project/jsonschema-specifications/
|
| 45 |
+
|
| 46 |
+
.. |Pythons| image:: https://img.shields.io/pypi/pyversions/jsonschema-specifications.svg
|
| 47 |
+
:alt: Supported Python versions
|
| 48 |
+
:target: https://pypi.org/project/jsonschema-specifications/
|
| 49 |
+
|
| 50 |
+
.. |CI| image:: https://github.com/python-jsonschema/jsonschema-specifications/workflows/CI/badge.svg
|
| 51 |
+
:alt: Build status
|
| 52 |
+
:target: https://github.com/python-jsonschema/jsonschema-specifications/actions?query=workflow%3ACI
|
| 53 |
+
|
| 54 |
+
.. |ReadTheDocs| image:: https://readthedocs.org/projects/jsonschema-specifications/badge/?version=stable&style=flat
|
| 55 |
+
:alt: ReadTheDocs status
|
| 56 |
+
:target: https://jsonschema-specifications.readthedocs.io/en/stable/
|
parrot/lib/python3.10/site-packages/jsonschema_specifications-2023.12.1.dist-info/RECORD
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
jsonschema_specifications-2023.12.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
jsonschema_specifications-2023.12.1.dist-info/METADATA,sha256=fnTxmkgaHmLZ2WGJ1erA8FSWtQmx1wB3tpnalxBQ2C0,2977
|
| 3 |
+
jsonschema_specifications-2023.12.1.dist-info/RECORD,,
|
| 4 |
+
jsonschema_specifications-2023.12.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 5 |
+
jsonschema_specifications-2023.12.1.dist-info/WHEEL,sha256=mRYSEL3Ih6g5a_CVMIcwiF__0Ae4_gLYh01YFNwiq1k,87
|
| 6 |
+
jsonschema_specifications-2023.12.1.dist-info/licenses/COPYING,sha256=QtzWNJX4e063x3V6-jebtVpT-Ur9el9lfZrfVyNuUVw,1057
|
| 7 |
+
jsonschema_specifications/__init__.py,sha256=XmYAMRnPbRv_oidAvNZyoOttwYAvBdqr77ouDD32ZXE,385
|
| 8 |
+
jsonschema_specifications/__pycache__/__init__.cpython-310.pyc,,
|
| 9 |
+
jsonschema_specifications/__pycache__/_core.cpython-310.pyc,,
|
| 10 |
+
jsonschema_specifications/_core.py,sha256=tFhc1CMleJ3AJOK_bjxOpFQTdrsUClFGfFxPBU_CebM,1140
|
| 11 |
+
jsonschema_specifications/schemas/draft201909/metaschema.json,sha256=e3YbPhIfCgyh6ioLjizIVrz4AWBLgmjXG6yqICvAwTs,1785
|
| 12 |
+
jsonschema_specifications/schemas/draft201909/vocabularies/applicator,sha256=aJUQDplyb7sQcFhRK77D7P1LJOj9L6zuPlBe5ysNTDE,1860
|
| 13 |
+
jsonschema_specifications/schemas/draft201909/vocabularies/content,sha256=m31PVaTi_bAsQwBo_f-rxzKt3OI42j8d8mkCScM1MnQ,517
|
| 14 |
+
jsonschema_specifications/schemas/draft201909/vocabularies/core,sha256=taLElX9kldClCB8ECevooU5BOayyA_x0hHH47eKvWyw,1531
|
| 15 |
+
jsonschema_specifications/schemas/draft201909/vocabularies/meta-data,sha256=1H4kRd1qgicaKY2DzGxsuNSuHhXg3Fa-zTehY-zwEoY,892
|
| 16 |
+
jsonschema_specifications/schemas/draft201909/vocabularies/validation,sha256=HlJsHTNac0gF_ILPV5jBK5YK19olF8Zs2lobCTWcPBw,2834
|
| 17 |
+
jsonschema_specifications/schemas/draft202012/metaschema.json,sha256=Qdp29a-3zgYtJI92JGOpL3ykfk4PkFsiS6av7vkd7Q8,2452
|
| 18 |
+
jsonschema_specifications/schemas/draft202012/vocabularies/applicator,sha256=xKbkFHuR_vf-ptwFjLG_k0AvdBS3ZXiosWqvHa1qrO8,1659
|
| 19 |
+
jsonschema_specifications/schemas/draft202012/vocabularies/content,sha256=CDQ3R3ZOSlgUJieTz01lIFenkThjxZUNQyl-jh_axbY,519
|
| 20 |
+
jsonschema_specifications/schemas/draft202012/vocabularies/core,sha256=wtEqjk3RHTNt_IOj9mOqTGnwtJs76wlP_rJbUxb0gD0,1564
|
| 21 |
+
jsonschema_specifications/schemas/draft202012/vocabularies/format,sha256=UOu_55BhGoSbjMQAoJwdDg-2q1wNQ6DyIgH9NiUFa_Q,403
|
| 22 |
+
jsonschema_specifications/schemas/draft202012/vocabularies/format-annotation,sha256=q8d1rf79idIjWBcNm_k_Tr0jSVY7u-3WDwK-98gSvMA,448
|
| 23 |
+
jsonschema_specifications/schemas/draft202012/vocabularies/format-assertion,sha256=xSJCuaG7eGsmw-gset1CjDH5yW5XXc6Z5W6l_qptogw,445
|
| 24 |
+
jsonschema_specifications/schemas/draft202012/vocabularies/meta-data,sha256=j3bW4U9Bubku-TO3CM3FFEyLUmhlGtEZGEhfsXVPHHY,892
|
| 25 |
+
jsonschema_specifications/schemas/draft202012/vocabularies/unevaluated,sha256=Lb-8tzmUtnCwl2SSre4f_7RsIWgnhNL1pMpWH54tDLQ,506
|
| 26 |
+
jsonschema_specifications/schemas/draft202012/vocabularies/validation,sha256=cBCjHlQfMtK-ch4t40jfdcmzaHaj7TBId_wKvaHTelg,2834
|
| 27 |
+
jsonschema_specifications/schemas/draft3/metaschema.json,sha256=LPdfZENvtb43Si6qJ6uLfh_WUcm0ba6mxnsC_WTiRYs,2600
|
| 28 |
+
jsonschema_specifications/schemas/draft4/metaschema.json,sha256=4UidC0dV8CeTMCWR0_y48Htok6gqlPJIlfjk7fEbguI,4357
|
| 29 |
+
jsonschema_specifications/schemas/draft6/metaschema.json,sha256=wp386fVINcOgbAOzxdXsDtp3cGVo-cTffPvHVmpRAG0,4437
|
| 30 |
+
jsonschema_specifications/schemas/draft7/metaschema.json,sha256=PVOSCIJhYGxVm2A_OFMpyfGrRbXWZ-uZBodFOwVdQF4,4819
|
| 31 |
+
jsonschema_specifications/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 32 |
+
jsonschema_specifications/tests/__pycache__/__init__.cpython-310.pyc,,
|
| 33 |
+
jsonschema_specifications/tests/__pycache__/test_jsonschema_specifications.cpython-310.pyc,,
|
| 34 |
+
jsonschema_specifications/tests/test_jsonschema_specifications.py,sha256=WkbYRW6A6FoZ0rivShfqVLSCsAiHJ2x8TxqECJTXPTY,1106
|
parrot/lib/python3.10/site-packages/jsonschema_specifications-2023.12.1.dist-info/REQUESTED
ADDED
|
File without changes
|
parrot/lib/python3.10/site-packages/jsonschema_specifications-2023.12.1.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: hatchling 1.21.0
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
parrot/lib/python3.10/site-packages/jsonschema_specifications-2023.12.1.dist-info/licenses/COPYING
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2022 Julian Berman
|
| 2 |
+
|
| 3 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 4 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 5 |
+
in the Software without restriction, including without limitation the rights
|
| 6 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 7 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 8 |
+
furnished to do so, subject to the following conditions:
|
| 9 |
+
|
| 10 |
+
The above copyright notice and this permission notice shall be included in
|
| 11 |
+
all copies or substantial portions of the Software.
|
| 12 |
+
|
| 13 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 14 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 15 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 16 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 17 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 18 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
| 19 |
+
THE SOFTWARE.
|
parrot/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
parrot/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/LICENSE
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2008-2016 California Institute of Technology.
|
| 2 |
+
Copyright (c) 2016-2024 The Uncertainty Quantification Foundation.
|
| 3 |
+
All rights reserved.
|
| 4 |
+
|
| 5 |
+
This software forks the python package "multiprocessing". Licence and
|
| 6 |
+
copyright information for multiprocessing can be found in "COPYING".
|
| 7 |
+
|
| 8 |
+
This software is available subject to the conditions and terms laid
|
| 9 |
+
out below. By downloading and using this software you are agreeing
|
| 10 |
+
to the following conditions.
|
| 11 |
+
|
| 12 |
+
Redistribution and use in source and binary forms, with or without
|
| 13 |
+
modification, are permitted provided that the following conditions
|
| 14 |
+
are met:
|
| 15 |
+
|
| 16 |
+
- Redistributions of source code must retain the above copyright
|
| 17 |
+
notice, this list of conditions and the following disclaimer.
|
| 18 |
+
|
| 19 |
+
- Redistributions in binary form must reproduce the above copyright
|
| 20 |
+
notice, this list of conditions and the following disclaimer in the
|
| 21 |
+
documentation and/or other materials provided with the distribution.
|
| 22 |
+
|
| 23 |
+
- Neither the names of the copyright holders nor the names of any of
|
| 24 |
+
the contributors may be used to endorse or promote products derived
|
| 25 |
+
from this software without specific prior written permission.
|
| 26 |
+
|
| 27 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 28 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
| 29 |
+
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
| 30 |
+
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
| 31 |
+
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
| 32 |
+
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
| 33 |
+
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
|
| 34 |
+
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
| 35 |
+
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
|
| 36 |
+
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
|
| 37 |
+
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 38 |
+
|
parrot/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/METADATA
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: multiprocess
|
| 3 |
+
Version: 0.70.16
|
| 4 |
+
Summary: better multiprocessing and multithreading in Python
|
| 5 |
+
Home-page: https://github.com/uqfoundation/multiprocess
|
| 6 |
+
Download-URL: https://pypi.org/project/multiprocess/#files
|
| 7 |
+
Author: Mike McKerns
|
| 8 |
+
Author-email: mmckerns@uqfoundation.org
|
| 9 |
+
Maintainer: Mike McKerns
|
| 10 |
+
Maintainer-email: mmckerns@uqfoundation.org
|
| 11 |
+
License: BSD-3-Clause
|
| 12 |
+
Project-URL: Documentation, http://multiprocess.rtfd.io
|
| 13 |
+
Project-URL: Source Code, https://github.com/uqfoundation/multiprocess
|
| 14 |
+
Project-URL: Bug Tracker, https://github.com/uqfoundation/multiprocess/issues
|
| 15 |
+
Platform: Linux
|
| 16 |
+
Platform: Windows
|
| 17 |
+
Platform: Mac
|
| 18 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 19 |
+
Classifier: Intended Audience :: Developers
|
| 20 |
+
Classifier: Intended Audience :: Science/Research
|
| 21 |
+
Classifier: License :: OSI Approved :: BSD License
|
| 22 |
+
Classifier: Programming Language :: Python :: 3
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 25 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 26 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 27 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 28 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 29 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 30 |
+
Classifier: Topic :: Scientific/Engineering
|
| 31 |
+
Classifier: Topic :: Software Development
|
| 32 |
+
Requires-Python: >=3.8
|
| 33 |
+
License-File: LICENSE
|
| 34 |
+
License-File: COPYING
|
| 35 |
+
Requires-Dist: dill (>=0.3.8)
|
| 36 |
+
|
| 37 |
+
-----------------------------------------------------------------
|
| 38 |
+
multiprocess: better multiprocessing and multithreading in Python
|
| 39 |
+
-----------------------------------------------------------------
|
| 40 |
+
|
| 41 |
+
About Multiprocess
|
| 42 |
+
==================
|
| 43 |
+
|
| 44 |
+
``multiprocess`` is a fork of ``multiprocessing``. ``multiprocess`` extends ``multiprocessing`` to provide enhanced serialization, using `dill`. ``multiprocess`` leverages ``multiprocessing`` to support the spawning of processes using the API of the Python standard library's ``threading`` module. ``multiprocessing`` has been distributed as part of the standard library since Python 2.6.
|
| 45 |
+
|
| 46 |
+
``multiprocess`` is part of ``pathos``, a Python framework for heterogeneous computing.
|
| 47 |
+
``multiprocess`` is in active development, so any user feedback, bug reports, comments,
|
| 48 |
+
or suggestions are highly appreciated. A list of issues is located at https://github.com/uqfoundation/multiprocess/issues, with a legacy list maintained at https://uqfoundation.github.io/project/pathos/query.
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
Major Features
|
| 52 |
+
==============
|
| 53 |
+
|
| 54 |
+
``multiprocess`` enables:
|
| 55 |
+
|
| 56 |
+
- objects to be transferred between processes using pipes or multi-producer/multi-consumer queues
|
| 57 |
+
- objects to be shared between processes using a server process or (for simple data) shared memory
|
| 58 |
+
|
| 59 |
+
``multiprocess`` provides:
|
| 60 |
+
|
| 61 |
+
- equivalents of all the synchronization primitives in ``threading``
|
| 62 |
+
- a ``Pool`` class to facilitate submitting tasks to worker processes
|
| 63 |
+
- enhanced serialization, using ``dill``
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
Current Release
|
| 67 |
+
===============
|
| 68 |
+
|
| 69 |
+
The latest released version of ``multiprocess`` is available from:
|
| 70 |
+
|
| 71 |
+
https://pypi.org/project/multiprocess
|
| 72 |
+
|
| 73 |
+
``multiprocess`` is distributed under a 3-clause BSD license, and is a fork of ``multiprocessing``.
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
Development Version
|
| 77 |
+
===================
|
| 78 |
+
|
| 79 |
+
You can get the latest development version with all the shiny new features at:
|
| 80 |
+
|
| 81 |
+
https://github.com/uqfoundation
|
| 82 |
+
|
| 83 |
+
If you have a new contribution, please submit a pull request.
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
Installation
|
| 87 |
+
============
|
| 88 |
+
|
| 89 |
+
``multiprocess`` can be installed with ``pip``::
|
| 90 |
+
|
| 91 |
+
$ pip install multiprocess
|
| 92 |
+
|
| 93 |
+
For Python 2, a C compiler is required to build the included extension module from source. Python 3 and binary installs do not require a C compiler.
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
Requirements
|
| 97 |
+
============
|
| 98 |
+
|
| 99 |
+
``multiprocess`` requires:
|
| 100 |
+
|
| 101 |
+
- ``python`` (or ``pypy``), **>=3.8**
|
| 102 |
+
- ``setuptools``, **>=42**
|
| 103 |
+
- ``dill``, **>=0.3.8**
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
Basic Usage
|
| 107 |
+
===========
|
| 108 |
+
|
| 109 |
+
The ``multiprocess.Process`` class follows the API of ``threading.Thread``.
|
| 110 |
+
For example ::
|
| 111 |
+
|
| 112 |
+
from multiprocess import Process, Queue
|
| 113 |
+
|
| 114 |
+
def f(q):
|
| 115 |
+
q.put('hello world')
|
| 116 |
+
|
| 117 |
+
if __name__ == '__main__':
|
| 118 |
+
q = Queue()
|
| 119 |
+
p = Process(target=f, args=[q])
|
| 120 |
+
p.start()
|
| 121 |
+
print (q.get())
|
| 122 |
+
p.join()
|
| 123 |
+
|
| 124 |
+
Synchronization primitives like locks, semaphores and conditions are
|
| 125 |
+
available, for example ::
|
| 126 |
+
|
| 127 |
+
>>> from multiprocess import Condition
|
| 128 |
+
>>> c = Condition()
|
| 129 |
+
>>> print (c)
|
| 130 |
+
<Condition(<RLock(None, 0)>), 0>
|
| 131 |
+
>>> c.acquire()
|
| 132 |
+
True
|
| 133 |
+
>>> print (c)
|
| 134 |
+
<Condition(<RLock(MainProcess, 1)>), 0>
|
| 135 |
+
|
| 136 |
+
One can also use a manager to create shared objects either in shared
|
| 137 |
+
memory or in a server process, for example ::
|
| 138 |
+
|
| 139 |
+
>>> from multiprocess import Manager
|
| 140 |
+
>>> manager = Manager()
|
| 141 |
+
>>> l = manager.list(range(10))
|
| 142 |
+
>>> l.reverse()
|
| 143 |
+
>>> print (l)
|
| 144 |
+
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
|
| 145 |
+
>>> print (repr(l))
|
| 146 |
+
<Proxy[list] object at 0x00E1B3B0>
|
| 147 |
+
|
| 148 |
+
Tasks can be offloaded to a pool of worker processes in various ways,
|
| 149 |
+
for example ::
|
| 150 |
+
|
| 151 |
+
>>> from multiprocess import Pool
|
| 152 |
+
>>> def f(x): return x*x
|
| 153 |
+
...
|
| 154 |
+
>>> p = Pool(4)
|
| 155 |
+
>>> result = p.map_async(f, range(10))
|
| 156 |
+
>>> print (result.get(timeout=1))
|
| 157 |
+
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
|
| 158 |
+
|
| 159 |
+
When ``dill`` is installed, serialization is extended to most objects,
|
| 160 |
+
for example ::
|
| 161 |
+
|
| 162 |
+
>>> from multiprocess import Pool
|
| 163 |
+
>>> p = Pool(4)
|
| 164 |
+
>>> print (p.map(lambda x: (lambda y:y**2)(x) + x, xrange(10)))
|
| 165 |
+
[0, 2, 6, 12, 20, 30, 42, 56, 72, 90]
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
More Information
|
| 169 |
+
================
|
| 170 |
+
|
| 171 |
+
Probably the best way to get started is to look at the documentation at
|
| 172 |
+
http://multiprocess.rtfd.io. Also see ``multiprocess.tests`` for scripts that
|
| 173 |
+
demonstrate how ``multiprocess`` can be used to leverge multiple processes
|
| 174 |
+
to execute Python in parallel. You can run the test suite with
|
| 175 |
+
``python -m multiprocess.tests``. As ``multiprocess`` conforms to the
|
| 176 |
+
``multiprocessing`` interface, the examples and documentation found at
|
| 177 |
+
http://docs.python.org/library/multiprocessing.html also apply to
|
| 178 |
+
``multiprocess`` if one will ``import multiprocessing as multiprocess``.
|
| 179 |
+
See https://github.com/uqfoundation/multiprocess/tree/master/py3.12/examples
|
| 180 |
+
for a set of examples that demonstrate some basic use cases and benchmarking
|
| 181 |
+
for running Python code in parallel. Please feel free to submit a ticket on
|
| 182 |
+
github, or ask a question on stackoverflow (**@Mike McKerns**). If you would
|
| 183 |
+
like to share how you use ``multiprocess`` in your work, please send an email
|
| 184 |
+
(to **mmckerns at uqfoundation dot org**).
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
Citation
|
| 188 |
+
========
|
| 189 |
+
|
| 190 |
+
If you use ``multiprocess`` to do research that leads to publication, we ask that you
|
| 191 |
+
acknowledge use of ``multiprocess`` by citing the following in your publication::
|
| 192 |
+
|
| 193 |
+
M.M. McKerns, L. Strand, T. Sullivan, A. Fang, M.A.G. Aivazis,
|
| 194 |
+
"Building a framework for predictive science", Proceedings of
|
| 195 |
+
the 10th Python in Science Conference, 2011;
|
| 196 |
+
http://arxiv.org/pdf/1202.1056
|
| 197 |
+
|
| 198 |
+
Michael McKerns and Michael Aivazis,
|
| 199 |
+
"pathos: a framework for heterogeneous computing", 2010- ;
|
| 200 |
+
https://uqfoundation.github.io/project/pathos
|
| 201 |
+
|
| 202 |
+
Please see https://uqfoundation.github.io/project/pathos or
|
| 203 |
+
http://arxiv.org/pdf/1202.1056 for further information.
|
parrot/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/RECORD
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
_multiprocess/__init__.py,sha256=zX5_h36TGSL0brHRtBvCL5E59ccW7yjL79i-Y399ODM,321
|
| 2 |
+
_multiprocess/__pycache__/__init__.cpython-310.pyc,,
|
| 3 |
+
multiprocess-0.70.16.dist-info/COPYING,sha256=n3_yfLkw0sMgLuB-PS1hRvTeZ20GmjPaMWbJjNuoOpU,1493
|
| 4 |
+
multiprocess-0.70.16.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 5 |
+
multiprocess-0.70.16.dist-info/LICENSE,sha256=6XUJedJKg2dhI98BD3PMtVtZvRFT-oGczkOr5B4tEEA,1930
|
| 6 |
+
multiprocess-0.70.16.dist-info/METADATA,sha256=Sv2eH2CjjyjVYaryTKqHkbJTlxlVA-SbmziCgkBJeQ0,7151
|
| 7 |
+
multiprocess-0.70.16.dist-info/RECORD,,
|
| 8 |
+
multiprocess-0.70.16.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 9 |
+
multiprocess-0.70.16.dist-info/WHEEL,sha256=KxatxaZA14OswIJTdImHhiM2tdZgU-xLZEzs-sYveVc,94
|
| 10 |
+
multiprocess-0.70.16.dist-info/top_level.txt,sha256=qtJc8GNdvi6suNpISX0Myln9AXJBYrNuas1MCqRPPqg,27
|
| 11 |
+
multiprocess/__info__.py,sha256=84TUBn1oJMNpbVvXKs0lKyfLYaZvRr-ZVh1zHM9VeCY,7997
|
| 12 |
+
multiprocess/__init__.py,sha256=XWUBDGorUkDW04h64xe51pUV9N5gzvSDj3tNT2ekifw,1856
|
| 13 |
+
multiprocess/__pycache__/__info__.cpython-310.pyc,,
|
| 14 |
+
multiprocess/__pycache__/__init__.cpython-310.pyc,,
|
| 15 |
+
multiprocess/__pycache__/connection.cpython-310.pyc,,
|
| 16 |
+
multiprocess/__pycache__/context.cpython-310.pyc,,
|
| 17 |
+
multiprocess/__pycache__/forkserver.cpython-310.pyc,,
|
| 18 |
+
multiprocess/__pycache__/heap.cpython-310.pyc,,
|
| 19 |
+
multiprocess/__pycache__/managers.cpython-310.pyc,,
|
| 20 |
+
multiprocess/__pycache__/pool.cpython-310.pyc,,
|
| 21 |
+
multiprocess/__pycache__/popen_fork.cpython-310.pyc,,
|
| 22 |
+
multiprocess/__pycache__/popen_forkserver.cpython-310.pyc,,
|
| 23 |
+
multiprocess/__pycache__/popen_spawn_posix.cpython-310.pyc,,
|
| 24 |
+
multiprocess/__pycache__/popen_spawn_win32.cpython-310.pyc,,
|
| 25 |
+
multiprocess/__pycache__/process.cpython-310.pyc,,
|
| 26 |
+
multiprocess/__pycache__/queues.cpython-310.pyc,,
|
| 27 |
+
multiprocess/__pycache__/reduction.cpython-310.pyc,,
|
| 28 |
+
multiprocess/__pycache__/resource_sharer.cpython-310.pyc,,
|
| 29 |
+
multiprocess/__pycache__/resource_tracker.cpython-310.pyc,,
|
| 30 |
+
multiprocess/__pycache__/shared_memory.cpython-310.pyc,,
|
| 31 |
+
multiprocess/__pycache__/sharedctypes.cpython-310.pyc,,
|
| 32 |
+
multiprocess/__pycache__/spawn.cpython-310.pyc,,
|
| 33 |
+
multiprocess/__pycache__/synchronize.cpython-310.pyc,,
|
| 34 |
+
multiprocess/__pycache__/util.cpython-310.pyc,,
|
| 35 |
+
multiprocess/connection.py,sha256=TO9BbLVlLVjTjr0fP7lIumBgiLwaFVnpqMBgFG6iL9s,31843
|
| 36 |
+
multiprocess/context.py,sha256=2fYvgfnu3B8wj8UyNndHUHgeuVDoVxlkFFKryycstaU,11610
|
| 37 |
+
multiprocess/dummy/__init__.py,sha256=kSekDqD_NCy0FDg7XnxZSgW-Ldg1_iRr07sNwDajKpA,3061
|
| 38 |
+
multiprocess/dummy/__pycache__/__init__.cpython-310.pyc,,
|
| 39 |
+
multiprocess/dummy/__pycache__/connection.cpython-310.pyc,,
|
| 40 |
+
multiprocess/dummy/connection.py,sha256=1j3Rl5_enBM-_kMO6HDmum3kPAoFE4Zs485HV5H-V6s,1598
|
| 41 |
+
multiprocess/forkserver.py,sha256=hiltKfLImDYJyAcezNAgMDaQznB2LtYWgwre0QroLRg,12138
|
| 42 |
+
multiprocess/heap.py,sha256=9rt5u5m5rkhJNfDWiCLpYDoWIt0LbElmx52yMqk7phQ,11626
|
| 43 |
+
multiprocess/managers.py,sha256=Y5m_aCdLE4mSCuyVrwMWg5Nh9f4OdSHDlSajyOgyGao,47562
|
| 44 |
+
multiprocess/pool.py,sha256=FTmtfoqkuN8Dd48f5TgdkokoxYN75xcnR78Hw-bLSng,32759
|
| 45 |
+
multiprocess/popen_fork.py,sha256=Nvq5vVId24UfkOQxXhxZbcXuo8d6YMc409yRXAamTd0,2374
|
| 46 |
+
multiprocess/popen_forkserver.py,sha256=SrEbV8Wv0Uu_UegkaW-cayXRdjTGXr560Yyy90pj-yE,2227
|
| 47 |
+
multiprocess/popen_spawn_posix.py,sha256=l7XSWqR5UWiUSJh35qeSElLuNfUeEYwvH5HzKRnnyqg,2029
|
| 48 |
+
multiprocess/popen_spawn_win32.py,sha256=A9uvlPmhO8JBzNcEU_Gmix2Q_qYJW1NXZgXPwtN5Ao0,4011
|
| 49 |
+
multiprocess/process.py,sha256=GIIo2NiBsX1r_m0J1TcnbdeSulGLWHElRCuYRkkdgQ4,12083
|
| 50 |
+
multiprocess/queues.py,sha256=sgXCXnIOVrPScqI3lwRD9t3IshqIBMEksLtouPH9Nzc,12139
|
| 51 |
+
multiprocess/reduction.py,sha256=NQQ6KbDhmuAyaDeWaIarTZQokGPhcFda1poNnPm5uNc,9637
|
| 52 |
+
multiprocess/resource_sharer.py,sha256=nEApLhMQqd8KunfaNKl3n8vdeiCGPxKrSL1Ja0nNAEk,5132
|
| 53 |
+
multiprocess/resource_tracker.py,sha256=_D2iX4IWRe3dOwLoLjfCnXNbDAM4pRzA8qEMTcRfutw,9056
|
| 54 |
+
multiprocess/shared_memory.py,sha256=UTAecHECIOHElP9Tg6yURCo4pKZiLy65TkASjEXeGus,18458
|
| 55 |
+
multiprocess/sharedctypes.py,sha256=d-9SKRJHRlJJC331IxEoWOUXIeY9zxCbhWejXOmzGw0,6306
|
| 56 |
+
multiprocess/spawn.py,sha256=cgtV66HhV_yIVzvdblc8bVdSpem16Ks0BOFu_bV5PDQ,9293
|
| 57 |
+
multiprocess/synchronize.py,sha256=6q1ijwWyWLWLO8uUtaYT9MKepAYKfdzWPSEZGyJFP4s,11829
|
| 58 |
+
multiprocess/tests/__init__.py,sha256=k00IjwhAUV_O1bp81895vN1gLnFzBM3iM-QTn5VrQnU,199087
|
| 59 |
+
multiprocess/tests/__main__.py,sha256=RauIRQrO0HwRq_clLqbBk4gwo5Xw3-ASLuC029XaHeA,912
|
| 60 |
+
multiprocess/tests/__pycache__/__init__.cpython-310.pyc,,
|
| 61 |
+
multiprocess/tests/__pycache__/__main__.cpython-310.pyc,,
|
| 62 |
+
multiprocess/tests/__pycache__/mp_fork_bomb.cpython-310.pyc,,
|
| 63 |
+
multiprocess/tests/__pycache__/mp_preload.cpython-310.pyc,,
|
| 64 |
+
multiprocess/tests/__pycache__/test_multiprocessing_fork.cpython-310.pyc,,
|
| 65 |
+
multiprocess/tests/__pycache__/test_multiprocessing_forkserver.cpython-310.pyc,,
|
| 66 |
+
multiprocess/tests/__pycache__/test_multiprocessing_main_handling.cpython-310.pyc,,
|
| 67 |
+
multiprocess/tests/__pycache__/test_multiprocessing_spawn.cpython-310.pyc,,
|
| 68 |
+
multiprocess/tests/mp_fork_bomb.py,sha256=6ADOEzh1aXHZ21aOGoBPhKcgB5sj15G9tQVgSc6GrlY,448
|
| 69 |
+
multiprocess/tests/mp_preload.py,sha256=1-WvLFMaPoH-vZbpUaJvvZHFxTpA9tgmct2vblQy99M,365
|
| 70 |
+
multiprocess/tests/test_multiprocessing_fork.py,sha256=ue1SQLJFxm1oc_3F2gR_WRtt39jhaj0l_Ht6Y1MBmFo,476
|
| 71 |
+
multiprocess/tests/test_multiprocessing_forkserver.py,sha256=VFlUuZI60gyRbNxfHWDlgmy3zm-dPTldLWuKQZ8KObs,391
|
| 72 |
+
multiprocess/tests/test_multiprocessing_main_handling.py,sha256=mtmN0K-spqZCcZVNLf_HrhP186-knpY6eaoFonL1U4U,12018
|
| 73 |
+
multiprocess/tests/test_multiprocessing_spawn.py,sha256=2UAisJX58GZCbYuDFay_x97R9akhzzjIA4VuUUzITOY,276
|
| 74 |
+
multiprocess/util.py,sha256=OPI3CZ34BNwwwa7AqW-eGhnuSUsu-ozy2NRU8BYKuwg,14012
|
parrot/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/REQUESTED
ADDED
|
File without changes
|
parrot/lib/python3.10/site-packages/multiprocess-0.70.16.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: bdist_wheel (0.37.1)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py310-none-any
|
| 5 |
+
|
vllm/lib/python3.10/site-packages/torch/include/ATen/native/BatchLinearAlgebra.h
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <optional>
|
| 4 |
+
#include <c10/util/string_view.h>
|
| 5 |
+
#include <ATen/Config.h>
|
| 6 |
+
#include <ATen/native/DispatchStub.h>
|
| 7 |
+
|
| 8 |
+
// Forward declare TI
|
| 9 |
+
namespace at {
|
| 10 |
+
class Tensor;
|
| 11 |
+
struct TensorIterator;
|
| 12 |
+
|
| 13 |
+
namespace native {
|
| 14 |
+
enum class TransposeType;
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
namespace at::native {
|
| 20 |
+
|
| 21 |
+
enum class LapackLstsqDriverType : int64_t { Gels, Gelsd, Gelsy, Gelss};
|
| 22 |
+
|
| 23 |
+
#if AT_BUILD_WITH_LAPACK()
|
| 24 |
+
// Define per-batch functions to be used in the implementation of batched
|
| 25 |
+
// linear algebra operations
|
| 26 |
+
|
| 27 |
+
template <class scalar_t>
|
| 28 |
+
void lapackCholesky(char uplo, int n, scalar_t *a, int lda, int *info);
|
| 29 |
+
|
| 30 |
+
template <class scalar_t>
|
| 31 |
+
void lapackCholeskyInverse(char uplo, int n, scalar_t *a, int lda, int *info);
|
| 32 |
+
|
| 33 |
+
template <class scalar_t, class value_t=scalar_t>
|
| 34 |
+
void lapackEig(char jobvl, char jobvr, int n, scalar_t *a, int lda, scalar_t *w, scalar_t* vl, int ldvl, scalar_t *vr, int ldvr, scalar_t *work, int lwork, value_t *rwork, int *info);
|
| 35 |
+
|
| 36 |
+
template <class scalar_t>
|
| 37 |
+
void lapackGeqrf(int m, int n, scalar_t *a, int lda, scalar_t *tau, scalar_t *work, int lwork, int *info);
|
| 38 |
+
|
| 39 |
+
template <class scalar_t>
|
| 40 |
+
void lapackOrgqr(int m, int n, int k, scalar_t *a, int lda, scalar_t *tau, scalar_t *work, int lwork, int *info);
|
| 41 |
+
|
| 42 |
+
template <class scalar_t>
|
| 43 |
+
void lapackOrmqr(char side, char trans, int m, int n, int k, scalar_t *a, int lda, scalar_t *tau, scalar_t *c, int ldc, scalar_t *work, int lwork, int *info);
|
| 44 |
+
|
| 45 |
+
template <class scalar_t, class value_t = scalar_t>
|
| 46 |
+
void lapackSyevd(char jobz, char uplo, int n, scalar_t* a, int lda, value_t* w, scalar_t* work, int lwork, value_t* rwork, int lrwork, int* iwork, int liwork, int* info);
|
| 47 |
+
|
| 48 |
+
template <class scalar_t>
|
| 49 |
+
void lapackGels(char trans, int m, int n, int nrhs,
|
| 50 |
+
scalar_t *a, int lda, scalar_t *b, int ldb,
|
| 51 |
+
scalar_t *work, int lwork, int *info);
|
| 52 |
+
|
| 53 |
+
template <class scalar_t, class value_t = scalar_t>
|
| 54 |
+
void lapackGelsd(int m, int n, int nrhs,
|
| 55 |
+
scalar_t *a, int lda, scalar_t *b, int ldb,
|
| 56 |
+
value_t *s, value_t rcond, int *rank,
|
| 57 |
+
scalar_t* work, int lwork,
|
| 58 |
+
value_t *rwork, int* iwork, int *info);
|
| 59 |
+
|
| 60 |
+
template <class scalar_t, class value_t = scalar_t>
|
| 61 |
+
void lapackGelsy(int m, int n, int nrhs,
|
| 62 |
+
scalar_t *a, int lda, scalar_t *b, int ldb,
|
| 63 |
+
int *jpvt, value_t rcond, int *rank,
|
| 64 |
+
scalar_t *work, int lwork, value_t* rwork, int *info);
|
| 65 |
+
|
| 66 |
+
template <class scalar_t, class value_t = scalar_t>
|
| 67 |
+
void lapackGelss(int m, int n, int nrhs,
|
| 68 |
+
scalar_t *a, int lda, scalar_t *b, int ldb,
|
| 69 |
+
value_t *s, value_t rcond, int *rank,
|
| 70 |
+
scalar_t *work, int lwork,
|
| 71 |
+
value_t *rwork, int *info);
|
| 72 |
+
|
| 73 |
+
template <LapackLstsqDriverType, class scalar_t, class value_t = scalar_t>
|
| 74 |
+
struct lapackLstsq_impl;
|
| 75 |
+
|
| 76 |
+
template <class scalar_t, class value_t>
|
| 77 |
+
struct lapackLstsq_impl<LapackLstsqDriverType::Gels, scalar_t, value_t> {
|
| 78 |
+
static void call(
|
| 79 |
+
char trans, int m, int n, int nrhs,
|
| 80 |
+
scalar_t *a, int lda, scalar_t *b, int ldb,
|
| 81 |
+
scalar_t *work, int lwork, int *info, // Gels flavor
|
| 82 |
+
int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
|
| 83 |
+
value_t *s, // Gelss flavor
|
| 84 |
+
int *iwork // Gelsd flavor
|
| 85 |
+
) {
|
| 86 |
+
lapackGels<scalar_t>(
|
| 87 |
+
trans, m, n, nrhs,
|
| 88 |
+
a, lda, b, ldb,
|
| 89 |
+
work, lwork, info);
|
| 90 |
+
}
|
| 91 |
+
};
|
| 92 |
+
|
| 93 |
+
template <class scalar_t, class value_t>
|
| 94 |
+
struct lapackLstsq_impl<LapackLstsqDriverType::Gelsy, scalar_t, value_t> {
|
| 95 |
+
static void call(
|
| 96 |
+
char trans, int m, int n, int nrhs,
|
| 97 |
+
scalar_t *a, int lda, scalar_t *b, int ldb,
|
| 98 |
+
scalar_t *work, int lwork, int *info, // Gels flavor
|
| 99 |
+
int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
|
| 100 |
+
value_t *s, // Gelss flavor
|
| 101 |
+
int *iwork // Gelsd flavor
|
| 102 |
+
) {
|
| 103 |
+
lapackGelsy<scalar_t, value_t>(
|
| 104 |
+
m, n, nrhs,
|
| 105 |
+
a, lda, b, ldb,
|
| 106 |
+
jpvt, rcond, rank,
|
| 107 |
+
work, lwork, rwork, info);
|
| 108 |
+
}
|
| 109 |
+
};
|
| 110 |
+
|
| 111 |
+
template <class scalar_t, class value_t>
|
| 112 |
+
struct lapackLstsq_impl<LapackLstsqDriverType::Gelsd, scalar_t, value_t> {
|
| 113 |
+
static void call(
|
| 114 |
+
char trans, int m, int n, int nrhs,
|
| 115 |
+
scalar_t *a, int lda, scalar_t *b, int ldb,
|
| 116 |
+
scalar_t *work, int lwork, int *info, // Gels flavor
|
| 117 |
+
int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
|
| 118 |
+
value_t *s, // Gelss flavor
|
| 119 |
+
int *iwork // Gelsd flavor
|
| 120 |
+
) {
|
| 121 |
+
lapackGelsd<scalar_t, value_t>(
|
| 122 |
+
m, n, nrhs,
|
| 123 |
+
a, lda, b, ldb,
|
| 124 |
+
s, rcond, rank,
|
| 125 |
+
work, lwork,
|
| 126 |
+
rwork, iwork, info);
|
| 127 |
+
}
|
| 128 |
+
};
|
| 129 |
+
|
| 130 |
+
template <class scalar_t, class value_t>
|
| 131 |
+
struct lapackLstsq_impl<LapackLstsqDriverType::Gelss, scalar_t, value_t> {
|
| 132 |
+
static void call(
|
| 133 |
+
char trans, int m, int n, int nrhs,
|
| 134 |
+
scalar_t *a, int lda, scalar_t *b, int ldb,
|
| 135 |
+
scalar_t *work, int lwork, int *info, // Gels flavor
|
| 136 |
+
int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
|
| 137 |
+
value_t *s, // Gelss flavor
|
| 138 |
+
int *iwork // Gelsd flavor
|
| 139 |
+
) {
|
| 140 |
+
lapackGelss<scalar_t, value_t>(
|
| 141 |
+
m, n, nrhs,
|
| 142 |
+
a, lda, b, ldb,
|
| 143 |
+
s, rcond, rank,
|
| 144 |
+
work, lwork,
|
| 145 |
+
rwork, info);
|
| 146 |
+
}
|
| 147 |
+
};
|
| 148 |
+
|
| 149 |
+
template <LapackLstsqDriverType driver_type, class scalar_t, class value_t = scalar_t>
|
| 150 |
+
void lapackLstsq(
|
| 151 |
+
char trans, int m, int n, int nrhs,
|
| 152 |
+
scalar_t *a, int lda, scalar_t *b, int ldb,
|
| 153 |
+
scalar_t *work, int lwork, int *info, // Gels flavor
|
| 154 |
+
int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
|
| 155 |
+
value_t *s, // Gelss flavor
|
| 156 |
+
int *iwork // Gelsd flavor
|
| 157 |
+
) {
|
| 158 |
+
lapackLstsq_impl<driver_type, scalar_t, value_t>::call(
|
| 159 |
+
trans, m, n, nrhs,
|
| 160 |
+
a, lda, b, ldb,
|
| 161 |
+
work, lwork, info,
|
| 162 |
+
jpvt, rcond, rank, rwork,
|
| 163 |
+
s,
|
| 164 |
+
iwork);
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
template <class scalar_t>
|
| 168 |
+
void lapackLuSolve(char trans, int n, int nrhs, scalar_t *a, int lda, int *ipiv, scalar_t *b, int ldb, int *info);
|
| 169 |
+
|
| 170 |
+
template <class scalar_t>
|
| 171 |
+
void lapackLu(int m, int n, scalar_t *a, int lda, int *ipiv, int *info);
|
| 172 |
+
|
| 173 |
+
template <class scalar_t>
|
| 174 |
+
void lapackLdlHermitian(
|
| 175 |
+
char uplo,
|
| 176 |
+
int n,
|
| 177 |
+
scalar_t* a,
|
| 178 |
+
int lda,
|
| 179 |
+
int* ipiv,
|
| 180 |
+
scalar_t* work,
|
| 181 |
+
int lwork,
|
| 182 |
+
int* info);
|
| 183 |
+
|
| 184 |
+
template <class scalar_t>
|
| 185 |
+
void lapackLdlSymmetric(
|
| 186 |
+
char uplo,
|
| 187 |
+
int n,
|
| 188 |
+
scalar_t* a,
|
| 189 |
+
int lda,
|
| 190 |
+
int* ipiv,
|
| 191 |
+
scalar_t* work,
|
| 192 |
+
int lwork,
|
| 193 |
+
int* info);
|
| 194 |
+
|
| 195 |
+
template <class scalar_t>
|
| 196 |
+
void lapackLdlSolveHermitian(
|
| 197 |
+
char uplo,
|
| 198 |
+
int n,
|
| 199 |
+
int nrhs,
|
| 200 |
+
scalar_t* a,
|
| 201 |
+
int lda,
|
| 202 |
+
int* ipiv,
|
| 203 |
+
scalar_t* b,
|
| 204 |
+
int ldb,
|
| 205 |
+
int* info);
|
| 206 |
+
|
| 207 |
+
template <class scalar_t>
|
| 208 |
+
void lapackLdlSolveSymmetric(
|
| 209 |
+
char uplo,
|
| 210 |
+
int n,
|
| 211 |
+
int nrhs,
|
| 212 |
+
scalar_t* a,
|
| 213 |
+
int lda,
|
| 214 |
+
int* ipiv,
|
| 215 |
+
scalar_t* b,
|
| 216 |
+
int ldb,
|
| 217 |
+
int* info);
|
| 218 |
+
|
| 219 |
+
template<class scalar_t, class value_t=scalar_t>
|
| 220 |
+
void lapackSvd(char jobz, int m, int n, scalar_t *a, int lda, value_t *s, scalar_t *u, int ldu, scalar_t *vt, int ldvt, scalar_t *work, int lwork, value_t *rwork, int *iwork, int *info);
|
| 221 |
+
#endif
|
| 222 |
+
|
| 223 |
+
#if AT_BUILD_WITH_BLAS()
|
| 224 |
+
template <class scalar_t>
|
| 225 |
+
void blasTriangularSolve(char side, char uplo, char trans, char diag, int n, int nrhs, scalar_t* a, int lda, scalar_t* b, int ldb);
|
| 226 |
+
#endif
|
| 227 |
+
|
| 228 |
+
using cholesky_fn = void (*)(const Tensor& /*input*/, const Tensor& /*info*/, bool /*upper*/);
|
| 229 |
+
DECLARE_DISPATCH(cholesky_fn, cholesky_stub);
|
| 230 |
+
|
| 231 |
+
using cholesky_inverse_fn = Tensor& (*)(Tensor& /*result*/, Tensor& /*infos*/, bool /*upper*/);
|
| 232 |
+
|
| 233 |
+
DECLARE_DISPATCH(cholesky_inverse_fn, cholesky_inverse_stub);
|
| 234 |
+
|
| 235 |
+
using linalg_eig_fn = void (*)(Tensor& /*eigenvalues*/, Tensor& /*eigenvectors*/, Tensor& /*infos*/, const Tensor& /*input*/, bool /*compute_eigenvectors*/);
|
| 236 |
+
|
| 237 |
+
DECLARE_DISPATCH(linalg_eig_fn, linalg_eig_stub);
|
| 238 |
+
|
| 239 |
+
using geqrf_fn = void (*)(const Tensor& /*input*/, const Tensor& /*tau*/);
|
| 240 |
+
DECLARE_DISPATCH(geqrf_fn, geqrf_stub);
|
| 241 |
+
|
| 242 |
+
using orgqr_fn = Tensor& (*)(Tensor& /*result*/, const Tensor& /*tau*/);
|
| 243 |
+
DECLARE_DISPATCH(orgqr_fn, orgqr_stub);
|
| 244 |
+
|
| 245 |
+
using ormqr_fn = void (*)(const Tensor& /*input*/, const Tensor& /*tau*/, const Tensor& /*other*/, bool /*left*/, bool /*transpose*/);
|
| 246 |
+
DECLARE_DISPATCH(ormqr_fn, ormqr_stub);
|
| 247 |
+
|
| 248 |
+
using linalg_eigh_fn = void (*)(
|
| 249 |
+
const Tensor& /*eigenvalues*/,
|
| 250 |
+
const Tensor& /*eigenvectors*/,
|
| 251 |
+
const Tensor& /*infos*/,
|
| 252 |
+
bool /*upper*/,
|
| 253 |
+
bool /*compute_eigenvectors*/);
|
| 254 |
+
DECLARE_DISPATCH(linalg_eigh_fn, linalg_eigh_stub);
|
| 255 |
+
|
| 256 |
+
using lstsq_fn = void (*)(
|
| 257 |
+
const Tensor& /*a*/,
|
| 258 |
+
Tensor& /*b*/,
|
| 259 |
+
Tensor& /*rank*/,
|
| 260 |
+
Tensor& /*singular_values*/,
|
| 261 |
+
Tensor& /*infos*/,
|
| 262 |
+
double /*rcond*/,
|
| 263 |
+
std::string /*driver_name*/);
|
| 264 |
+
DECLARE_DISPATCH(lstsq_fn, lstsq_stub);
|
| 265 |
+
|
| 266 |
+
using triangular_solve_fn = void (*)(
|
| 267 |
+
const Tensor& /*A*/,
|
| 268 |
+
const Tensor& /*B*/,
|
| 269 |
+
bool /*left*/,
|
| 270 |
+
bool /*upper*/,
|
| 271 |
+
TransposeType /*transpose*/,
|
| 272 |
+
bool /*unitriangular*/);
|
| 273 |
+
DECLARE_DISPATCH(triangular_solve_fn, triangular_solve_stub);
|
| 274 |
+
|
| 275 |
+
using lu_factor_fn = void (*)(
|
| 276 |
+
const Tensor& /*input*/,
|
| 277 |
+
const Tensor& /*pivots*/,
|
| 278 |
+
const Tensor& /*infos*/,
|
| 279 |
+
bool /*compute_pivots*/);
|
| 280 |
+
DECLARE_DISPATCH(lu_factor_fn, lu_factor_stub);
|
| 281 |
+
|
| 282 |
+
using unpack_pivots_fn = void(*)(
|
| 283 |
+
TensorIterator& iter,
|
| 284 |
+
const int64_t dim_size,
|
| 285 |
+
const int64_t max_pivot);
|
| 286 |
+
DECLARE_DISPATCH(unpack_pivots_fn, unpack_pivots_stub);
|
| 287 |
+
|
| 288 |
+
using lu_solve_fn = void (*)(
|
| 289 |
+
const Tensor& /*LU*/,
|
| 290 |
+
const Tensor& /*pivots*/,
|
| 291 |
+
const Tensor& /*B*/,
|
| 292 |
+
TransposeType /*trans*/);
|
| 293 |
+
DECLARE_DISPATCH(lu_solve_fn, lu_solve_stub);
|
| 294 |
+
|
| 295 |
+
using ldl_factor_fn = void (*)(
|
| 296 |
+
const Tensor& /*LD*/,
|
| 297 |
+
const Tensor& /*pivots*/,
|
| 298 |
+
const Tensor& /*info*/,
|
| 299 |
+
bool /*upper*/,
|
| 300 |
+
bool /*hermitian*/);
|
| 301 |
+
DECLARE_DISPATCH(ldl_factor_fn, ldl_factor_stub);
|
| 302 |
+
|
| 303 |
+
using svd_fn = void (*)(
|
| 304 |
+
const Tensor& /*A*/,
|
| 305 |
+
const bool /*full_matrices*/,
|
| 306 |
+
const bool /*compute_uv*/,
|
| 307 |
+
const std::optional<c10::string_view>& /*driver*/,
|
| 308 |
+
const Tensor& /*U*/,
|
| 309 |
+
const Tensor& /*S*/,
|
| 310 |
+
const Tensor& /*Vh*/,
|
| 311 |
+
const Tensor& /*info*/);
|
| 312 |
+
DECLARE_DISPATCH(svd_fn, svd_stub);
|
| 313 |
+
|
| 314 |
+
using ldl_solve_fn = void (*)(
|
| 315 |
+
const Tensor& /*LD*/,
|
| 316 |
+
const Tensor& /*pivots*/,
|
| 317 |
+
const Tensor& /*result*/,
|
| 318 |
+
bool /*upper*/,
|
| 319 |
+
bool /*hermitian*/);
|
| 320 |
+
DECLARE_DISPATCH(ldl_solve_fn, ldl_solve_stub);
|
| 321 |
+
} // namespace at::native
|
vllm/lib/python3.10/site-packages/torch/include/ATen/native/BinaryOps.h
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <ATen/core/TensorBase.h>
|
| 4 |
+
#include <ATen/native/DispatchStub.h>
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/util/TypeSafeSignMath.h>
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
namespace at {
|
| 10 |
+
struct TensorIterator;
|
| 11 |
+
struct TensorIteratorBase;
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
namespace at::native {
|
| 15 |
+
|
| 16 |
+
inline void alpha_check(const ScalarType dtype, const Scalar& alpha) {
|
| 17 |
+
TORCH_CHECK(! alpha.isBoolean() || dtype == ScalarType::Bool,
|
| 18 |
+
"Boolean alpha only supported for Boolean results.");
|
| 19 |
+
TORCH_CHECK(isFloatingType(dtype) || isComplexType(dtype)
|
| 20 |
+
|| alpha.isIntegral(true),
|
| 21 |
+
"For integral input tensors, argument alpha must not be a floating point number.");
|
| 22 |
+
TORCH_CHECK(isComplexType(dtype) || !alpha.isComplex(),
|
| 23 |
+
"For non-complex input tensors, argument alpha must not be a complex number.")
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
// Basic checking for all sub functions.
|
| 27 |
+
inline void sub_check(const TensorBase& self, const TensorBase& other) {
|
| 28 |
+
TORCH_CHECK(self.scalar_type() != kBool || other.scalar_type() != kBool,
|
| 29 |
+
"Subtraction, the `-` operator, with two bool tensors is not supported. "
|
| 30 |
+
"Use the `^` or `logical_xor()` operator instead.")
|
| 31 |
+
TORCH_CHECK(self.scalar_type() != kBool && other.scalar_type() != kBool,
|
| 32 |
+
"Subtraction, the `-` operator, with a bool tensor is not supported. "
|
| 33 |
+
"If you are trying to invert a mask, use the `~` or `logical_not()` operator instead.");
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
inline void sub_check(const TensorBase& self, const Scalar& scalar) {
|
| 37 |
+
TORCH_CHECK(self.scalar_type() != kBool || !scalar.isBoolean(),
|
| 38 |
+
"Subtraction, the `-` operator, with two bool tensors is not supported. "
|
| 39 |
+
"Use the `^` or `logical_xor()` operator instead.")
|
| 40 |
+
TORCH_CHECK(self.scalar_type() != kBool && !scalar.isBoolean(),
|
| 41 |
+
"Subtraction, the `-` operator, with a bool tensor is not supported. "
|
| 42 |
+
"If you are trying to invert a mask, use the `~` or `logical_not()` operator instead.");
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
using structured_binary_fn_alpha = void(*)(TensorIteratorBase&, const Scalar& alpha);
|
| 46 |
+
using structured_binary_fn_double = void(*)(TensorIteratorBase&, double);
|
| 47 |
+
using structured_binary_fn = void(*)(TensorIteratorBase&);
|
| 48 |
+
|
| 49 |
+
using binary_fn_alpha = void(*)(TensorIteratorBase&, const Scalar& alpha);
|
| 50 |
+
using binary_fn_double = void(*)(TensorIterator&, double);
|
| 51 |
+
using binary_fn = void(*)(TensorIterator&);
|
| 52 |
+
using binary_clamp_fn_alpha =
|
| 53 |
+
void(*)(TensorIterator&, const Scalar& alpha, const Scalar& min_val, const Scalar& max_val);
|
| 54 |
+
|
| 55 |
+
// NB: codegenned
|
| 56 |
+
DECLARE_DISPATCH(structured_binary_fn_alpha, add_stub);
|
| 57 |
+
|
| 58 |
+
DECLARE_DISPATCH(binary_clamp_fn_alpha, add_clamp_stub);
|
| 59 |
+
DECLARE_DISPATCH(structured_binary_fn_alpha, sub_stub);
|
| 60 |
+
DECLARE_DISPATCH(structured_binary_fn, mul_stub);
|
| 61 |
+
DECLARE_DISPATCH(structured_binary_fn, div_true_stub);
|
| 62 |
+
DECLARE_DISPATCH(structured_binary_fn, div_floor_stub);
|
| 63 |
+
DECLARE_DISPATCH(structured_binary_fn, div_trunc_stub);
|
| 64 |
+
DECLARE_DISPATCH(structured_binary_fn, atan2_stub);
|
| 65 |
+
DECLARE_DISPATCH(structured_binary_fn, remainder_stub);
|
| 66 |
+
DECLARE_DISPATCH(structured_binary_fn, bitwise_and_stub);
|
| 67 |
+
DECLARE_DISPATCH(structured_binary_fn, bitwise_or_stub);
|
| 68 |
+
DECLARE_DISPATCH(structured_binary_fn, bitwise_xor_stub);
|
| 69 |
+
DECLARE_DISPATCH(structured_binary_fn, lshift_stub);
|
| 70 |
+
DECLARE_DISPATCH(structured_binary_fn, rshift_stub);
|
| 71 |
+
DECLARE_DISPATCH(binary_fn, logical_xor_stub);
|
| 72 |
+
DECLARE_DISPATCH(binary_fn, logical_and_stub);
|
| 73 |
+
DECLARE_DISPATCH(binary_fn, logical_or_stub);
|
| 74 |
+
DECLARE_DISPATCH(structured_binary_fn, lt_stub);
|
| 75 |
+
DECLARE_DISPATCH(structured_binary_fn, le_stub);
|
| 76 |
+
DECLARE_DISPATCH(structured_binary_fn, gt_stub);
|
| 77 |
+
DECLARE_DISPATCH(structured_binary_fn, ge_stub);
|
| 78 |
+
DECLARE_DISPATCH(structured_binary_fn, eq_stub);
|
| 79 |
+
DECLARE_DISPATCH(structured_binary_fn, ne_stub);
|
| 80 |
+
DECLARE_DISPATCH(binary_fn, max_elementwise_stub);
|
| 81 |
+
DECLARE_DISPATCH(binary_fn, min_elementwise_stub);
|
| 82 |
+
DECLARE_DISPATCH(structured_binary_fn, maximum_stub);
|
| 83 |
+
DECLARE_DISPATCH(structured_binary_fn, minimum_stub);
|
| 84 |
+
DECLARE_DISPATCH(structured_binary_fn, fmax_stub);
|
| 85 |
+
DECLARE_DISPATCH(structured_binary_fn, fmin_stub);
|
| 86 |
+
DECLARE_DISPATCH(structured_binary_fn_double, smooth_l1_stub);
|
| 87 |
+
DECLARE_DISPATCH(binary_fn_double, huber_stub);
|
| 88 |
+
DECLARE_DISPATCH(structured_binary_fn, sigmoid_backward_stub);
|
| 89 |
+
DECLARE_DISPATCH(binary_fn_alpha, logit_backward_stub);
|
| 90 |
+
DECLARE_DISPATCH(structured_binary_fn, tanh_backward_stub);
|
| 91 |
+
DECLARE_DISPATCH(structured_binary_fn, mse_stub);
|
| 92 |
+
DECLARE_DISPATCH(structured_binary_fn, fmod_stub);
|
| 93 |
+
DECLARE_DISPATCH(structured_binary_fn, logaddexp_stub);
|
| 94 |
+
DECLARE_DISPATCH(structured_binary_fn, logaddexp2_stub);
|
| 95 |
+
DECLARE_DISPATCH(structured_binary_fn, gcd_stub);
|
| 96 |
+
DECLARE_DISPATCH(structured_binary_fn, lcm_stub);
|
| 97 |
+
DECLARE_DISPATCH(structured_binary_fn, hypot_stub);
|
| 98 |
+
DECLARE_DISPATCH(structured_binary_fn, igamma_stub);
|
| 99 |
+
DECLARE_DISPATCH(structured_binary_fn, igammac_stub);
|
| 100 |
+
DECLARE_DISPATCH(structured_binary_fn, nextafter_stub);
|
| 101 |
+
DECLARE_DISPATCH(structured_binary_fn, heaviside_stub);
|
| 102 |
+
DECLARE_DISPATCH(structured_binary_fn, copysign_stub);
|
| 103 |
+
DECLARE_DISPATCH(structured_binary_fn, xlogy_stub);
|
| 104 |
+
DECLARE_DISPATCH(structured_binary_fn, xlog1py_stub);
|
| 105 |
+
DECLARE_DISPATCH(structured_binary_fn, zeta_stub);
|
| 106 |
+
DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_t_stub);
|
| 107 |
+
DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_u_stub);
|
| 108 |
+
DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_v_stub);
|
| 109 |
+
DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_w_stub);
|
| 110 |
+
DECLARE_DISPATCH(structured_binary_fn, hermite_polynomial_h_stub);
|
| 111 |
+
DECLARE_DISPATCH(structured_binary_fn, hermite_polynomial_he_stub);
|
| 112 |
+
DECLARE_DISPATCH(structured_binary_fn, laguerre_polynomial_l_stub);
|
| 113 |
+
DECLARE_DISPATCH(structured_binary_fn, legendre_polynomial_p_stub);
|
| 114 |
+
DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_t_stub);
|
| 115 |
+
DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_u_stub);
|
| 116 |
+
DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_v_stub);
|
| 117 |
+
DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_w_stub);
|
| 118 |
+
|
| 119 |
+
} // namespace at::native
|
vllm/lib/python3.10/site-packages/torch/include/ATen/native/ComplexHelper.h
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <ATen/core/Tensor.h>
|
| 4 |
+
#include <c10/util/irange.h>
|
| 5 |
+
|
| 6 |
+
#ifndef AT_PER_OPERATOR_HEADERS
|
| 7 |
+
#include <ATen/NativeFunctions.h>
|
| 8 |
+
#else
|
| 9 |
+
#include <ATen/ops/view_as_real_native.h>
|
| 10 |
+
#include <ATen/ops/view_as_complex_native.h>
|
| 11 |
+
|
| 12 |
+
#include <utility>
|
| 13 |
+
#endif
|
| 14 |
+
|
| 15 |
+
// WARNING: this header contains non-inline functions and should be only
|
| 16 |
+
// included from ONE cpp file
|
| 17 |
+
|
| 18 |
+
namespace at::native {
|
| 19 |
+
|
| 20 |
+
// View tensor with new dtype, storage offset, sizes and strides
|
| 21 |
+
inline Tensor view_tensor(
|
| 22 |
+
const Tensor &tensor, ScalarType dtype,
|
| 23 |
+
c10::SymInt offset, SymIntArrayRef sizes, SymIntArrayRef strides) {
|
| 24 |
+
Storage storage = tensor.storage();
|
| 25 |
+
auto key_set = tensor.key_set().remove(DispatchKey::Conjugate);
|
| 26 |
+
auto new_tensor = detail::make_tensor<TensorImpl>(
|
| 27 |
+
c10::TensorImpl::VIEW, std::move(storage), key_set, scalarTypeToTypeMeta(dtype));
|
| 28 |
+
auto * impl = new_tensor.unsafeGetTensorImpl();
|
| 29 |
+
impl->set_sizes_and_strides(sizes, strides, offset);
|
| 30 |
+
return new_tensor;
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
inline SymDimVector computeStrideForViewAsReal(SymIntArrayRef oldstride) {
|
| 34 |
+
SymDimVector res(oldstride.size() + 1);
|
| 35 |
+
for (const auto i : c10::irange(oldstride.size())) {
|
| 36 |
+
res[i] = oldstride[i] * 2;
|
| 37 |
+
}
|
| 38 |
+
res.back() = 1;
|
| 39 |
+
return res;
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
inline Tensor _view_as_real_physical(const Tensor& self) {
|
| 43 |
+
TORCH_CHECK(self.is_complex(), "view_as_real is only supported for complex tensors");
|
| 44 |
+
auto old_sizes = self.sym_sizes();
|
| 45 |
+
SymDimVector new_sizes(old_sizes.size() + 1);
|
| 46 |
+
std::copy(old_sizes.begin(), old_sizes.end(), new_sizes.begin());
|
| 47 |
+
// last dimension will always have two elements containing the real and imag vals
|
| 48 |
+
new_sizes.back() = 2;
|
| 49 |
+
auto new_strides = computeStrideForViewAsReal(self.sym_strides());
|
| 50 |
+
auto new_storage_offset = self.sym_storage_offset() * 2;
|
| 51 |
+
const auto float_type = c10::toRealValueType(self.scalar_type());
|
| 52 |
+
auto real_tensor = view_tensor(self, float_type, std::move(new_storage_offset), new_sizes, new_strides);
|
| 53 |
+
return real_tensor;
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
// expects as input a complex tensor and returns back a tensor
|
| 57 |
+
// with corresponding real dtype containing the complex values
|
| 58 |
+
// in the last two dimensions
|
| 59 |
+
Tensor view_as_real(const Tensor& self) {
|
| 60 |
+
TORCH_CHECK(!self.is_conj(), "view_as_real doesn't work on unresolved conjugated tensors. To resolve the conjugate tensor so you can view it as real, use self.resolve_conj(); however, be warned that the resulting tensor will NOT alias the original.");
|
| 61 |
+
return _view_as_real_physical(self);
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
inline SymDimVector computeStrideForViewAsComplex(SymIntArrayRef oldstride) {
|
| 65 |
+
const auto dim = oldstride.size();
|
| 66 |
+
TORCH_CHECK(dim > 0 && oldstride[dim - 1] == 1, "Tensor must have a last dimension with stride 1");
|
| 67 |
+
|
| 68 |
+
SymDimVector res(dim - 1);
|
| 69 |
+
for (const auto i : c10::irange(res.size())) {
|
| 70 |
+
TORCH_CHECK(oldstride[i] % 2 == 0, "Tensor must have a stride divisible by 2 for all but last dimension");
|
| 71 |
+
res[i] = oldstride[i] / 2;
|
| 72 |
+
}
|
| 73 |
+
return res;
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
// expects as input a float or double tensor with last dimension of size 2
|
| 77 |
+
// and returns back a tensor with corresponding complex dtype
|
| 78 |
+
Tensor view_as_complex(const Tensor& self) {
|
| 79 |
+
TORCH_CHECK(
|
| 80 |
+
self.scalar_type() == kFloat || self.scalar_type() == kDouble || self.scalar_type() == kHalf,
|
| 81 |
+
"view_as_complex is only supported for half, float and double tensors, but got a tensor of scalar type: ", self.scalar_type());
|
| 82 |
+
|
| 83 |
+
auto old_sizes = self.sym_sizes();
|
| 84 |
+
TORCH_CHECK(!old_sizes.empty(), "Input tensor must have one or more dimensions");
|
| 85 |
+
TORCH_CHECK(old_sizes[old_sizes.size()-1] == 2, "Tensor must have a last dimension of size 2");
|
| 86 |
+
SymDimVector new_sizes(old_sizes.begin(), old_sizes.end() - 1);
|
| 87 |
+
|
| 88 |
+
const auto new_strides = computeStrideForViewAsComplex(self.sym_strides());
|
| 89 |
+
const auto complex_type = c10::toComplexType(self.scalar_type());
|
| 90 |
+
|
| 91 |
+
TORCH_CHECK(self.sym_storage_offset() % 2 == 0, "Tensor must have a storage_offset divisible by 2");
|
| 92 |
+
const auto new_storage_offset = self.sym_storage_offset() / 2;
|
| 93 |
+
|
| 94 |
+
return view_tensor(self, complex_type, new_storage_offset, new_sizes, new_strides);
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
} // namespace at::native
|
vllm/lib/python3.10/site-packages/torch/include/ATen/native/CompositeRandomAccessorCommon.h
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <utility>
|
| 2 |
+
|
| 3 |
+
#pragma once
|
| 4 |
+
|
| 5 |
+
namespace at::native {
|
| 6 |
+
|
| 7 |
+
namespace {
|
| 8 |
+
|
| 9 |
+
// operator_brackets_proxy is used in
|
| 10 |
+
// CompositeRandomAccessor in place of operator[].
|
| 11 |
+
// For some iterators, references returned by operator[]
|
| 12 |
+
// could become invalid, operator_brackets_proxy tries to
|
| 13 |
+
// resolve that by making accessor[n] to be equivalent to
|
| 14 |
+
// *(accessor + n).
|
| 15 |
+
template <typename Accessor>
|
| 16 |
+
class operator_brackets_proxy {
|
| 17 |
+
using reference = typename std::iterator_traits<Accessor>::reference;
|
| 18 |
+
using value_type = typename std::iterator_traits<Accessor>::value_type;
|
| 19 |
+
|
| 20 |
+
public:
|
| 21 |
+
C10_HOST_DEVICE
|
| 22 |
+
operator_brackets_proxy(Accessor const& accessor)
|
| 23 |
+
: accessor(accessor)
|
| 24 |
+
{}
|
| 25 |
+
|
| 26 |
+
C10_HOST_DEVICE
|
| 27 |
+
operator reference() {
|
| 28 |
+
return *accessor;
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
C10_HOST_DEVICE
|
| 32 |
+
reference operator*() {
|
| 33 |
+
return *accessor;
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
C10_HOST_DEVICE
|
| 37 |
+
operator_brackets_proxy& operator=(value_type const& val) {
|
| 38 |
+
*accessor = val;
|
| 39 |
+
return *this;
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
private:
|
| 43 |
+
Accessor accessor;
|
| 44 |
+
};
|
| 45 |
+
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
// references_holder is used as a surrogate for the
|
| 49 |
+
// references type from std::iterator_traits in CompositeRandomAccessor.
|
| 50 |
+
// It is assumed in CompositeRandomAccessor that
|
| 51 |
+
// References = tuple<Types&...>,
|
| 52 |
+
// Values = tuple<Types...> by default,
|
| 53 |
+
// but they could be anything as long as References could be
|
| 54 |
+
// cast to Values.
|
| 55 |
+
// If you plan to use it with STL, for example, you will need to
|
| 56 |
+
// define 'swap` and `get`(aka std::get) methods.
|
| 57 |
+
template <typename Values, typename References>
|
| 58 |
+
class references_holder {
|
| 59 |
+
public:
|
| 60 |
+
using values = Values;
|
| 61 |
+
using references = References;
|
| 62 |
+
|
| 63 |
+
C10_HOST_DEVICE
|
| 64 |
+
references_holder(references refs)
|
| 65 |
+
: refs{std::move(refs)}
|
| 66 |
+
{}
|
| 67 |
+
|
| 68 |
+
C10_HOST_DEVICE
|
| 69 |
+
operator references() {
|
| 70 |
+
return refs;
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
C10_HOST_DEVICE
|
| 74 |
+
operator values() {
|
| 75 |
+
return refs;
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
C10_HOST_DEVICE
|
| 79 |
+
references_holder& operator=(values vals) {
|
| 80 |
+
refs = vals;
|
| 81 |
+
return *this;
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
C10_HOST_DEVICE
|
| 85 |
+
references& data() {
|
| 86 |
+
return refs;
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
protected:
|
| 90 |
+
references refs;
|
| 91 |
+
};
|
| 92 |
+
|
| 93 |
+
// CompositeRandomAccessor is essentially a simplified version of
|
| 94 |
+
// a random access iterator over two random access iterators.
|
| 95 |
+
// TupleInfo should contain a variadic type `tuple`, and a method `tie`,
|
| 96 |
+
// which constructs a tuple of references from a variadic list of arguments.
|
| 97 |
+
template <typename KeyAccessor, typename ValueAccessor, typename TupleInfo>
|
| 98 |
+
class CompositeRandomAccessor {
|
| 99 |
+
using self_type = CompositeRandomAccessor<KeyAccessor, ValueAccessor, TupleInfo>;
|
| 100 |
+
|
| 101 |
+
using key_accessor_value_type =
|
| 102 |
+
typename std::iterator_traits<KeyAccessor>::value_type;
|
| 103 |
+
using value_accessor_value_type =
|
| 104 |
+
typename std::iterator_traits<ValueAccessor>::value_type;
|
| 105 |
+
using key_accessor_reference_type =
|
| 106 |
+
typename std::iterator_traits<KeyAccessor>::reference;
|
| 107 |
+
using value_accessor_reference_type =
|
| 108 |
+
typename std::iterator_traits<ValueAccessor>::reference;
|
| 109 |
+
|
| 110 |
+
using composite_value_type = typename TupleInfo::template tuple<
|
| 111 |
+
key_accessor_value_type,
|
| 112 |
+
value_accessor_value_type>;
|
| 113 |
+
using composite_reference = typename TupleInfo::template tuple<
|
| 114 |
+
key_accessor_reference_type,
|
| 115 |
+
value_accessor_reference_type>;
|
| 116 |
+
|
| 117 |
+
public:
|
| 118 |
+
using value_type = composite_value_type;
|
| 119 |
+
using reference = references_holder<composite_value_type, composite_reference>;
|
| 120 |
+
// Note that CompositeRandomAccessor does not hold key and values
|
| 121 |
+
// in a specific datastructure, which means that a pointer to a (key, value)
|
| 122 |
+
// is not defined. Hence we just use a pointer type of the KeyAccessor.
|
| 123 |
+
using pointer = typename std::iterator_traits<KeyAccessor>::pointer;
|
| 124 |
+
using difference_type = typename std::iterator_traits<KeyAccessor>::difference_type;
|
| 125 |
+
using iterator_category = std::random_access_iterator_tag;
|
| 126 |
+
|
| 127 |
+
C10_HOST_DEVICE
|
| 128 |
+
CompositeRandomAccessor() = default;
|
| 129 |
+
|
| 130 |
+
C10_HOST_DEVICE
|
| 131 |
+
CompositeRandomAccessor(KeyAccessor keys, ValueAccessor values)
|
| 132 |
+
: keys(keys), values(values)
|
| 133 |
+
{}
|
| 134 |
+
|
| 135 |
+
// Pointer-like operations {
|
| 136 |
+
C10_HOST_DEVICE
|
| 137 |
+
reference operator*() const {
|
| 138 |
+
return TupleInfo::tie(*keys, *values);
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
// operator->() is supposed to return a pointer type.
|
| 142 |
+
// Since CompositeRandomAccessor does not hold pointers to pairs,
|
| 143 |
+
// we just return a pointer to a key.
|
| 144 |
+
C10_HOST_DEVICE
|
| 145 |
+
auto* operator->() const {
|
| 146 |
+
return keys.operator->();
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
C10_HOST_DEVICE
|
| 150 |
+
reference operator[](difference_type idx) {
|
| 151 |
+
return operator_brackets_proxy<self_type>(
|
| 152 |
+
CompositeRandomAccessor(keys + idx, values + idx)
|
| 153 |
+
);
|
| 154 |
+
}
|
| 155 |
+
// }
|
| 156 |
+
|
| 157 |
+
// Prefix/postfix increment/decrement {
|
| 158 |
+
C10_HOST_DEVICE
|
| 159 |
+
CompositeRandomAccessor& operator++() {
|
| 160 |
+
++keys;
|
| 161 |
+
++values;
|
| 162 |
+
return *this;
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
C10_HOST_DEVICE
|
| 166 |
+
CompositeRandomAccessor operator++(int) {
|
| 167 |
+
CompositeRandomAccessor copy(*this);
|
| 168 |
+
++*this;
|
| 169 |
+
return copy;
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
C10_HOST_DEVICE
|
| 173 |
+
CompositeRandomAccessor& operator--() {
|
| 174 |
+
--keys;
|
| 175 |
+
--values;
|
| 176 |
+
return *this;
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
C10_HOST_DEVICE
|
| 180 |
+
CompositeRandomAccessor operator--(int) {
|
| 181 |
+
CompositeRandomAccessor copy(*this);
|
| 182 |
+
--*this;
|
| 183 |
+
return copy;
|
| 184 |
+
}
|
| 185 |
+
// }
|
| 186 |
+
|
| 187 |
+
// Arithmetic operations {
|
| 188 |
+
C10_HOST_DEVICE
|
| 189 |
+
CompositeRandomAccessor& operator+=(difference_type offset) {
|
| 190 |
+
keys += offset;
|
| 191 |
+
values += offset;
|
| 192 |
+
return *this;
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
C10_HOST_DEVICE
|
| 196 |
+
CompositeRandomAccessor operator+(difference_type offset) const {
|
| 197 |
+
return CompositeRandomAccessor(keys + offset, values + offset);
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
C10_HOST_DEVICE
|
| 201 |
+
friend CompositeRandomAccessor operator+(
|
| 202 |
+
difference_type offset,
|
| 203 |
+
const CompositeRandomAccessor& accessor
|
| 204 |
+
) {
|
| 205 |
+
return accessor + offset;
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
C10_HOST_DEVICE
|
| 209 |
+
CompositeRandomAccessor& operator-=(difference_type offset) {
|
| 210 |
+
keys -= offset;
|
| 211 |
+
values -= offset;
|
| 212 |
+
return *this;
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
C10_HOST_DEVICE
|
| 216 |
+
CompositeRandomAccessor operator-(difference_type offset) const {
|
| 217 |
+
return CompositeRandomAccessor(keys - offset, values - offset);
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
C10_HOST_DEVICE
|
| 221 |
+
difference_type operator-(const CompositeRandomAccessor& other) const {
|
| 222 |
+
return keys - other.keys;
|
| 223 |
+
}
|
| 224 |
+
// }
|
| 225 |
+
|
| 226 |
+
// Comparison operators {
|
| 227 |
+
C10_HOST_DEVICE
|
| 228 |
+
bool operator==(const CompositeRandomAccessor& other) const {
|
| 229 |
+
return keys == other.keys;
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
C10_HOST_DEVICE
|
| 233 |
+
bool operator!=(const CompositeRandomAccessor& other) const {
|
| 234 |
+
return keys != other.keys;
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
C10_HOST_DEVICE
|
| 238 |
+
bool operator<(const CompositeRandomAccessor& other) const {
|
| 239 |
+
return keys < other.keys;
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
C10_HOST_DEVICE
|
| 243 |
+
bool operator<=(const CompositeRandomAccessor& other) const {
|
| 244 |
+
return keys <= other.keys;
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
C10_HOST_DEVICE
|
| 248 |
+
bool operator>(const CompositeRandomAccessor& other) const {
|
| 249 |
+
return keys > other.keys;
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
C10_HOST_DEVICE
|
| 253 |
+
bool operator>=(const CompositeRandomAccessor& other) const {
|
| 254 |
+
return keys >= other.keys;
|
| 255 |
+
}
|
| 256 |
+
// }
|
| 257 |
+
|
| 258 |
+
protected:
|
| 259 |
+
KeyAccessor keys;
|
| 260 |
+
ValueAccessor values;
|
| 261 |
+
};
|
| 262 |
+
|
| 263 |
+
} // namespace at::native
|
vllm/lib/python3.10/site-packages/torch/include/ATen/native/Cross.h
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <ATen/native/DispatchStub.h>
|
| 4 |
+
|
| 5 |
+
namespace at {
|
| 6 |
+
class Tensor;
|
| 7 |
+
|
| 8 |
+
namespace native {
|
| 9 |
+
|
| 10 |
+
using cross_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const int64_t d);
|
| 11 |
+
|
| 12 |
+
DECLARE_DISPATCH(cross_fn, cross_stub);
|
| 13 |
+
|
| 14 |
+
}} // namespace at::native
|
vllm/lib/python3.10/site-packages/torch/include/ATen/native/DilatedConvolutionUtils.h
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <algorithm>
|
| 4 |
+
#include <vector>
|
| 5 |
+
|
| 6 |
+
#include <ATen/div_rtn.h>
|
| 7 |
+
#include <ATen/core/Tensor.h>
|
| 8 |
+
#include <c10/util/irange.h>
|
| 9 |
+
|
| 10 |
+
#define TORCH_CHECK_DIM_SIZE(T, DIM, DIM_SIZE, SIZE) \
|
| 11 |
+
TORCH_CHECK( \
|
| 12 |
+
T.dim() == DIM && T.size(DIM_SIZE) == SIZE, \
|
| 13 |
+
"Need " #T " of dimension ", \
|
| 14 |
+
DIM, \
|
| 15 |
+
" and " #T ".size[", \
|
| 16 |
+
DIM_SIZE, \
|
| 17 |
+
"] == ", \
|
| 18 |
+
SIZE, \
|
| 19 |
+
" but got input to be of shape ", \
|
| 20 |
+
T.sizes())
|
| 21 |
+
|
| 22 |
+
namespace at::native::internal {
|
| 23 |
+
namespace {
|
| 24 |
+
inline bool all_positive(IntArrayRef& arr) {
|
| 25 |
+
return std::all_of(
|
| 26 |
+
arr.begin(), arr.end(), [](int64_t item) { return item > 0; });
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
inline bool all_nonnegative(std::vector<int64_t>& arr) {
|
| 30 |
+
return std::all_of(
|
| 31 |
+
arr.begin(), arr.end(), [](int64_t item) { return item >= 0; });
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
} // namespace
|
| 35 |
+
|
| 36 |
+
// calculate the rear part of output tensor sizes
|
| 37 |
+
template <int64_t dim>
|
| 38 |
+
std::vector<int64_t> get_output_size(
|
| 39 |
+
const Tensor& input,
|
| 40 |
+
IntArrayRef kernel_size,
|
| 41 |
+
IntArrayRef stride_size,
|
| 42 |
+
IntArrayRef pad_size,
|
| 43 |
+
IntArrayRef dilation_size) {
|
| 44 |
+
std::vector<int64_t> sizes;
|
| 45 |
+
for (const auto index : c10::irange(dim)) {
|
| 46 |
+
sizes.push_back(
|
| 47 |
+
div_rtn<int64_t>(
|
| 48 |
+
input.size(index + input.dim() - dim) + 2 * pad_size[index] -
|
| 49 |
+
(dilation_size[index] * (kernel_size[index] - 1) + 1),
|
| 50 |
+
stride_size[index]) +
|
| 51 |
+
1);
|
| 52 |
+
}
|
| 53 |
+
return sizes;
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
// calculate the sizes of output tensor
|
| 57 |
+
template <int64_t dim>
|
| 58 |
+
std::vector<int64_t> get_output_size(
|
| 59 |
+
const Tensor& input,
|
| 60 |
+
const Tensor& weight,
|
| 61 |
+
IntArrayRef kernel_size,
|
| 62 |
+
IntArrayRef stride_size,
|
| 63 |
+
IntArrayRef pad_size,
|
| 64 |
+
IntArrayRef dilation_size) {
|
| 65 |
+
auto output_size = get_output_size<dim>(
|
| 66 |
+
input, kernel_size, stride_size, pad_size, dilation_size);
|
| 67 |
+
output_size.insert(output_size.begin(), weight.size(0));
|
| 68 |
+
if (input.dim() == dim + 2) {
|
| 69 |
+
output_size.insert(output_size.begin(), input.size(0));
|
| 70 |
+
}
|
| 71 |
+
return output_size;
|
| 72 |
+
}
|
| 73 |
+
/*
|
| 74 |
+
slow_conv_dilated_shape_check - check user-input to dilated convolution
|
| 75 |
+
forward and backward functions.
|
| 76 |
+
*/
|
| 77 |
+
template <int64_t dim>
|
| 78 |
+
void slow_conv_dilated_shape_check(
|
| 79 |
+
const Tensor& input,
|
| 80 |
+
const Tensor& weight,
|
| 81 |
+
const Tensor& bias,
|
| 82 |
+
const Tensor& grad_output,
|
| 83 |
+
IntArrayRef kernel_size,
|
| 84 |
+
IntArrayRef stride_size,
|
| 85 |
+
IntArrayRef pad_size,
|
| 86 |
+
IntArrayRef dilation_size) {
|
| 87 |
+
/*
|
| 88 |
+
When the following tensors are defined:
|
| 89 |
+
|
| 90 |
+
bias, grad_weight, grad_output
|
| 91 |
+
|
| 92 |
+
then these are assumed to be contiguous without checking
|
| 93 |
+
because of these tensors are made contiguous by calling
|
| 94 |
+
.contiguous() method or by resizing of zero-sized tensors in
|
| 95 |
+
forward/backward functions.
|
| 96 |
+
|
| 97 |
+
When grad_weight is defined then it is assumed without
|
| 98 |
+
checking to have the same shape as weight, see backward
|
| 99 |
+
functions.
|
| 100 |
+
*/
|
| 101 |
+
// Check size arguments
|
| 102 |
+
TORCH_CHECK(
|
| 103 |
+
kernel_size.size() == dim,
|
| 104 |
+
"kernel sizes length should be ",
|
| 105 |
+
dim,
|
| 106 |
+
", but got ",
|
| 107 |
+
kernel_size.size());
|
| 108 |
+
TORCH_CHECK(
|
| 109 |
+
stride_size.size() == dim,
|
| 110 |
+
"strides length should be ",
|
| 111 |
+
dim,
|
| 112 |
+
", but got ",
|
| 113 |
+
stride_size.size());
|
| 114 |
+
TORCH_CHECK(
|
| 115 |
+
dilation_size.size() == dim,
|
| 116 |
+
"dilations length should be ",
|
| 117 |
+
dim,
|
| 118 |
+
", but got ",
|
| 119 |
+
dilation_size.size());
|
| 120 |
+
TORCH_CHECK(
|
| 121 |
+
pad_size.size() == dim,
|
| 122 |
+
"pads length should be ",
|
| 123 |
+
dim,
|
| 124 |
+
", but got ",
|
| 125 |
+
pad_size.size());
|
| 126 |
+
|
| 127 |
+
TORCH_CHECK(
|
| 128 |
+
all_positive(kernel_size),
|
| 129 |
+
"kernel size should be greater than zero, but got ",
|
| 130 |
+
kernel_size);
|
| 131 |
+
TORCH_CHECK(
|
| 132 |
+
all_positive(stride_size),
|
| 133 |
+
"stride should be greater than zero, but got ",
|
| 134 |
+
stride_size);
|
| 135 |
+
TORCH_CHECK(
|
| 136 |
+
all_positive(dilation_size),
|
| 137 |
+
"dilation should be greater than zero, but got ",
|
| 138 |
+
dilation_size);
|
| 139 |
+
|
| 140 |
+
// check input
|
| 141 |
+
TORCH_CHECK(input.defined(), "input must be defined");
|
| 142 |
+
bool is_batch = input.dim() == dim + 2;
|
| 143 |
+
int64_t n = (is_batch ? 2 : 1);
|
| 144 |
+
int64_t ndim = n + dim;
|
| 145 |
+
if (!is_batch) {
|
| 146 |
+
// input dim has to be dim + 1 if not batched
|
| 147 |
+
TORCH_CHECK(
|
| 148 |
+
input.dim() == dim + 1,
|
| 149 |
+
"input must be 4D or 5D tensor but got ",
|
| 150 |
+
input.dim(),
|
| 151 |
+
"D tensor");
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
// check output sizes
|
| 155 |
+
auto output_size = get_output_size<dim>(
|
| 156 |
+
input, kernel_size, stride_size, pad_size, dilation_size);
|
| 157 |
+
|
| 158 |
+
TORCH_CHECK(
|
| 159 |
+
all_nonnegative(output_size),
|
| 160 |
+
"calculated output size ",
|
| 161 |
+
output_size,
|
| 162 |
+
" is too small (all sizes must be non-negative)");
|
| 163 |
+
|
| 164 |
+
// check weight
|
| 165 |
+
TORCH_CHECK(weight.defined(), "weight must be defined");
|
| 166 |
+
TORCH_CHECK(
|
| 167 |
+
weight.dim() == dim + 2,
|
| 168 |
+
"weight must be ",
|
| 169 |
+
dim + 2,
|
| 170 |
+
"D tensor but got ",
|
| 171 |
+
weight.dim(),
|
| 172 |
+
"D tensor dim=",
|
| 173 |
+
dim);
|
| 174 |
+
TORCH_CHECK(
|
| 175 |
+
weight.sizes().slice(2) == kernel_size,
|
| 176 |
+
"weight[2:] shape ",
|
| 177 |
+
weight.sizes().slice(2),
|
| 178 |
+
" must be equal to kernel_size ",
|
| 179 |
+
kernel_size);
|
| 180 |
+
|
| 181 |
+
TORCH_CHECK_DIM_SIZE(input, input.dim(), (is_batch ? 1 : 0), weight.size(1));
|
| 182 |
+
|
| 183 |
+
// check bias when present
|
| 184 |
+
if (bias.defined()) {
|
| 185 |
+
TORCH_CHECK(
|
| 186 |
+
bias.dim() == 1,
|
| 187 |
+
"bias must be 1D tensor but got ",
|
| 188 |
+
bias.dim(),
|
| 189 |
+
"D tensor");
|
| 190 |
+
TORCH_CHECK_DIM_SIZE(bias, 1, 0, weight.size(0));
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
// check grad_output when present
|
| 194 |
+
if (grad_output.defined()) {
|
| 195 |
+
TORCH_CHECK(
|
| 196 |
+
grad_output.dim() == ndim,
|
| 197 |
+
"grad_output must be ",
|
| 198 |
+
ndim,
|
| 199 |
+
"D tensor but got ",
|
| 200 |
+
grad_output.dim(),
|
| 201 |
+
"D tensor");
|
| 202 |
+
if (is_batch) {
|
| 203 |
+
TORCH_CHECK(
|
| 204 |
+
grad_output.size(0) == input.size(0),
|
| 205 |
+
"grad_output.size(0)=",
|
| 206 |
+
grad_output.size(0),
|
| 207 |
+
" must be input.size(0)=",
|
| 208 |
+
input.size(0));
|
| 209 |
+
}
|
| 210 |
+
TORCH_CHECK(
|
| 211 |
+
grad_output.size(n - 1) == weight.size(0),
|
| 212 |
+
"grad_output.size(",
|
| 213 |
+
n - 1,
|
| 214 |
+
")=",
|
| 215 |
+
grad_output.size(n - 1),
|
| 216 |
+
" must be weight.size(0)=",
|
| 217 |
+
weight.size(0));
|
| 218 |
+
TORCH_CHECK(
|
| 219 |
+
grad_output.sizes().slice(n) == output_size,
|
| 220 |
+
"grad_output[",
|
| 221 |
+
n,
|
| 222 |
+
":] shape",
|
| 223 |
+
grad_output.sizes().slice(n),
|
| 224 |
+
" must be equal to output size ",
|
| 225 |
+
output_size);
|
| 226 |
+
}
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
} // namespace at::native::internal
|
vllm/lib/python3.10/site-packages/torch/include/ATen/native/DistributionTemplates.h
ADDED
|
@@ -0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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <ATen/core/Tensor.h>
|
| 4 |
+
#include <ATen/Dispatch.h>
|
| 5 |
+
#include <ATen/Dispatch_v2.h>
|
| 6 |
+
#include <ATen/Generator.h>
|
| 7 |
+
#include <ATen/ExpandUtils.h>
|
| 8 |
+
#include <ATen/Tensor.h>
|
| 9 |
+
#include <ATen/MemoryOverlap.h>
|
| 10 |
+
#include <ATen/NamedTensorUtils.h>
|
| 11 |
+
#include <ATen/native/Resize.h>
|
| 12 |
+
#include <ATen/native/TensorIterator.h>
|
| 13 |
+
#include <cmath>
|
| 14 |
+
#include <limits>
|
| 15 |
+
#include <optional>
|
| 16 |
+
|
| 17 |
+
#ifndef AT_PER_OPERATOR_HEADERS
|
| 18 |
+
#include <ATen/Functions.h>
|
| 19 |
+
#else
|
| 20 |
+
#include <ATen/ops/empty_like.h>
|
| 21 |
+
#include <ATen/ops/empty.h>
|
| 22 |
+
#include <ATen/ops/full.h>
|
| 23 |
+
#include <ATen/ops/view_as_real.h>
|
| 24 |
+
#endif
|
| 25 |
+
|
| 26 |
+
namespace at::native::templates {
|
| 27 |
+
|
| 28 |
+
// ==================================================== Random ========================================================
|
| 29 |
+
|
| 30 |
+
// The purpose of `update_from` and `update_to` is to find the closest valid int64_t number that can be used as actual `from`.
|
| 31 |
+
// The current implementation of `random_` uses uint64_t arithmetics and casts the result to the target dtype(scalar_t).
|
| 32 |
+
// This casting can result in generating numbers that happen to be greater or equal to `to` value. For instance:
|
| 33 |
+
//
|
| 34 |
+
// auto actual = torch::empty({3, 3}, torch::half);
|
| 35 |
+
// actual.random_(0, 65504);
|
| 36 |
+
//
|
| 37 |
+
// If random's uint64_t arithmetics produces 65503 as a random value after casting to torch::half it becomes 65504
|
| 38 |
+
// and violates the requirement that random value must be less than `to`. To resolve this issue `update_from` and `update_to`
|
| 39 |
+
// moves `from` to the right and `to` to the left to the next closest value that won't go outside [from, to) after casting to
|
| 40 |
+
// the target dtype. For `to` = 65504 it moves left for (1 << (log2(to) - 11 + 1)) = 32 and becomes 65472, which is previous
|
| 41 |
+
// available number for torch::half dtype.
|
| 42 |
+
template<typename scalar_t>
|
| 43 |
+
int64_t update_from(int64_t from) {
|
| 44 |
+
static_assert(
|
| 45 |
+
std::is_floating_point<scalar_t>::value ||
|
| 46 |
+
std::is_same<scalar_t, at::Half>::value ||
|
| 47 |
+
std::is_same<scalar_t, at::BFloat16>::value, "scalar_t must be floating-point type");
|
| 48 |
+
const auto from_plus_1 = static_cast<int64_t>(static_cast<scalar_t>(from + 1));
|
| 49 |
+
if (from_plus_1 < from) {
|
| 50 |
+
int64_t from_ = std::abs(from + 1);
|
| 51 |
+
int n = 0;
|
| 52 |
+
while (from_ >>= 1) ++n;
|
| 53 |
+
// NOLINTNEXTLINE(clang-analyzer-core.UndefinedBinaryOperatorResult)
|
| 54 |
+
from = from_plus_1 + (1LL << (n - std::numeric_limits<scalar_t>::digits + 1));
|
| 55 |
+
}
|
| 56 |
+
return from;
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
template<typename scalar_t>
|
| 60 |
+
int64_t update_to(int64_t to) {
|
| 61 |
+
static_assert(
|
| 62 |
+
std::is_floating_point<scalar_t>::value ||
|
| 63 |
+
std::is_same<scalar_t, at::Half>::value ||
|
| 64 |
+
std::is_same<scalar_t, at::BFloat16>::value, "scalar_t must be floating-point type");
|
| 65 |
+
const auto to_minus_1 = static_cast<int64_t>(static_cast<scalar_t>(to - 1));
|
| 66 |
+
if (to_minus_1 >= to) {
|
| 67 |
+
int64_t to_ = std::abs(to - 1);
|
| 68 |
+
int n = 0;
|
| 69 |
+
while (to_ >>= 1) ++n;
|
| 70 |
+
// NOLINTNEXTLINE(clang-analyzer-core.UndefinedBinaryOperatorResult)
|
| 71 |
+
to = to_minus_1 - (1LL << (n - std::numeric_limits<scalar_t>::digits + 1));
|
| 72 |
+
}
|
| 73 |
+
return to;
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
// Return earlier for not invoking kernel.
|
| 77 |
+
// See https://github.com/pytorch/pytorch/issues/103418 for more details
|
| 78 |
+
#define CHECK_EMPTY_AND_RETURN(tensor) \
|
| 79 |
+
if (tensor.numel() == 0) { \
|
| 80 |
+
return tensor; \
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
template<template<typename> class random_kernel, typename RNG>
|
| 84 |
+
at::Tensor& random_impl(at::Tensor& self, std::optional<Generator> generator) {
|
| 85 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 86 |
+
auto iter = at::TensorIterator::borrowing_nullary_op(self);
|
| 87 |
+
random_kernel<RNG>()(iter, generator);
|
| 88 |
+
return self;
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
#define CHECK_OUT_OF_BOUNDS(var, name, min, max, dtype) \
|
| 92 |
+
TORCH_CHECK(var >= min && var <= max, name , " is out of bounds for ", dtype); \
|
| 93 |
+
|
| 94 |
+
#define WARN_OUT_OF_BOUNDS(var, name, digits, dtype) \
|
| 95 |
+
if (var < -(1LL << digits) || var > (1LL << digits)) { \
|
| 96 |
+
TORCH_WARN(name , " is out of bounds [-(2^", digits, "), 2^", digits, "]. ", \
|
| 97 |
+
"Due to precision limitations ", dtype, " can support discrete uniform distribution only within this range. ", \
|
| 98 |
+
"This warning will become an error in version 1.7 release, please fix the code in advance"); \
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
inline void check_from_to_in_range(int64_t from, int64_t to_inc, caffe2::TypeMeta dtype) {
|
| 102 |
+
const auto scalar_type = typeMetaToScalarType(dtype);
|
| 103 |
+
if (isFloatingType(scalar_type)) {
|
| 104 |
+
AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, scalar_type, "check_random_fp_bounds", [&] {
|
| 105 |
+
const auto min = static_cast<double>(std::numeric_limits<scalar_t>::lowest());
|
| 106 |
+
const auto max = static_cast<double>(std::numeric_limits<scalar_t>::max());
|
| 107 |
+
CHECK_OUT_OF_BOUNDS(from, "from", min, max, dtype);
|
| 108 |
+
CHECK_OUT_OF_BOUNDS(to_inc, "to - 1", min, max, dtype);
|
| 109 |
+
|
| 110 |
+
constexpr auto digits = std::numeric_limits<scalar_t>::digits;
|
| 111 |
+
WARN_OUT_OF_BOUNDS(from, "from", digits, dtype);
|
| 112 |
+
WARN_OUT_OF_BOUNDS(to_inc, "to - 1", digits, dtype);
|
| 113 |
+
});
|
| 114 |
+
} else if (scalar_type == kUInt64) {
|
| 115 |
+
// When you do a comparison between int64_t and uint64_t, the usual
|
| 116 |
+
// arithmetic conversions say that the int64_t value is promoted to
|
| 117 |
+
// unsigned. But this conversion wraps around: if I had -1 as my int64_t,
|
| 118 |
+
// then it will promote to 0xFFFFFFFFFFFFFFFF in uint64_t. This is never
|
| 119 |
+
// the right thing to do.
|
| 120 |
+
CHECK_OUT_OF_BOUNDS(from, "from", 0, INT64_MAX, dtype);
|
| 121 |
+
CHECK_OUT_OF_BOUNDS(to_inc, "to - 1", 0, INT64_MAX, dtype);
|
| 122 |
+
} else if (isIntegralType(scalar_type, /*includeBool=*/true)) {
|
| 123 |
+
AT_DISPATCH_V2(scalar_type, "check_random_integral_bounds", AT_WRAP([&]() {
|
| 124 |
+
const auto min = static_cast<int64_t>(std::numeric_limits<scalar_t>::lowest());
|
| 125 |
+
const auto max = static_cast<int64_t>(std::numeric_limits<scalar_t>::max());
|
| 126 |
+
CHECK_OUT_OF_BOUNDS(from, "from", min, max, dtype);
|
| 127 |
+
CHECK_OUT_OF_BOUNDS(to_inc, "to - 1", min, max, dtype);
|
| 128 |
+
}), AT_EXPAND(AT_INTEGRAL_TYPES), kUInt16, kUInt32, kBool);
|
| 129 |
+
} else {
|
| 130 |
+
TORCH_CHECK(false, "check_random_bounds handles only integral, floating-point and boolean types");
|
| 131 |
+
}
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
template<template<typename> class random_from_to_kernel, typename RNG>
|
| 135 |
+
at::Tensor& random_from_to_impl(at::Tensor& self, int64_t from, std::optional<int64_t> to_opt, std::optional<Generator> generator) {
|
| 136 |
+
uint64_t range = 0;
|
| 137 |
+
auto iter = at::TensorIterator::borrowing_nullary_op(self);
|
| 138 |
+
if (to_opt.has_value()) {
|
| 139 |
+
// [from, to)
|
| 140 |
+
int64_t to = *to_opt;
|
| 141 |
+
TORCH_CHECK(from < to, "random_ expects 'from' to be less than 'to', but got from=", from, " >= to=", to);
|
| 142 |
+
if (isFloatingType(iter.dtype())) {
|
| 143 |
+
AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, self.scalar_type(), "random_update_from_to", [&] {
|
| 144 |
+
from = update_from<scalar_t>(from);
|
| 145 |
+
to = update_to<scalar_t>(to);
|
| 146 |
+
TORCH_CHECK(from < to, "random_ expects 'from' casted to dtype to be less than 'to' casted to dtype, but got from=", from, " >= to=", to);
|
| 147 |
+
});
|
| 148 |
+
}
|
| 149 |
+
check_from_to_in_range(from, to - 1, self.dtype());
|
| 150 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 151 |
+
range = static_cast<uint64_t>(to) - static_cast<uint64_t>(from);
|
| 152 |
+
random_from_to_kernel<RNG>()(iter, range, from, generator);
|
| 153 |
+
} else if (from != std::numeric_limits<int64_t>::lowest()) {
|
| 154 |
+
// [from, std::numeric_limits<int64_t>::max()]
|
| 155 |
+
int64_t to_inc = 0;
|
| 156 |
+
if (isFloatingType(iter.dtype())) {
|
| 157 |
+
AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, self.scalar_type(), "random_from_to_range_calc", [&] {
|
| 158 |
+
constexpr int64_t scalar_t_max = static_cast<int64_t>(1) << std::numeric_limits<scalar_t>::digits;
|
| 159 |
+
to_inc = scalar_t_max > std::numeric_limits<int64_t>::max() ? std::numeric_limits<int64_t>::max() : static_cast<int64_t>(scalar_t_max);
|
| 160 |
+
from = update_from<scalar_t>(from);
|
| 161 |
+
TORCH_CHECK(from < to_inc, "random_ expects 'from' casted to dtype to be less than or equal to 'to_inc' casted to dtype, but got from=", from, " > to_inc=", to_inc);
|
| 162 |
+
});
|
| 163 |
+
} else if (isIntegralType(iter.dtype(), /*includeBool=*/true)) {
|
| 164 |
+
AT_DISPATCH_V2(self.scalar_type(), "random_from_to_range_calc", AT_WRAP([&] {
|
| 165 |
+
if constexpr (std::is_same_v<scalar_t, bool>) {
|
| 166 |
+
to_inc = static_cast<int64_t>(true);
|
| 167 |
+
} else {
|
| 168 |
+
to_inc = static_cast<int64_t>(std::numeric_limits<scalar_t>::max());
|
| 169 |
+
}
|
| 170 |
+
}), AT_EXPAND(AT_INTEGRAL_TYPES_V2), kBool);
|
| 171 |
+
} else {
|
| 172 |
+
TORCH_CHECK(false, "random_from_to_impl handles only integral, floating-point and boolean types");
|
| 173 |
+
}
|
| 174 |
+
check_from_to_in_range(from, to_inc, self.dtype());
|
| 175 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 176 |
+
range = static_cast<uint64_t>(to_inc) - static_cast<uint64_t>(from) + 1;
|
| 177 |
+
random_from_to_kernel<RNG>()(iter, range, from, generator);
|
| 178 |
+
} else {
|
| 179 |
+
// [std::numeric_limits<int64_t>::lowest(), std::numeric_limits<int64_t>::max()]
|
| 180 |
+
// range = 2^64
|
| 181 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 182 |
+
random_from_to_kernel<RNG>()(iter, generator);
|
| 183 |
+
}
|
| 184 |
+
return self;
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
// ==================================================== Normal ========================================================
|
| 188 |
+
|
| 189 |
+
#define CHECK_NORMAL_TENSOR_STD(std) \
|
| 190 |
+
do { \
|
| 191 |
+
TORCH_CHECK( \
|
| 192 |
+
!std.is_complex(), \
|
| 193 |
+
"normal expects standard deviation to be non-complex"); \
|
| 194 |
+
TORCH_CHECK( \
|
| 195 |
+
std.numel() == 0 || std.is_meta() || std.min().ge(0).item<bool>(), \
|
| 196 |
+
"normal expects all elements of std >= 0.0"); \
|
| 197 |
+
} while (0)
|
| 198 |
+
|
| 199 |
+
#define CHECK_NORMAL_STD(std) \
|
| 200 |
+
TORCH_CHECK(std >= 0.0, "normal expects std >= 0.0, but found std ", std);
|
| 201 |
+
|
| 202 |
+
template<template<typename> class normal_kernel, typename RNG>
|
| 203 |
+
Tensor& normal_impl_(Tensor& self, double mean, double std, std::optional<Generator> gen) {
|
| 204 |
+
CHECK_NORMAL_STD(std);
|
| 205 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 206 |
+
|
| 207 |
+
if (self.is_complex()) {
|
| 208 |
+
auto float_tensor = at::view_as_real(self);
|
| 209 |
+
// variance for normal distribution of the real and imaginary values
|
| 210 |
+
// is half of the input variance
|
| 211 |
+
normal_kernel<RNG>()(float_tensor, mean, std/(std::sqrt(2)), gen);
|
| 212 |
+
} else {
|
| 213 |
+
normal_kernel<RNG>()(self, mean, std, gen);
|
| 214 |
+
}
|
| 215 |
+
return self;
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
template<template<typename> class normal_kernel, typename RNG>
|
| 219 |
+
Tensor& normal_out_impl(Tensor& output, const Tensor& mean, double std, std::optional<Generator> gen) {
|
| 220 |
+
CHECK_NORMAL_STD(std);
|
| 221 |
+
auto std_tensor = at::empty_like(output, MemoryFormat::Contiguous);
|
| 222 |
+
auto shape = at::infer_size(mean.sizes(), std_tensor.sizes());
|
| 223 |
+
at::native::resize_output(output, shape);
|
| 224 |
+
normal_impl_<normal_kernel, RNG>(output, 0, std, gen);
|
| 225 |
+
output.add_(mean);
|
| 226 |
+
return output;
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
template<template<typename> class normal_kernel, typename RNG>
|
| 230 |
+
Tensor& normal_out_impl(Tensor& output, double mean, const Tensor& std, std::optional<Generator> gen) {
|
| 231 |
+
CHECK_NORMAL_TENSOR_STD(std);
|
| 232 |
+
auto mean_tensor = at::full({}, mean, output.options());
|
| 233 |
+
auto shape = at::infer_size(mean_tensor.sizes(), std.sizes());
|
| 234 |
+
at::native::resize_output(output, shape);
|
| 235 |
+
normal_impl_<normal_kernel, RNG>(output, 0, 1, gen);
|
| 236 |
+
// CUDA NB: addcmul_out copies the tensor to be added into the output.
|
| 237 |
+
// The previous function here was addcmul_out(output, mean_tensor, output, std, 1);
|
| 238 |
+
// The third argument is not a constant reference and hence the samples in output are overwritten.
|
| 239 |
+
// Consequently, the computation performed is mean_tensor + mean_tensor * std instead of mean_tensor + output * std
|
| 240 |
+
output.mul_(std).add_(mean_tensor);
|
| 241 |
+
return output;
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
template<template<typename> class normal_kernel, typename RNG>
|
| 245 |
+
Tensor& normal_out_impl(Tensor& output, const Tensor& mean, const Tensor& std, std::optional<Generator> gen) {
|
| 246 |
+
CHECK_NORMAL_TENSOR_STD(std);
|
| 247 |
+
auto shape = at::infer_size(mean.sizes(), std.sizes());
|
| 248 |
+
at::native::resize_output(output, shape);
|
| 249 |
+
normal_impl_<normal_kernel, RNG>(output, 0, 1, gen);
|
| 250 |
+
// CUDA NB: addcmul_out copies the tensor to be added into the output.
|
| 251 |
+
// The previous function here was addcmul_out(output, mean, output, std, 1);
|
| 252 |
+
// The third argument is not a constant reference and hence the samples in output are overwritten.
|
| 253 |
+
// Consequently, the computation performed is mean + mean * std instead of mean + output * std
|
| 254 |
+
output.mul_(std).add_(mean);
|
| 255 |
+
return output;
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
template<template<typename> class normal_kernel, typename RNG>
|
| 259 |
+
Tensor normal_impl(const Tensor& mean, double std, std::optional<Generator> gen) {
|
| 260 |
+
CHECK_NORMAL_STD(std);
|
| 261 |
+
Tensor ret = at::empty_like(mean, MemoryFormat::Contiguous);
|
| 262 |
+
normal_out_impl<normal_kernel, RNG>(ret, mean, std, gen);
|
| 263 |
+
return ret;
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
template<template<typename> class normal_kernel, typename RNG>
|
| 267 |
+
Tensor normal_impl(double mean, const Tensor& std, std::optional<Generator> gen) {
|
| 268 |
+
CHECK_NORMAL_TENSOR_STD(std);
|
| 269 |
+
Tensor ret = at::empty_like(std, MemoryFormat::Contiguous);
|
| 270 |
+
normal_out_impl<normal_kernel, RNG>(ret, mean, std, gen);
|
| 271 |
+
return ret;
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
template<template<typename> class normal_kernel, typename RNG>
|
| 275 |
+
Tensor normal_impl(const Tensor& mean, const Tensor& std, std::optional<Generator> gen) {
|
| 276 |
+
CHECK_NORMAL_TENSOR_STD(std);
|
| 277 |
+
auto shape = at::infer_size(mean.sizes(), std.sizes());
|
| 278 |
+
Tensor ret = at::empty(shape, mean.options(), MemoryFormat::Contiguous);
|
| 279 |
+
normal_out_impl<normal_kernel, RNG>(ret, mean, std, gen);
|
| 280 |
+
return ret;
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
// ==================================================== Uniform =======================================================
|
| 284 |
+
|
| 285 |
+
template<template<typename> class uniform_kernel, typename RNG>
|
| 286 |
+
at::Tensor& uniform_impl_(at::Tensor& self, double from, double to, std::optional<Generator> generator) {
|
| 287 |
+
if (self.is_complex()) {
|
| 288 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 289 |
+
auto float_tensor = at::view_as_real(self);
|
| 290 |
+
uniform_impl_<uniform_kernel, RNG>(float_tensor, from, to, generator);
|
| 291 |
+
} else {
|
| 292 |
+
AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, self.scalar_type(), "check_uniform_bounds", [&] {
|
| 293 |
+
[[maybe_unused]] const auto dtype = self.dtype();
|
| 294 |
+
const auto min = static_cast<double>(std::numeric_limits<scalar_t>::lowest());
|
| 295 |
+
const auto max = static_cast<double>(std::numeric_limits<scalar_t>::max());
|
| 296 |
+
CHECK_OUT_OF_BOUNDS(from, "from", min, max, dtype);
|
| 297 |
+
CHECK_OUT_OF_BOUNDS(to, "to", min, max, dtype);
|
| 298 |
+
TORCH_CHECK(from <= to, "uniform_ expects to return a [from, to) range, but found from=", from, " > to=", to);
|
| 299 |
+
TORCH_CHECK((to - from) <= std::numeric_limits<scalar_t>::max(),
|
| 300 |
+
"uniform_ expects to-from <= std::numeric_limits<", toString(self.scalar_type()),
|
| 301 |
+
">::max(), but found to=", to, " and from=", from,
|
| 302 |
+
" which result in to-from to exceed the limit");
|
| 303 |
+
from = std::min(std::max(from, min), max);
|
| 304 |
+
to = std::max(std::min(to, max), min);
|
| 305 |
+
});
|
| 306 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 307 |
+
auto iter = at::TensorIterator::borrowing_nullary_op(self);
|
| 308 |
+
uniform_kernel<RNG>()(iter, from, to, generator);
|
| 309 |
+
}
|
| 310 |
+
return self;
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
// ================================================== LogNormal =======================================================
|
| 314 |
+
|
| 315 |
+
template<template<typename> class log_normal_kernel, typename RNG>
|
| 316 |
+
at::Tensor& log_normal_impl_(at::Tensor& self, double mean, double std, std::optional<Generator> gen) {
|
| 317 |
+
TORCH_CHECK(std > 0.0, "log_normal_ expects std > 0.0, but found std=", std);
|
| 318 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 319 |
+
auto iter = TensorIterator::borrowing_nullary_op(self);
|
| 320 |
+
log_normal_kernel<RNG>()(iter, mean, std, gen);
|
| 321 |
+
return self;
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
// =================================================== Geometric ======================================================
|
| 325 |
+
|
| 326 |
+
template<template<typename> class geometric_kernel, typename RNG>
|
| 327 |
+
Tensor& geometric_impl_(Tensor& self, double p, std::optional<Generator> gen) {
|
| 328 |
+
TORCH_CHECK(0 < p && p < 1, "geometric_ expects p to be in (0, 1), but got p=", p);
|
| 329 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 330 |
+
auto iter = TensorIterator::borrowing_nullary_op(self);
|
| 331 |
+
geometric_kernel<RNG>()(iter, p, gen);
|
| 332 |
+
return self;
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
// ================================================== Exponential =====================================================
|
| 336 |
+
|
| 337 |
+
template<template<typename> class exponential_kernel, typename RNG>
|
| 338 |
+
Tensor& exponential_impl_(Tensor& self, double lambda, std::optional<Generator> gen) {
|
| 339 |
+
TORCH_CHECK(lambda > 0.0, "exponential_ expects lambda > 0.0, but found lambda=", lambda);
|
| 340 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 341 |
+
auto iter = TensorIterator::borrowing_nullary_op(self);
|
| 342 |
+
exponential_kernel<RNG>()(iter, lambda, gen);
|
| 343 |
+
return self;
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
// ==================================================== Cauchy ========================================================
|
| 347 |
+
|
| 348 |
+
template<template<typename> class cauchy_kernel, typename RNG>
|
| 349 |
+
Tensor& cauchy_impl_(Tensor& self, double median, double sigma, std::optional<Generator> gen) {
|
| 350 |
+
// TODO: instead of variable name 'sigma', use 'gamma' or 'scale'
|
| 351 |
+
// the variance, squared sigma, is undefined for cauchy distribution
|
| 352 |
+
TORCH_CHECK(sigma > 0.0, "cauchy_ expects sigma > 0.0, but found sigma=", sigma);
|
| 353 |
+
TORCH_CHECK(at::isFloatingType(self.scalar_type()), "Cauchy distribution is a continuous probability distribution. dtype must be a floating point but you specified ", self.dtype());
|
| 354 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 355 |
+
auto iter = TensorIterator::borrowing_nullary_op(self);
|
| 356 |
+
cauchy_kernel<RNG>()(iter, median, sigma, gen);
|
| 357 |
+
return self;
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
// ==================================================== Bernoulli =====================================================
|
| 361 |
+
|
| 362 |
+
template<template<typename> class bernoulli_tensor_kernel, typename RNG>
|
| 363 |
+
Tensor& bernoulli_impl_(Tensor& self, const Tensor& p_, std::optional<Generator> gen) {
|
| 364 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 365 |
+
NoNamesGuard guard;
|
| 366 |
+
at::assert_no_internal_overlap(self);
|
| 367 |
+
bernoulli_tensor_kernel<RNG>()(self, p_, gen);
|
| 368 |
+
return self;
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
template<template<typename> class bernoulli_scalar_kernel, typename RNG>
|
| 372 |
+
Tensor& bernoulli_impl_(Tensor& self, double p, std::optional<Generator> gen) {
|
| 373 |
+
TORCH_CHECK(0 <= p && p <= 1, "bernoulli_ expects p to be in [0, 1], but got p=", p);
|
| 374 |
+
CHECK_EMPTY_AND_RETURN(self);
|
| 375 |
+
at::assert_no_internal_overlap(self);
|
| 376 |
+
bernoulli_scalar_kernel<RNG>()(self, p, gen);
|
| 377 |
+
return self;
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
template<template<typename> class bernoulli_tensor_kernel, typename RNG>
|
| 381 |
+
Tensor& bernoulli_out_impl(Tensor& result, const Tensor& self, std::optional<Generator> gen) {
|
| 382 |
+
// result.resize_as_(self) requires self to have same dtype as result, so we
|
| 383 |
+
// use resize_ instead.
|
| 384 |
+
// TODO: Fix resize_as_. See pytorch/pytorch#11665.
|
| 385 |
+
result.resize_(self.sizes());
|
| 386 |
+
bernoulli_impl_<bernoulli_tensor_kernel, RNG>(result, self, gen);
|
| 387 |
+
namedinference::propagate_names(result, self);
|
| 388 |
+
return result;
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
#undef CHECK_OUT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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <ATen/core/Tensor.h>
|
| 2 |
+
#include <ATen/Config.h>
|
| 3 |
+
#include <cstdint>
|
| 4 |
+
|
| 5 |
+
#ifdef USE_FBGEMM
|
| 6 |
+
#include <fbgemm/FbgemmEmbedding.h>
|
| 7 |
+
#endif
|
| 8 |
+
|
| 9 |
+
namespace at::native {
|
| 10 |
+
|
| 11 |
+
enum class EmbeddingBagMode {
|
| 12 |
+
SUM = 0,
|
| 13 |
+
MEAN = 1,
|
| 14 |
+
MAX = 2,
|
| 15 |
+
};
|
| 16 |
+
|
| 17 |
+
[[maybe_unused]] static bool operator==(int64_t op1, EmbeddingBagMode op2) {
|
| 18 |
+
return op1 == static_cast<int64_t>(op2);
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
[[maybe_unused]] static bool operator!=(int64_t op1, EmbeddingBagMode op2) {
|
| 22 |
+
return !(op1 == op2);
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
void check_arguments(
|
| 26 |
+
const Tensor& weight,
|
| 27 |
+
const Tensor& indices,
|
| 28 |
+
const Tensor& offsets,
|
| 29 |
+
const int64_t mode,
|
| 30 |
+
const std::optional<Tensor>& per_sample_weights,
|
| 31 |
+
bool include_last_offset);
|
| 32 |
+
|
| 33 |
+
void make_bag_size_out(
|
| 34 |
+
Tensor& bag_size_out,
|
| 35 |
+
const Tensor& offsets,
|
| 36 |
+
const Tensor& indices,
|
| 37 |
+
const int64_t mode,
|
| 38 |
+
const bool include_last_offset,
|
| 39 |
+
const bool requires_grad);
|
| 40 |
+
|
| 41 |
+
void make_max_indices_out(
|
| 42 |
+
Tensor& max_indices_out,
|
| 43 |
+
const Tensor& weight,
|
| 44 |
+
const Tensor& indices,
|
| 45 |
+
const Tensor& offsets,
|
| 46 |
+
const Tensor& bag_size,
|
| 47 |
+
const int64_t mode,
|
| 48 |
+
bool include_last_offset);
|
| 49 |
+
|
| 50 |
+
void make_offset2bag_out(
|
| 51 |
+
Tensor& offset2bag,
|
| 52 |
+
Tensor& output,
|
| 53 |
+
const Tensor& weight,
|
| 54 |
+
const Tensor& indices,
|
| 55 |
+
const Tensor& offsets,
|
| 56 |
+
const int64_t mode,
|
| 57 |
+
const std::optional<Tensor>& per_sample_weights,
|
| 58 |
+
const int64_t padding_idx = -1);
|
| 59 |
+
|
| 60 |
+
#ifdef USE_FBGEMM
|
| 61 |
+
|
| 62 |
+
template<bool has_weight, typename TIndex, typename TData>
|
| 63 |
+
struct _CallbackAndBlockSize {
|
| 64 |
+
using TCallback = typename fbgemm::EmbeddingSpMDMKernelSignature<TData, TIndex, TIndex, TData>::Type;
|
| 65 |
+
|
| 66 |
+
int64_t blockSize = -1;
|
| 67 |
+
TCallback callback = nullptr;
|
| 68 |
+
|
| 69 |
+
static TCallback generateCallback(int64_t block_size) {
|
| 70 |
+
return fbgemm::GenerateEmbeddingSpMDM<TData, TIndex, TIndex, TData>(
|
| 71 |
+
block_size,
|
| 72 |
+
has_weight,
|
| 73 |
+
/* normalize_by_lengths */false,
|
| 74 |
+
/* prefetch */16,
|
| 75 |
+
/* is_weight_positional */false,
|
| 76 |
+
/* use_offsets */true);
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
_CallbackAndBlockSize() = default;
|
| 80 |
+
|
| 81 |
+
explicit _CallbackAndBlockSize(std::optional<int64_t> maybe_block_size)
|
| 82 |
+
: blockSize(maybe_block_size.value_or(-1))
|
| 83 |
+
, callback(maybe_block_size.has_value() ? generateCallback(maybe_block_size.value()) : nullptr)
|
| 84 |
+
{}
|
| 85 |
+
};
|
| 86 |
+
|
| 87 |
+
template<typename... StorageMixins>
|
| 88 |
+
struct _EmbeddingBagKernelCacheImpl : private StorageMixins... {
|
| 89 |
+
|
| 90 |
+
_EmbeddingBagKernelCacheImpl() = default;
|
| 91 |
+
// use each of the mixins to store corresponding kernel and block size
|
| 92 |
+
explicit _EmbeddingBagKernelCacheImpl(std::optional<int64_t> maybe_block_size)
|
| 93 |
+
: StorageMixins(maybe_block_size)...
|
| 94 |
+
{}
|
| 95 |
+
|
| 96 |
+
// this method is thread safe (call sites may call from different threads)
|
| 97 |
+
template<bool has_weight, typename TIndex, typename TData>
|
| 98 |
+
typename _CallbackAndBlockSize<has_weight, TIndex, TData>::TCallback
|
| 99 |
+
getCallback(int64_t block_size) const {
|
| 100 |
+
// if the cache doesn't store the kernel for the incoming block size
|
| 101 |
+
// (so it is different from the one stored in corresponding mixin)
|
| 102 |
+
// regenerate the kernel (not writing it into the cache so we avoid locks)
|
| 103 |
+
if (block_size != _CallbackAndBlockSize<has_weight, TIndex, TData>::blockSize) {
|
| 104 |
+
return _CallbackAndBlockSize<has_weight, TIndex, TData>::generateCallback(block_size);
|
| 105 |
+
}
|
| 106 |
+
// else retrieve the cached kernel from the corresponding mixin
|
| 107 |
+
return _CallbackAndBlockSize<has_weight, TIndex, TData>::callback;
|
| 108 |
+
}
|
| 109 |
+
};
|
| 110 |
+
|
| 111 |
+
// instantiate the cache with the list of storage mixins
|
| 112 |
+
// for each of the 8 _EmbeddingBagKernelCache* usages in the EmbeddingBag.cpp impl file
|
| 113 |
+
using _EmbeddingBagKernelCache = _EmbeddingBagKernelCacheImpl<
|
| 114 |
+
_CallbackAndBlockSize<true, int32_t, float>,
|
| 115 |
+
_CallbackAndBlockSize<false, int32_t, float>,
|
| 116 |
+
_CallbackAndBlockSize<true, int64_t, float>,
|
| 117 |
+
_CallbackAndBlockSize<false, int64_t, float>,
|
| 118 |
+
_CallbackAndBlockSize<true, int32_t, unsigned short>,
|
| 119 |
+
_CallbackAndBlockSize<false, int32_t, unsigned short>,
|
| 120 |
+
_CallbackAndBlockSize<true, int64_t, unsigned short>,
|
| 121 |
+
_CallbackAndBlockSize<false, int64_t, unsigned short>>;
|
| 122 |
+
#else
|
| 123 |
+
struct _EmbeddingBagKernelCache {
|
| 124 |
+
explicit _EmbeddingBagKernelCache(std::optional<int64_t> /* maybe_block_size */) {}
|
| 125 |
+
};
|
| 126 |
+
#endif
|
| 127 |
+
|
| 128 |
+
void _embedding_bag_cpu_impl_out(Tensor& output, Tensor& offset2bag,
|
| 129 |
+
Tensor& bag_size, Tensor* max_indices,
|
| 130 |
+
const Tensor &weight, const Tensor &indices,
|
| 131 |
+
const Tensor &offsets, const int64_t mode = 0,
|
| 132 |
+
const std::optional<Tensor>& per_sample_weights = std::nullopt,
|
| 133 |
+
bool include_last_offset = false,
|
| 134 |
+
int64_t padding_idx = -1,
|
| 135 |
+
_EmbeddingBagKernelCache* fbgemm_kernel_cache = nullptr);
|
| 136 |
+
|
| 137 |
+
void _embedding_bag_cpu_out(
|
| 138 |
+
at::Tensor& output,
|
| 139 |
+
at::Tensor& offset2bag,
|
| 140 |
+
at::Tensor& bag_size,
|
| 141 |
+
at::Tensor* p_max_indices,
|
| 142 |
+
const at::Tensor& weight,
|
| 143 |
+
const at::Tensor& indices,
|
| 144 |
+
const at::Tensor& offsets,
|
| 145 |
+
const bool scale_grad_by_freq,
|
| 146 |
+
const int64_t mode,
|
| 147 |
+
const bool sparse,
|
| 148 |
+
const std::optional<at::Tensor>& per_sample_weights,
|
| 149 |
+
const bool include_last_offset,
|
| 150 |
+
const std::optional<int64_t>& padding_idx,
|
| 151 |
+
_EmbeddingBagKernelCache* fbgemm_kernel_cache = nullptr);
|
| 152 |
+
|
| 153 |
+
} // namespace at::native
|
vllm/lib/python3.10/site-packages/torch/include/ATen/native/FusedSGD.h
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <ATen/core/Tensor.h>
|
| 2 |
+
#include <ATen/native/DispatchStub.h>
|
| 3 |
+
|
| 4 |
+
namespace at::native {
|
| 5 |
+
|
| 6 |
+
using fused_sgd_fn = void (*)(
|
| 7 |
+
const at::Tensor& param,
|
| 8 |
+
const at::Tensor& grad,
|
| 9 |
+
const at::Tensor& momentum_buffer,
|
| 10 |
+
const double weight_decay,
|
| 11 |
+
const double momentum,
|
| 12 |
+
const double lr,
|
| 13 |
+
const double dampening,
|
| 14 |
+
const bool nesterov,
|
| 15 |
+
const bool maximize,
|
| 16 |
+
const bool is_first_step,
|
| 17 |
+
const float* grad_scale_ptr);
|
| 18 |
+
|
| 19 |
+
DECLARE_DISPATCH(fused_sgd_fn, fused_sgd_stub);
|
| 20 |
+
|
| 21 |
+
} // namespace at::native
|
vllm/lib/python3.10/site-packages/torch/include/ATen/native/GridSampler.h
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <algorithm>
|
| 4 |
+
#include <cmath>
|
| 5 |
+
#include <cstdint>
|
| 6 |
+
#include <utility>
|
| 7 |
+
|
| 8 |
+
#include <ATen/native/GridSamplerUtils.h>
|
| 9 |
+
|
| 10 |
+
namespace at::native {
|
| 11 |
+
|
| 12 |
+
using detail::GridSamplerInterpolation;
|
| 13 |
+
using detail::GridSamplerPadding;
|
| 14 |
+
|
| 15 |
+
// Unnormalizes a coordinate from the -1 to +1 scale to its pixel index value,
|
| 16 |
+
// where we view each pixel as an area between (idx - 0.5) and (idx + 0.5).
|
| 17 |
+
// if align_corners: -1 and +1 get sent to the centers of the corner pixels
|
| 18 |
+
// -1 --> 0
|
| 19 |
+
// +1 --> (size - 1)
|
| 20 |
+
// scale_factor = (size - 1) / 2
|
| 21 |
+
// if not align_corners: -1 and +1 get sent to the image edges
|
| 22 |
+
// -1 --> -0.5
|
| 23 |
+
// +1 --> (size - 1) + 0.5 == size - 0.5
|
| 24 |
+
// scale_factor = size / 2
|
| 25 |
+
template <typename scalar_t>
|
| 26 |
+
static inline scalar_t grid_sampler_unnormalize(scalar_t coord, int64_t size,
|
| 27 |
+
bool align_corners) {
|
| 28 |
+
if (align_corners) {
|
| 29 |
+
// unnormalize coord from [-1, 1] to [0, size - 1]
|
| 30 |
+
return ((coord + 1) / 2) * (size - 1);
|
| 31 |
+
} else {
|
| 32 |
+
// unnormalize coord from [-1, 1] to [-0.5, size - 0.5]
|
| 33 |
+
return ((coord + 1) * size - 1) / 2;
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
// grid_sampler_unnormalize_set_grad works the same as grid_sampler_unnormalize
|
| 38 |
+
// except that it also returns the `d output / d input` via pointer argument
|
| 39 |
+
// `grad_in`.
|
| 40 |
+
// This is useful in the backward pass of grid_sampler.
|
| 41 |
+
template <typename scalar_t>
|
| 42 |
+
static inline scalar_t grid_sampler_unnormalize_set_grad(scalar_t coord, int64_t size,
|
| 43 |
+
bool align_corners, scalar_t *grad_in) {
|
| 44 |
+
if (align_corners) {
|
| 45 |
+
// unnormalize coord from [-1, 1] to [0, size - 1]
|
| 46 |
+
*grad_in = static_cast<scalar_t>(size - 1) / 2;
|
| 47 |
+
return ((coord + 1) / 2) * (size - 1);
|
| 48 |
+
} else {
|
| 49 |
+
// unnormalize coord from [-1, 1] to [-0.5, size - 0.5]
|
| 50 |
+
*grad_in = static_cast<scalar_t>(size) / 2;
|
| 51 |
+
return ((coord + 1) * size - 1) / 2;
|
| 52 |
+
}
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
// Clips coordinates to between 0 and clip_limit - 1
|
| 56 |
+
template<typename scalar_t>
|
| 57 |
+
static inline scalar_t clip_coordinates(scalar_t in, int64_t clip_limit) {
|
| 58 |
+
return std::min(static_cast<scalar_t>(clip_limit - 1), std::max(in, static_cast<scalar_t>(0)));
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
// clip_coordinates_set_grad works similarly to clip_coordinates except that
|
| 62 |
+
// it also returns the `d output / d input` via pointer argument `grad_in`.
|
| 63 |
+
// This is useful in the backward pass of grid_sampler.
|
| 64 |
+
template<typename scalar_t>
|
| 65 |
+
static inline scalar_t clip_coordinates_set_grad(scalar_t in, int64_t clip_limit,
|
| 66 |
+
scalar_t *grad_in) {
|
| 67 |
+
// Note that it is important for the gradient calculation that borders
|
| 68 |
+
// are considered out of bounds.
|
| 69 |
+
if (in <= static_cast<scalar_t>(0)) {
|
| 70 |
+
*grad_in = static_cast<scalar_t>(0);
|
| 71 |
+
return static_cast<scalar_t>(0);
|
| 72 |
+
} else {
|
| 73 |
+
scalar_t max = static_cast<scalar_t>(clip_limit - 1);
|
| 74 |
+
if (in >= max) {
|
| 75 |
+
*grad_in = static_cast<scalar_t>(0);
|
| 76 |
+
return max;
|
| 77 |
+
} else {
|
| 78 |
+
*grad_in = static_cast<scalar_t>(1);
|
| 79 |
+
return in;
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
// Reflects coordinates until they fall between low and high (inclusive).
|
| 85 |
+
// The bounds are passed as twice their value so that half-integer values
|
| 86 |
+
// can be represented as ints.
|
| 87 |
+
template<typename scalar_t>
|
| 88 |
+
static inline scalar_t reflect_coordinates(scalar_t in, int64_t twice_low,
|
| 89 |
+
int64_t twice_high) {
|
| 90 |
+
if (twice_low == twice_high) {
|
| 91 |
+
return static_cast<scalar_t>(0);
|
| 92 |
+
}
|
| 93 |
+
scalar_t min = static_cast<scalar_t>(twice_low) / 2;
|
| 94 |
+
scalar_t span = static_cast<scalar_t>(twice_high - twice_low) / 2;
|
| 95 |
+
in = std::fabs(in - min);
|
| 96 |
+
// `fmod` returns same sign as `in`, which is positive after the `fabs` above.
|
| 97 |
+
scalar_t extra = std::fmod(in, span);
|
| 98 |
+
int flips = static_cast<int>(std::floor(in / span));
|
| 99 |
+
if (flips % 2 == 0) {
|
| 100 |
+
return extra + min;
|
| 101 |
+
} else {
|
| 102 |
+
return span - extra + min;
|
| 103 |
+
}
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
// reflect_coordinates_set_grad works similarly to reflect_coordinates except
|
| 107 |
+
// that it also returns the `d output / d input` via pointer argument
|
| 108 |
+
// `grad_in`.
|
| 109 |
+
// This is useful in the backward pass of grid_sampler.
|
| 110 |
+
template<typename scalar_t>
|
| 111 |
+
static inline scalar_t reflect_coordinates_set_grad(scalar_t in, int64_t twice_low,
|
| 112 |
+
int64_t twice_high, scalar_t *grad_in) {
|
| 113 |
+
if (twice_low == twice_high) {
|
| 114 |
+
*grad_in = static_cast<scalar_t>(0);
|
| 115 |
+
return static_cast<scalar_t>(0);
|
| 116 |
+
}
|
| 117 |
+
int grad_in_mult_;
|
| 118 |
+
scalar_t min = static_cast<scalar_t>(twice_low) / 2;
|
| 119 |
+
scalar_t span = static_cast<scalar_t>(twice_high - twice_low) / 2;
|
| 120 |
+
in = in - min;
|
| 121 |
+
if (in < static_cast<scalar_t>(0)) {
|
| 122 |
+
grad_in_mult_ = -1;
|
| 123 |
+
in = -in;
|
| 124 |
+
} else {
|
| 125 |
+
grad_in_mult_ = 1;
|
| 126 |
+
}
|
| 127 |
+
// `fmod` returns same sign as `in`, which is positive after the `if` above.
|
| 128 |
+
scalar_t extra = std::fmod(in, span);
|
| 129 |
+
int flips = static_cast<int>(std::floor(in / span));
|
| 130 |
+
if (flips % 2 == 0) {
|
| 131 |
+
*grad_in = static_cast<scalar_t>(grad_in_mult_);
|
| 132 |
+
return extra + min;
|
| 133 |
+
} else {
|
| 134 |
+
*grad_in = static_cast<scalar_t>(-grad_in_mult_);
|
| 135 |
+
return span - extra + min;
|
| 136 |
+
}
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
// Mapping the out-of-boundary points back into boundary
|
| 140 |
+
// This would only affect padding_mode=border or reflection
|
| 141 |
+
template<typename scalar_t>
|
| 142 |
+
static inline scalar_t compute_coordinates(scalar_t coord, int64_t size,
|
| 143 |
+
GridSamplerPadding padding_mode,
|
| 144 |
+
bool align_corners) {
|
| 145 |
+
if (padding_mode == GridSamplerPadding::Border) {
|
| 146 |
+
// clip coordinates to image borders
|
| 147 |
+
coord = clip_coordinates(coord, size);
|
| 148 |
+
} else if (padding_mode == GridSamplerPadding::Reflection) {
|
| 149 |
+
// reflect coordinates by image borders
|
| 150 |
+
if (align_corners) {
|
| 151 |
+
coord = reflect_coordinates(coord, 0, 2*(size - 1));
|
| 152 |
+
} else {
|
| 153 |
+
coord = reflect_coordinates(coord, -1, 2*size - 1);
|
| 154 |
+
}
|
| 155 |
+
// clip coordinates to image borders
|
| 156 |
+
coord = clip_coordinates(coord, size);
|
| 157 |
+
}
|
| 158 |
+
return coord;
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
// Computes the pixel source index value for a grid coordinate
|
| 162 |
+
template <typename scalar_t>
|
| 163 |
+
static inline scalar_t grid_sampler_compute_source_index(
|
| 164 |
+
scalar_t coord,
|
| 165 |
+
int64_t size,
|
| 166 |
+
GridSamplerPadding padding_mode,
|
| 167 |
+
bool align_corners) {
|
| 168 |
+
coord = grid_sampler_unnormalize(coord, size, align_corners);
|
| 169 |
+
coord = compute_coordinates(coord, size, padding_mode, align_corners);
|
| 170 |
+
return coord;
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
// grid_sampler_compute_source_index_set_grad works similarly to
|
| 174 |
+
// grid_sampler_compute_source_index except that it also returns the
|
| 175 |
+
// `d output / d input` via pointer argument `grad_in`.
|
| 176 |
+
// This is useful in the backward pass of grid_sampler.
|
| 177 |
+
template <typename scalar_t>
|
| 178 |
+
static inline scalar_t grid_sampler_compute_source_index_set_grad(
|
| 179 |
+
scalar_t coord,
|
| 180 |
+
int64_t size,
|
| 181 |
+
GridSamplerPadding padding_mode,
|
| 182 |
+
bool align_corners,
|
| 183 |
+
scalar_t *grad_in) {
|
| 184 |
+
scalar_t grad_clip, grad_refl;
|
| 185 |
+
coord = grid_sampler_unnormalize_set_grad(coord, size, align_corners, grad_in);
|
| 186 |
+
if (padding_mode == GridSamplerPadding::Border) {
|
| 187 |
+
// clip coordinates to image borders
|
| 188 |
+
coord = clip_coordinates_set_grad(coord, size, &grad_clip);
|
| 189 |
+
*grad_in = (*grad_in) * grad_clip;
|
| 190 |
+
} else if (padding_mode == GridSamplerPadding::Reflection) {
|
| 191 |
+
// reflect coordinates by image borders
|
| 192 |
+
if (align_corners) {
|
| 193 |
+
coord = reflect_coordinates_set_grad(coord, 0, 2*(size - 1), &grad_refl);
|
| 194 |
+
} else {
|
| 195 |
+
coord = reflect_coordinates_set_grad(coord, -1, 2*size - 1, &grad_refl);
|
| 196 |
+
}
|
| 197 |
+
// clip coordinates to image borders
|
| 198 |
+
coord = clip_coordinates_set_grad(coord, size, &grad_clip);
|
| 199 |
+
*grad_in = (*grad_in) * grad_refl * grad_clip;
|
| 200 |
+
}
|
| 201 |
+
return coord;
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
static inline bool within_bounds_2d(int64_t h, int64_t w, int64_t H, int64_t W) {
|
| 205 |
+
return h >= 0 && h < H && w >= 0 && w < W;
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
static inline bool within_bounds_3d(int64_t d, int64_t h, int64_t w, int64_t D, int64_t H, int64_t W) {
|
| 209 |
+
return d >= 0 && d < D && h >= 0 && h < H && w >= 0 && w < W;
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
template<typename scalar_t>
|
| 213 |
+
static inline scalar_t get_value_bounded(
|
| 214 |
+
const scalar_t* data,
|
| 215 |
+
scalar_t x,
|
| 216 |
+
scalar_t y,
|
| 217 |
+
int64_t W,
|
| 218 |
+
int64_t H,
|
| 219 |
+
int64_t sW,
|
| 220 |
+
int64_t sH,
|
| 221 |
+
GridSamplerPadding padding_mode,
|
| 222 |
+
bool align_corners) {
|
| 223 |
+
|
| 224 |
+
x = compute_coordinates(x, W, padding_mode, align_corners);
|
| 225 |
+
y = compute_coordinates(y, H, padding_mode, align_corners);
|
| 226 |
+
|
| 227 |
+
int64_t ix = static_cast<int64_t>(x);
|
| 228 |
+
int64_t iy = static_cast<int64_t>(y);
|
| 229 |
+
|
| 230 |
+
if (within_bounds_2d(iy, ix, H, W)) {
|
| 231 |
+
return data[iy * sH + ix * sW];
|
| 232 |
+
}
|
| 233 |
+
return static_cast<scalar_t>(0);
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
template<typename scalar_t>
|
| 237 |
+
static inline void safe_add_2d(scalar_t *data, int64_t h, int64_t w,
|
| 238 |
+
int64_t sH, int64_t sW, int64_t H, int64_t W,
|
| 239 |
+
scalar_t delta) {
|
| 240 |
+
if (within_bounds_2d(h, w, H, W)) {
|
| 241 |
+
data[h * sH + w * sW] += delta;
|
| 242 |
+
}
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
template<typename scalar_t>
|
| 246 |
+
static inline void safe_add_3d(scalar_t *data, int64_t d, int64_t h, int64_t w,
|
| 247 |
+
int64_t sD, int64_t sH, int64_t sW,
|
| 248 |
+
int64_t D, int64_t H, int64_t W,
|
| 249 |
+
scalar_t delta) {
|
| 250 |
+
if (within_bounds_3d(d, h, w, D, H, W)) {
|
| 251 |
+
data[d * sD + h * sH + w * sW] += delta;
|
| 252 |
+
}
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
template<typename scalar_t>
|
| 256 |
+
static inline void add_value_bounded(
|
| 257 |
+
scalar_t* data,
|
| 258 |
+
scalar_t x,
|
| 259 |
+
scalar_t y,
|
| 260 |
+
int64_t W,
|
| 261 |
+
int64_t H,
|
| 262 |
+
int64_t sW,
|
| 263 |
+
int64_t sH,
|
| 264 |
+
scalar_t delta,
|
| 265 |
+
GridSamplerPadding padding_mode,
|
| 266 |
+
bool align_corners) {
|
| 267 |
+
|
| 268 |
+
x = compute_coordinates(x, W, padding_mode, align_corners);
|
| 269 |
+
y = compute_coordinates(y, H, padding_mode, align_corners);
|
| 270 |
+
|
| 271 |
+
int64_t ix = static_cast<int64_t>(x);
|
| 272 |
+
int64_t iy = static_cast<int64_t>(y);
|
| 273 |
+
|
| 274 |
+
safe_add_2d(data, iy, ix, sH, sW, H, W, delta);
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
// Calculate the differential of the cubic convolution, i.e. `d coeff / d x`
|
| 278 |
+
template<typename scalar_t>
|
| 279 |
+
static inline void get_cubic_coefficients_grad(
|
| 280 |
+
scalar_t coeffs[4],
|
| 281 |
+
scalar_t t) {
|
| 282 |
+
|
| 283 |
+
// Must be the same as forward calculation in
|
| 284 |
+
// aten/src/ATen/native/UpSample.h:get_cubic_upsample_coefficients
|
| 285 |
+
scalar_t A = -0.75;
|
| 286 |
+
|
| 287 |
+
scalar_t x;
|
| 288 |
+
x = -1 - t; // 1 < x = |-1 - tx| < 2
|
| 289 |
+
coeffs[0] = (-3 * A * x - 10 * A ) * x - 8 * A;
|
| 290 |
+
x = -t; // x = |0 - tx| <= 1
|
| 291 |
+
coeffs[1] = (-3 * (A + 2) * x - 2 * (A + 3)) * x;
|
| 292 |
+
x = 1 - t; // x = |1 - tx| <= 1
|
| 293 |
+
coeffs[2] = (3 * (A + 2) * x - 2 * (A + 3)) * x;
|
| 294 |
+
x = 2 - t; // 1 < x = |2 - tx| < 2
|
| 295 |
+
coeffs[3] = (3 * A * x - 10 * A) * x + 8 * A;
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
} // namespace at::native
|
vllm/lib/python3.10/site-packages/torch/include/ATen/native/GridSamplerUtils.h
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// See NOTE: [Tensor vs. TensorBase]
|
| 4 |
+
// https://github.com/pytorch/pytorch/pull/66979
|
| 5 |
+
#include <ATen/core/TensorBase.h>
|
| 6 |
+
#include <ATen/native/TensorProperties.h>
|
| 7 |
+
#include <ATen/native/CanUse32BitIndexMath.h>
|
| 8 |
+
|
| 9 |
+
namespace at::native {
|
| 10 |
+
|
| 11 |
+
namespace detail {
|
| 12 |
+
|
| 13 |
+
enum class GridSamplerInterpolation {Bilinear, Nearest, Bicubic};
|
| 14 |
+
enum class GridSamplerPadding {Zeros, Border, Reflection};
|
| 15 |
+
|
| 16 |
+
} // namespace detail
|
| 17 |
+
|
| 18 |
+
using detail::GridSamplerInterpolation;
|
| 19 |
+
using detail::GridSamplerPadding;
|
| 20 |
+
|
| 21 |
+
// See NOTE [ grid_sampler Native Functions ].
|
| 22 |
+
inline void check_grid_sampler_common(
|
| 23 |
+
const TensorBase& input,
|
| 24 |
+
const TensorBase& grid
|
| 25 |
+
) {
|
| 26 |
+
auto input_opt = input.options();
|
| 27 |
+
auto grid_opt = grid.options();
|
| 28 |
+
|
| 29 |
+
TORCH_CHECK(
|
| 30 |
+
input.defined(),
|
| 31 |
+
"grid_sampler(): expected input to not be undefined");
|
| 32 |
+
TORCH_CHECK(
|
| 33 |
+
grid.defined(),
|
| 34 |
+
"grid_sampler(): expected grid to not be undefined");
|
| 35 |
+
TORCH_CHECK(
|
| 36 |
+
input_opt.device() == grid_opt.device(),
|
| 37 |
+
"grid_sampler(): expected input and grid to be on same device, but input "
|
| 38 |
+
"is on ", input_opt.device(), " and grid is on ", grid_opt.device());
|
| 39 |
+
TORCH_CHECK(
|
| 40 |
+
input_opt.layout() == kStrided && grid_opt.layout() == kStrided,
|
| 41 |
+
"grid_sampler(): expected input and grid to have torch.strided layout, but "
|
| 42 |
+
"input has ", input_opt.layout(), " and grid has ", grid_opt.layout());
|
| 43 |
+
TORCH_CHECK(
|
| 44 |
+
input.size(0) == grid.size(0),
|
| 45 |
+
"grid_sampler(): expected grid and input to have same batch size, but got "
|
| 46 |
+
"input with sizes ", input.sizes(), " and grid with sizes ", grid.sizes());
|
| 47 |
+
TORCH_CHECK(
|
| 48 |
+
grid.size(-1) == input.dim() - 2,
|
| 49 |
+
"grid_sampler(): expected grid to have size ", input.dim() - 2, " in last "
|
| 50 |
+
"dimension, but got grid with sizes ", grid.sizes());
|
| 51 |
+
|
| 52 |
+
for (const auto i : c10::irange(2, input.dim())) {
|
| 53 |
+
TORCH_CHECK(input.size(i) > 0,
|
| 54 |
+
"grid_sampler(): expected input to have non-empty spatial dimensions, "
|
| 55 |
+
"but input has sizes ", input.sizes(), " with dimension ", i, " being "
|
| 56 |
+
"empty");
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
// See NOTE [ grid_sampler Native Functions ].
|
| 61 |
+
inline void check_grid_sampler_2d(
|
| 62 |
+
const TensorBase& input,
|
| 63 |
+
const TensorBase& grid
|
| 64 |
+
) {
|
| 65 |
+
TORCH_CHECK(
|
| 66 |
+
input.dim() == 4 && input.dim() == grid.dim(),
|
| 67 |
+
"grid_sampler(): expected 4D input and grid with same number of "
|
| 68 |
+
"dimensions, but got input with sizes ", input.sizes(),
|
| 69 |
+
" and grid with sizes ", grid.sizes());
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
// See NOTE [ grid_sampler Native Functions ].
|
| 73 |
+
inline void check_grid_sampler_3d(
|
| 74 |
+
const TensorBase& input,
|
| 75 |
+
const TensorBase& grid,
|
| 76 |
+
int64_t interpolation_mode
|
| 77 |
+
) {
|
| 78 |
+
TORCH_CHECK(
|
| 79 |
+
input.dim() == 5 && input.dim() == grid.dim(),
|
| 80 |
+
"grid_sampler(): expected 5D input and grid with same number of "
|
| 81 |
+
"dimensions, but got input with sizes ", input.sizes(),
|
| 82 |
+
" and grid with sizes ", grid.sizes());
|
| 83 |
+
TORCH_CHECK(
|
| 84 |
+
!(input.dim() == 5 &&
|
| 85 |
+
static_cast<GridSamplerInterpolation>(interpolation_mode) ==
|
| 86 |
+
GridSamplerInterpolation::Bicubic),
|
| 87 |
+
"grid_sampler(): bicubic interpolation only supports 4D input");
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
// See NOTE [ grid_sampler Native Functions ].
|
| 91 |
+
// cudnn does not support inputs larger than 1024.
|
| 92 |
+
inline bool cond_cudnn_grid_sampler(
|
| 93 |
+
const TensorBase& input,
|
| 94 |
+
const TensorBase& grid
|
| 95 |
+
) {
|
| 96 |
+
return (
|
| 97 |
+
at::native::cudnn_is_acceptable(input) &&
|
| 98 |
+
at::native::cudnn_is_acceptable(grid) &&
|
| 99 |
+
at::native::canUse32BitIndexMath(input) &&
|
| 100 |
+
at::native::canUse32BitIndexMath(grid) &&
|
| 101 |
+
input.dim() == 4 &&
|
| 102 |
+
input.sym_size(1) <= 1024);
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
} // namespace at::native
|
vllm/lib/python3.10/site-packages/torch/include/ATen/native/IndexKernel.h
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
#include <ATen/native/DispatchStub.h>
|
| 3 |
+
#include <c10/util/ArrayRef.h>
|
| 4 |
+
|
| 5 |
+
namespace at {
|
| 6 |
+
class Tensor;
|
| 7 |
+
class TensorBase;
|
| 8 |
+
struct TensorIterator;
|
| 9 |
+
struct TensorIteratorBase;
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
namespace c10 {
|
| 13 |
+
class Scalar;
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
namespace at::native {
|
| 17 |
+
|
| 18 |
+
using index_fn = void(*)(TensorIteratorBase &, IntArrayRef indexed_sizes, IntArrayRef indexed_strides);
|
| 19 |
+
using index_fill_fn = void(*)(TensorIterator & iter, int64_t dim, int64_t self_dim_size, int64_t self_dim_stride, const Scalar& source);
|
| 20 |
+
using index_copy_fn = void(*)(TensorIterator & iter, int64_t dim, int64_t self_dim_size, int64_t self_dim_stride);
|
| 21 |
+
using index_put_fn = void(*)(TensorIterator &, IntArrayRef indexed_sizes, IntArrayRef indexed_strides, bool accumulate);
|
| 22 |
+
using put_fn = void(*)(TensorIterator & iter, const TensorBase& self, const bool accumulate);
|
| 23 |
+
using take_fn = void(*)(TensorIterator & iter, const TensorBase& input);
|
| 24 |
+
using flip_fn = void(*)(TensorIterator &, const bool);
|
| 25 |
+
using masked_fill_fn = void(*)(TensorIterator &, const Scalar& scalar);
|
| 26 |
+
using masked_select_fn = void(*)(TensorIterator &, int64_t orig_stride);
|
| 27 |
+
using masked_scatter_fn = void(*)(TensorIterator &, const TensorBase &);
|
| 28 |
+
|
| 29 |
+
DECLARE_DISPATCH(index_fn, index_stub);
|
| 30 |
+
DECLARE_DISPATCH(index_fill_fn, index_fill_stub);
|
| 31 |
+
DECLARE_DISPATCH(index_copy_fn, index_copy_stub);
|
| 32 |
+
DECLARE_DISPATCH(index_put_fn, index_put_stub);
|
| 33 |
+
DECLARE_DISPATCH(put_fn, put_stub);
|
| 34 |
+
DECLARE_DISPATCH(take_fn, take_stub);
|
| 35 |
+
DECLARE_DISPATCH(flip_fn, flip_stub);
|
| 36 |
+
DECLARE_DISPATCH(masked_fill_fn, masked_fill_stub);
|
| 37 |
+
DECLARE_DISPATCH(masked_select_fn, masked_select_serial_stub);
|
| 38 |
+
DECLARE_DISPATCH(masked_select_fn, masked_select_stub);
|
| 39 |
+
DECLARE_DISPATCH(masked_scatter_fn, masked_scatter_stub);
|
| 40 |
+
|
| 41 |
+
} // namespace at::native
|
vllm/lib/python3.10/site-packages/torch/include/ATen/native/Lerp.h
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <ATen/native/DispatchStub.h>
|
| 4 |
+
#include <ATen/OpMathType.h>
|
| 5 |
+
#include <ATen/TensorIterator.h>
|
| 6 |
+
#include <c10/core/Scalar.h>
|
| 7 |
+
|
| 8 |
+
namespace at::native {
|
| 9 |
+
|
| 10 |
+
template <typename scalar_t>
|
| 11 |
+
C10_HOST_DEVICE C10_ALWAYS_INLINE bool is_lerp_weight_small(scalar_t weight) {
|
| 12 |
+
return std::abs(weight) < scalar_t(0.5);
|
| 13 |
+
}
|
| 14 |
+
template <typename scalar_t>
|
| 15 |
+
C10_HOST_DEVICE C10_ALWAYS_INLINE bool is_lerp_weight_small(c10::complex<scalar_t> weight) {
|
| 16 |
+
// Avoid the sqrt in abs(weight)
|
| 17 |
+
return (weight.real() * weight.real() + weight.imag() * weight.imag()) < scalar_t(0.25);
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
template <typename scalar_t, typename weight_t>
|
| 21 |
+
C10_HOST_DEVICE C10_ALWAYS_INLINE scalar_t lerp(scalar_t self_, scalar_t end_, weight_t weight_) {
|
| 22 |
+
using opmath_t = at::opmath_type<scalar_t>;
|
| 23 |
+
using opmath_weight_t = at::opmath_type<weight_t>;
|
| 24 |
+
|
| 25 |
+
opmath_t self = self_;
|
| 26 |
+
opmath_t end = end_;
|
| 27 |
+
opmath_weight_t weight = weight_;
|
| 28 |
+
|
| 29 |
+
// Conditional for better numeric. This has been discussed in
|
| 30 |
+
// https://github.com/pytorch/pytorch/pull/18871
|
| 31 |
+
return is_lerp_weight_small(weight)
|
| 32 |
+
? self + weight * (end - self)
|
| 33 |
+
: end - (end - self) * (opmath_t(1) - weight);
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
using lerp_fn_scalar = void (*)(
|
| 37 |
+
at::TensorIteratorBase& iter,
|
| 38 |
+
const Scalar& weight);
|
| 39 |
+
|
| 40 |
+
using lerp_fn_tensor = void (*)(
|
| 41 |
+
at::TensorIteratorBase& iter);
|
| 42 |
+
|
| 43 |
+
DECLARE_DISPATCH(lerp_fn_scalar, lerp_kernel_scalar_weight);
|
| 44 |
+
DECLARE_DISPATCH(lerp_fn_tensor, lerp_kernel_tensor_weight);
|
| 45 |
+
|
| 46 |
+
} // namespace at::native
|
vllm/lib/python3.10/site-packages/torch/include/ATen/native/LinearAlgebraUtils.h
ADDED
|
@@ -0,0 +1,623 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <c10/core/ScalarType.h>
|
| 4 |
+
#include <c10/util/irange.h>
|
| 5 |
+
#include <c10/util/Exception.h>
|
| 6 |
+
#include <c10/util/strides.h>
|
| 7 |
+
#include <ATen/core/Tensor.h>
|
| 8 |
+
#include <ATen/ExpandUtils.h>
|
| 9 |
+
#include <ATen/TensorUtils.h>
|
| 10 |
+
#include <ATen/native/TensorIterator.h>
|
| 11 |
+
#include <ATen/native/TransposeType.h>
|
| 12 |
+
#include <limits>
|
| 13 |
+
#include <type_traits>
|
| 14 |
+
#include <sstream>
|
| 15 |
+
#include <cstring>
|
| 16 |
+
#include <cctype>
|
| 17 |
+
|
| 18 |
+
#ifndef AT_PER_OPERATOR_HEADERS
|
| 19 |
+
#include <ATen/Functions.h>
|
| 20 |
+
#else
|
| 21 |
+
#include <ATen/ops/arange.h>
|
| 22 |
+
#include <ATen/ops/empty.h>
|
| 23 |
+
#include <ATen/ops/empty_like.h>
|
| 24 |
+
#include <ATen/ops/empty_strided.h>
|
| 25 |
+
#include <ATen/ops/zeros.h>
|
| 26 |
+
#endif
|
| 27 |
+
|
| 28 |
+
namespace at::native {
|
| 29 |
+
|
| 30 |
+
inline c10::MaybeOwned<Tensor> expect_resolved_conj(const Tensor& tensor) {
|
| 31 |
+
if (tensor.is_conj()) {
|
| 32 |
+
return c10::MaybeOwned<Tensor>::owned(tensor.resolve_conj());
|
| 33 |
+
} else {
|
| 34 |
+
return c10::MaybeOwned<Tensor>::borrowed(tensor);
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
inline DimVector batched_matrix_contiguous_strides(
|
| 39 |
+
const IntArrayRef sizes,
|
| 40 |
+
const bool f_contig = false) {
|
| 41 |
+
// f_contig chooses between the strides of a batch of Fortran (F-contiguous)
|
| 42 |
+
// and C-contiguous matrices
|
| 43 |
+
auto strides = c10::contiguous_strides(sizes);
|
| 44 |
+
auto dim = strides.size();
|
| 45 |
+
|
| 46 |
+
if (f_contig && dim >= 2) {
|
| 47 |
+
// Fix the strides of the last two dimensions, so that we return
|
| 48 |
+
// C-contiguous batches of F-contiguous matrices.
|
| 49 |
+
strides[dim - 1] = std::max(sizes[dim - 2], static_cast<int64_t>(1));
|
| 50 |
+
strides[dim - 2] = 1;
|
| 51 |
+
}
|
| 52 |
+
return strides;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
/*
|
| 56 |
+
* Clones a Tensor so that the following conditions hold:
|
| 57 |
+
* If we think of a Tensor of having size (B, M, N), where B is any number
|
| 58 |
+
* of batch dimensions, then:
|
| 59 |
+
* - Each (M, N) matrix is in column major form
|
| 60 |
+
* - Let Tensor P have size (B, M, N) and Q have size (B, M', N').
|
| 61 |
+
* Then when laid out in memory, the M by N matrix starting at
|
| 62 |
+
* P.data_ptr()[B * M * N] is of the same corresponding batch as the M' by N'
|
| 63 |
+
* matrix starting at Q.data_ptr()[B * M' * N'].
|
| 64 |
+
*/
|
| 65 |
+
inline Tensor cloneBatchedColumnMajor(const Tensor& src) {
|
| 66 |
+
// If src is already in batched column major format, then
|
| 67 |
+
// this will be efficient (no reordering of the data will occur)
|
| 68 |
+
// because the first transpose will make the tensor contiguous,
|
| 69 |
+
// and cloning a contiguous tensor is fast.
|
| 70 |
+
auto result = src.mT().clone(at::MemoryFormat::Contiguous);
|
| 71 |
+
result.transpose_(-2, -1);
|
| 72 |
+
return result;
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
/*
|
| 76 |
+
* contig chooses between C-contig (true) and F-contig (false)
|
| 77 |
+
*/
|
| 78 |
+
inline c10::MaybeOwned<Tensor> borrow_else_clone(const bool cond, const Tensor& borrow, const Tensor& clone, const bool contig) {
|
| 79 |
+
return cond ? c10::MaybeOwned<Tensor>::borrowed(borrow)
|
| 80 |
+
: c10::MaybeOwned<Tensor>::owned(contig ? clone.clone(MemoryFormat::Contiguous)
|
| 81 |
+
: cloneBatchedColumnMajor(clone));
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
/*
|
| 85 |
+
* This method is designed to be a faster alternative to
|
| 86 |
+
* `cloneBatchedColumnMajor` with some additional features,
|
| 87 |
+
* namely:
|
| 88 |
+
* 1. It uses `copy` instead of `clone` which could be much faster.
|
| 89 |
+
* 2. `nrows` parameter used to create inputs with the number of rows larger
|
| 90 |
+
* than the original input, which is required for some LAPACK/MAGMA methods.
|
| 91 |
+
* 3. `desired_batch_size` is used to create copies with the batch size
|
| 92 |
+
* which is either the original batch size of the input, or its larger
|
| 93 |
+
* broadcasted shape.
|
| 94 |
+
*/
|
| 95 |
+
inline Tensor copyBatchedColumnMajor(const Tensor& src, int64_t nrows = -1,
|
| 96 |
+
at::OptionalIntArrayRef desired_batch_sizes = std::nullopt) {
|
| 97 |
+
nrows = (nrows == -1) ? src.size(-2) : nrows;
|
| 98 |
+
auto copy_sizes = desired_batch_sizes.has_value()
|
| 99 |
+
? desired_batch_sizes.value().vec()
|
| 100 |
+
: IntArrayRef(src.sizes().data(), src.dim() - 2).vec();
|
| 101 |
+
copy_sizes.insert(copy_sizes.end(), {nrows, src.size(-1)});
|
| 102 |
+
const auto copy_strides = batched_matrix_contiguous_strides(copy_sizes, /*f-contig*/true);
|
| 103 |
+
auto copy = at::empty_strided(copy_sizes, copy_strides, src.options());
|
| 104 |
+
copy.narrow(-2, 0, src.size(-2)).copy_(src);
|
| 105 |
+
return copy;
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
/*
|
| 109 |
+
* Given batches of matrices with arbitrary batch dim,
|
| 110 |
+
* computes the number of batches.
|
| 111 |
+
*/
|
| 112 |
+
inline int64_t batchCount(const Tensor& batched_matrices) {
|
| 113 |
+
int64_t result = 1;
|
| 114 |
+
for (int64_t i = 0; i < batched_matrices.ndimension() - 2; i++) {
|
| 115 |
+
result *= batched_matrices.size(i);
|
| 116 |
+
}
|
| 117 |
+
return result;
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
// Computes the number of elements of a matrix in a batched matrix tensor
|
| 121 |
+
inline int64_t matrixStride(const Tensor& batched_matrices) {
|
| 122 |
+
return batched_matrices.size(-1) * batched_matrices.size(-2);
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
// Validates input shapes for operations on batches of square matrices (inverse, cholesky, symeig, eig)
|
| 126 |
+
inline void checkIsMatrix(const Tensor& A, const char* const f_name, const char* const arg_name = "A") {
|
| 127 |
+
TORCH_CHECK(A.dim() >= 2, f_name, ": The input tensor ", arg_name, " must have at least 2 dimensions.");
|
| 128 |
+
}
|
| 129 |
+
inline void squareCheckInputs(const Tensor& self, const char* const f_name, const char* const arg_name = "A") {
|
| 130 |
+
checkIsMatrix(self, f_name, arg_name);
|
| 131 |
+
TORCH_CHECK(self.sym_size(-1) == self.sym_size(-2),
|
| 132 |
+
f_name,
|
| 133 |
+
": ", arg_name, " must be batches of square matrices, "
|
| 134 |
+
"but they are ", self.sym_size(-2), " by ", self.sym_size(-1), " matrices");
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
inline void checkInputsSolver(const Tensor& A,
|
| 138 |
+
const Tensor& B,
|
| 139 |
+
const bool left,
|
| 140 |
+
const char* const f_name) {
|
| 141 |
+
squareCheckInputs(A, f_name, "A");
|
| 142 |
+
checkIsMatrix(B, f_name, "B");
|
| 143 |
+
TORCH_CHECK(left ? A.size(-2) == B.size(-2) : A.size(-1) == B.size(-1),
|
| 144 |
+
f_name, ": Incompatible shapes of A and B for the equation ",
|
| 145 |
+
left ? "AX = B" : "XA = B",
|
| 146 |
+
" (", A.size(-2), "x", A.size(-1), " and ", B.size(-2), "x", B.size(-1), ")");
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
inline bool is_row_or_column_contiguous(const Tensor& t) {
|
| 150 |
+
// This could be made more general, similar to how it's checked in matmul, which would allow to
|
| 151 |
+
// ellide the copy with strides such as (6, 12, 1, 3) or (3, 1, 9), but this is quite tricky.
|
| 152 |
+
// We choose to be conservative for simplicity
|
| 153 |
+
return t.is_contiguous() || t.transpose(-2, -1).is_contiguous();
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
inline TransposeType to_transpose_type(const bool contig, const bool conj) {
|
| 157 |
+
if (conj) {
|
| 158 |
+
if (contig) { TORCH_INTERNAL_ASSERT(false, "Invalid transpose type"); }
|
| 159 |
+
else { return TransposeType::ConjTranspose; }
|
| 160 |
+
} else {
|
| 161 |
+
if (contig) { return TransposeType::NoTranspose; }
|
| 162 |
+
else { return TransposeType::Transpose; }
|
| 163 |
+
}
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
// This function is designed to be used with linear algebra methods that minimize
|
| 168 |
+
// L(ax - b) = 0, where L is generally the identity map (`solve`, for example)
|
| 169 |
+
// or the L2 norm (`lstsq`).
|
| 170 |
+
// It is expected that `a` and `b` are contiguous tensors of column-major matrices
|
| 171 |
+
// (so that a.view({-1, a.size(-2), a.size(-1)}) succeeds, same for `b`),
|
| 172 |
+
// with the following additional properties:
|
| 173 |
+
//
|
| 174 |
+
// 1. a.dim() == b.dim()
|
| 175 |
+
// 2. a.shape[:-2] broadcasts over b.shape[:-2]
|
| 176 |
+
// 3. a.size(i) <= b.size(i) for i=0,..., a.dim() - 3 (only for batch dimensions)
|
| 177 |
+
//
|
| 178 |
+
// MAGMA/LAPACK modify tensor `a` in-place, and the main goal of this method
|
| 179 |
+
// is to be memory efficient, which means that if there exists an index i such that
|
| 180 |
+
// a.shape[i] < b.shape[i], 0 <= i <= a.dim() - 3,
|
| 181 |
+
// then instead of materializing copies of `a` in the broadcasted shape, we keep
|
| 182 |
+
// a buffer copy of `a` along with flags that check whether specific batch dimension
|
| 183 |
+
// indices for `a` were already accessed. If they were, we copy the data from the buffer
|
| 184 |
+
// into `a`. The number of copies does not exceed
|
| 185 |
+
// prod(max(a.shape[:-2], b.shape[:-2]) - a.shape[:-2] + 1)
|
| 186 |
+
// and this value is attained by tensors with non-empty batch dimensions.
|
| 187 |
+
//
|
| 188 |
+
// func_t `f` is a callable that is being supplied with
|
| 189 |
+
// scalar_t* a_working_ptr, scalar_t* b_working_ptr, int64_t a_linear_batch_idx.
|
| 190 |
+
// a_working_ptr and b_working_ptr can directly be passed to LAPACK/MAGMA routines,
|
| 191 |
+
// and a_linear_batch_idx is an index in the 3d representation which corresponds to
|
| 192 |
+
// the memory a_working_ptr points to, in other words:
|
| 193 |
+
// a_working_ptr == a.view({-1, a.size(-2), a.size(-1)}.select(0, a_linear_batch_idx).data_ptr<scalar_t>();
|
| 194 |
+
// a_linear_batch_idx is useful to store metadata related to `a`, such as, for example,
|
| 195 |
+
// its rank or singular values (see linalg_lstsq).
|
| 196 |
+
template<typename scalar_t, typename func_t>
|
| 197 |
+
void batch_iterator_with_broadcasting(const Tensor& a, const Tensor& b, const func_t& f) {
|
| 198 |
+
IntArrayRef a_batch_sizes(a.sizes().data(), a.dim() - 2);
|
| 199 |
+
IntArrayRef b_batch_sizes(b.sizes().data(), b.dim() - 2);
|
| 200 |
+
|
| 201 |
+
auto a_linear_batch_idx = at::arange(batchCount(a)).view(a_batch_sizes);
|
| 202 |
+
auto b_linear_batch_idx = at::arange(batchCount(b)).view(b_batch_sizes);
|
| 203 |
+
|
| 204 |
+
TensorIterator iter = TensorIteratorConfig()
|
| 205 |
+
.set_check_mem_overlap(false)
|
| 206 |
+
.check_all_same_dtype(false)
|
| 207 |
+
.resize_outputs(false)
|
| 208 |
+
.add_output(b_linear_batch_idx)
|
| 209 |
+
.add_input(a_linear_batch_idx)
|
| 210 |
+
.build();
|
| 211 |
+
|
| 212 |
+
auto m = a.size(-2);
|
| 213 |
+
auto n = a.size(-1);
|
| 214 |
+
auto a_3d = a.view({batchCount(a), m, n});
|
| 215 |
+
auto b_3d = b.view({batchCount(b), b.size(-2), b.size(-1)});
|
| 216 |
+
|
| 217 |
+
auto a_broadcasts_over_b = (a_batch_sizes != b_batch_sizes);
|
| 218 |
+
Tensor a_buffer, a_was_accessed, a_buffer_3d;
|
| 219 |
+
std::function<void(int64_t)> check_if_copy_needed_for_a
|
| 220 |
+
= [](int64_t /*a_curr_linear_batch_idx*/){};
|
| 221 |
+
if (a_broadcasts_over_b) {
|
| 222 |
+
a_buffer = at::empty_strided(a.sizes(), a.strides(), a.options())
|
| 223 |
+
.copy_(a);
|
| 224 |
+
a_was_accessed = at::zeros(batchCount(a), at::kBool);
|
| 225 |
+
a_buffer_3d = a_buffer.view({batchCount(a), m, n});
|
| 226 |
+
check_if_copy_needed_for_a = [&](int64_t a_curr_linear_batch_idx) {
|
| 227 |
+
auto* a_was_accessed_flag = a_was_accessed
|
| 228 |
+
.select(0, a_curr_linear_batch_idx)
|
| 229 |
+
.data_ptr<bool>();
|
| 230 |
+
if (!(*a_was_accessed_flag)) {
|
| 231 |
+
*a_was_accessed_flag = true;
|
| 232 |
+
}
|
| 233 |
+
else {
|
| 234 |
+
a_3d.select(0, a_curr_linear_batch_idx)
|
| 235 |
+
.copy_(a_buffer_3d.select(0, a_curr_linear_batch_idx));
|
| 236 |
+
}
|
| 237 |
+
};
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
auto loop = [&](char** data, const int64_t* strides, int64_t nelems) {
|
| 241 |
+
auto* b_batch_idx_ptr = data[0];
|
| 242 |
+
auto* a_batch_idx_ptr = data[1];
|
| 243 |
+
|
| 244 |
+
for (const auto elem C10_UNUSED : c10::irange(nelems)) {
|
| 245 |
+
auto b_curr_linear_batch_idx = *reinterpret_cast<int64_t*>(b_batch_idx_ptr);
|
| 246 |
+
auto a_curr_linear_batch_idx = *reinterpret_cast<int64_t*>(a_batch_idx_ptr);
|
| 247 |
+
|
| 248 |
+
check_if_copy_needed_for_a(a_curr_linear_batch_idx);
|
| 249 |
+
|
| 250 |
+
auto* a_working_ptr = a_3d.select(0, a_curr_linear_batch_idx)
|
| 251 |
+
.data_ptr<scalar_t>();
|
| 252 |
+
auto* b_working_ptr = b_3d.select(0, b_curr_linear_batch_idx)
|
| 253 |
+
.data_ptr<scalar_t>();
|
| 254 |
+
f(a_working_ptr, b_working_ptr, a_curr_linear_batch_idx);
|
| 255 |
+
|
| 256 |
+
b_batch_idx_ptr += strides[0];
|
| 257 |
+
a_batch_idx_ptr += strides[1];
|
| 258 |
+
}
|
| 259 |
+
};
|
| 260 |
+
iter.serial_for_each(loop, {0, batchCount(b)});
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
// Returns the epsilon value for floating types except half
|
| 264 |
+
inline double _get_epsilon(const ScalarType& sc_type) {
|
| 265 |
+
switch (sc_type) {
|
| 266 |
+
case at::ScalarType::Float:
|
| 267 |
+
return static_cast<double>(std::numeric_limits<float>::epsilon());
|
| 268 |
+
case at::ScalarType::Double:
|
| 269 |
+
return std::numeric_limits<double>::epsilon();
|
| 270 |
+
default:
|
| 271 |
+
AT_ERROR("This function doesn't handle types other than float and double");
|
| 272 |
+
}
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
// Validates input shapes and devices
|
| 276 |
+
// for linear solve methods (solve, cholesky_solve, lu_solve, triangular_solve)
|
| 277 |
+
inline void linearSolveCheckInputs(const Tensor& self, const Tensor& A, const char* name) {
|
| 278 |
+
TORCH_CHECK(self.device() == A.device(),
|
| 279 |
+
"Expected b and A to be on the same device, but found b on ",
|
| 280 |
+
self.device(), " and A on ", A.device(), " instead.");
|
| 281 |
+
|
| 282 |
+
TORCH_CHECK(self.scalar_type() == A.scalar_type(),
|
| 283 |
+
"Expected b and A to have the same dtype, but found b of type ",
|
| 284 |
+
self.scalar_type(), " and A of type ", A.scalar_type(), " instead.");
|
| 285 |
+
|
| 286 |
+
TORCH_CHECK(A.size(-1) == A.size(-2),
|
| 287 |
+
"A must be batches of square matrices, "
|
| 288 |
+
"but they are ", A.size(-2), " by ", A.size(-1), " matrices");
|
| 289 |
+
|
| 290 |
+
TORCH_CHECK(A.size(-1) == self.size(-2),
|
| 291 |
+
"Incompatible matrix sizes for ", name, ": each A "
|
| 292 |
+
"matrix is ", A.size(-1), " by ", A.size(-1),
|
| 293 |
+
" but each b matrix is ", self.size(-2), " by ", self.size(-1));
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
inline void checkFloatingOrComplex(const Tensor& t, const char* const f_name, const bool allow_low_precision_dtypes=true) {
|
| 297 |
+
auto dtype = t.scalar_type();
|
| 298 |
+
TORCH_CHECK((at::isFloatingType(dtype) || at::isComplexType(dtype)),
|
| 299 |
+
f_name, ": Expected a floating point or complex tensor as input. Got ", dtype);
|
| 300 |
+
if (!allow_low_precision_dtypes) {
|
| 301 |
+
TORCH_CHECK(dtype == kFloat || dtype == kDouble || dtype == kComplexFloat || dtype == kComplexDouble,
|
| 302 |
+
f_name, ": Low precision dtypes not supported. Got ", dtype);
|
| 303 |
+
}
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
// Checks if all the Tensors in a TensorList are of the same dimensions
|
| 308 |
+
inline void checkAllSameDim(TensorList tensors, int64_t dim) {
|
| 309 |
+
for (auto &t : tensors) {
|
| 310 |
+
TORCH_CHECK(t.dim() == dim, "Tensor dimension is ", t.dim(), ", expected ", dim, " instead.");
|
| 311 |
+
}
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
inline std::tuple<std::vector<int64_t>, std::vector<int64_t>> _linalg_broadcast_batch_dims(const Tensor& arg1, const Tensor& arg2) {
|
| 315 |
+
// broadcast the batch dimensions of arg1 and arg2.
|
| 316 |
+
IntArrayRef arg1_batch_sizes(arg1.sizes().data(), arg1.ndimension() - 2);
|
| 317 |
+
IntArrayRef arg2_batch_sizes(arg2.sizes().data(), arg2.ndimension() - 2);
|
| 318 |
+
std::vector<int64_t> expand_batch_portion = infer_size(arg1_batch_sizes, arg2_batch_sizes);
|
| 319 |
+
|
| 320 |
+
std::vector<int64_t> arg1_expand_size({expand_batch_portion});
|
| 321 |
+
arg1_expand_size.insert(arg1_expand_size.end(), { arg1.size(-2), arg1.size(-1) });
|
| 322 |
+
|
| 323 |
+
std::vector<int64_t> arg2_expand_size({expand_batch_portion});
|
| 324 |
+
arg2_expand_size.insert(arg2_expand_size.end(), { arg2.size(-2), arg2.size(-1) });
|
| 325 |
+
return std::make_tuple(std::move(arg1_expand_size), std::move(arg2_expand_size));
|
| 326 |
+
}
|
| 327 |
+
|
| 328 |
+
inline std::tuple<Tensor,Tensor> _linalg_broadcast_batch_dims(const Tensor& arg1, const Tensor& arg2, const char* name) {
|
| 329 |
+
// If there's no name we assume we don't want to check the errors
|
| 330 |
+
if (name != nullptr) {
|
| 331 |
+
linearSolveCheckInputs(arg1, arg2, name);
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
auto [arg1_expand_size, arg2_expand_size] = at::native::_linalg_broadcast_batch_dims(arg1, arg2);
|
| 335 |
+
|
| 336 |
+
auto arg1_broadcasted = arg1_expand_size == arg1.sizes() ? arg1 : arg1.expand(arg1_expand_size);
|
| 337 |
+
auto arg2_broadcasted = arg2_expand_size == arg2.sizes() ? arg2 : arg2.expand(arg2_expand_size);
|
| 338 |
+
return std::make_tuple(arg1_broadcasted, arg2_broadcasted);
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
inline std::vector<int64_t> broadcast_batch_size(const Tensor& t1, const Tensor& t2, int64_t n_batch_dims) {
|
| 342 |
+
IntArrayRef t1_batch_sizes(t1.sizes().data(), n_batch_dims);
|
| 343 |
+
IntArrayRef t2_batch_sizes(t2.sizes().data(), n_batch_dims);
|
| 344 |
+
auto broadcasted_batch_sizes = infer_size(t1_batch_sizes, t2_batch_sizes);
|
| 345 |
+
return broadcasted_batch_sizes;
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
// Return a permutation with the given axes moved to the end.
|
| 349 |
+
inline Tensor _move_to_end(const Tensor& self, IntArrayRef axes) {
|
| 350 |
+
const std::vector<int64_t> a = axes.vec();
|
| 351 |
+
const int64_t ndim = self.ndimension();
|
| 352 |
+
std::vector<int64_t> perm;
|
| 353 |
+
|
| 354 |
+
for (const auto i : c10::irange(ndim)) {
|
| 355 |
+
auto it = std::find(a.begin(), a.end(), i);
|
| 356 |
+
if (it == a.end()) {
|
| 357 |
+
perm.push_back(i);
|
| 358 |
+
}
|
| 359 |
+
}
|
| 360 |
+
for (auto i : a) {
|
| 361 |
+
perm.push_back(i);
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
TORCH_CHECK((int64_t)perm.size() == ndim,
|
| 365 |
+
"duplicate or invalid axis in 'dim' argument for tensor with ndim==", ndim);
|
| 366 |
+
|
| 367 |
+
return self.permute(perm);
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
// parse the "mode" param in linalg_qr: return a tuple of bools (compute_q, reduced)
|
| 371 |
+
inline std::tuple<bool, bool> _parse_qr_mode(c10::string_view mode) {
|
| 372 |
+
bool compute_q;
|
| 373 |
+
bool reduced;
|
| 374 |
+
if (mode == "reduced") {
|
| 375 |
+
compute_q = true;
|
| 376 |
+
reduced = true;
|
| 377 |
+
} else if (mode == "complete") {
|
| 378 |
+
compute_q = true;
|
| 379 |
+
reduced = false;
|
| 380 |
+
} else if (mode == "r") {
|
| 381 |
+
compute_q = false;
|
| 382 |
+
reduced = true; // this is actually irrelevant in this mode
|
| 383 |
+
} else {
|
| 384 |
+
TORCH_CHECK(false, "qr received unrecognized mode '", mode,
|
| 385 |
+
"' but expected one of 'reduced' (default), 'r', or 'complete'");
|
| 386 |
+
}
|
| 387 |
+
return std::make_tuple(compute_q, reduced);
|
| 388 |
+
}
|
| 389 |
+
|
| 390 |
+
// Function to compute sizes, strides and the extra columns for the Q matrix in the QR Decomposition
|
| 391 |
+
inline std::tuple<DimVector, DimVector, int64_t> _compute_geometry_for_Q(
|
| 392 |
+
const Tensor& input,
|
| 393 |
+
bool reduced) {
|
| 394 |
+
int64_t m = input.size(-2), n = input.size(-1);
|
| 395 |
+
int64_t n_columns_q;
|
| 396 |
+
|
| 397 |
+
// We need to compute the required size of Q based on the `reduced` option
|
| 398 |
+
DimVector q_sizes(input.sizes());
|
| 399 |
+
if (!reduced && m > n) {
|
| 400 |
+
q_sizes[input.dim() - 1] = m;
|
| 401 |
+
n_columns_q = m;
|
| 402 |
+
} else {
|
| 403 |
+
q_sizes[input.dim() - 1] = n;
|
| 404 |
+
n_columns_q = std::min(m, n);
|
| 405 |
+
}
|
| 406 |
+
auto q_strides = batched_matrix_contiguous_strides(q_sizes, /*f-contig*/true);
|
| 407 |
+
return std::make_tuple(q_sizes, q_strides, n_columns_q);
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
inline bool svd_uses_cusolver(const Tensor& A) {
|
| 411 |
+
// if cusolver is available, it is used unconditionally
|
| 412 |
+
return A.is_cuda()
|
| 413 |
+
&& at::globalContext().hasCuSOLVER()
|
| 414 |
+
&& at::globalContext().linalgPreferredBackend() != at::LinalgBackend::Magma;
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
// Function used instead of .to so that the original strides are retained
|
| 419 |
+
// .to doesn't retain strides and make the output tensor contiguous
|
| 420 |
+
inline Tensor same_stride_to(const Tensor& original_tensor, const at::TensorOptions& options) {
|
| 421 |
+
auto strided_to = at::empty_strided(original_tensor.sizes(),
|
| 422 |
+
original_tensor.strides(),
|
| 423 |
+
options);
|
| 424 |
+
strided_to.copy_(original_tensor);
|
| 425 |
+
return strided_to;
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
// Creates a dimension permutation array that can be given to `at::permute()`, which will shift
|
| 429 |
+
// the two specified dimensions to the end of a tensor, without changing the order of
|
| 430 |
+
// the other dimensions. `dim1` will be placed at the very end, and `dim0` will be
|
| 431 |
+
// placed just to the left of it.
|
| 432 |
+
//
|
| 433 |
+
// For instance, given a 4-D tensor, dimensions 1 and 3 can be shifted to the end by
|
| 434 |
+
// calling `create_dim_backshift_permutation(1, 3, 4)`. The resulting vector will
|
| 435 |
+
// be `vec(0, 2, 1, 3)`.
|
| 436 |
+
inline std::vector<int64_t> create_dim_backshift_permutation(int64_t dim0, int64_t dim1, int64_t ndim) {
|
| 437 |
+
TORCH_CHECK(
|
| 438 |
+
(dim0 != dim1) && (dim0 < ndim) && (dim0 >= 0) && (dim1 < ndim) && (dim1 >= 0),
|
| 439 |
+
"duplicate or invalid dimensions");
|
| 440 |
+
std::vector<int64_t> permutation(ndim);
|
| 441 |
+
int64_t cur_permuted_dim = 0;
|
| 442 |
+
for (const auto dim_ind : c10::irange(ndim)) {
|
| 443 |
+
if ((dim_ind != dim0) && (dim_ind != dim1)) {
|
| 444 |
+
permutation[cur_permuted_dim++] = dim_ind;
|
| 445 |
+
}
|
| 446 |
+
}
|
| 447 |
+
permutation[cur_permuted_dim++] = dim0;
|
| 448 |
+
permutation[cur_permuted_dim] = dim1;
|
| 449 |
+
return permutation;
|
| 450 |
+
}
|
| 451 |
+
|
| 452 |
+
// Creates a dimension permutation array that can be given to `at::permute()`, which
|
| 453 |
+
// will reverse a given permutation.
|
| 454 |
+
// The reverse permutation array is created by swapping the indices and their
|
| 455 |
+
// associated values from the given permutation array.
|
| 456 |
+
inline std::vector<int64_t> create_reverse_permutation(std::vector<int64_t> permutation) {
|
| 457 |
+
int64_t ndim = permutation.size();
|
| 458 |
+
std::vector<int64_t> reverse_permutation(ndim);
|
| 459 |
+
for (const auto dim_ind : c10::irange(ndim)) {
|
| 460 |
+
reverse_permutation[permutation[dim_ind]] = dim_ind;
|
| 461 |
+
}
|
| 462 |
+
return reverse_permutation;
|
| 463 |
+
}
|
| 464 |
+
|
| 465 |
+
// Compute R-work array size for MAGMA/LAPACK cgesdd/zgesdd
|
| 466 |
+
// See https://github.com/Reference-LAPACK/lapack/blob/122506cd8b6ce050a200920c3d4c0b153b150fd8/SRC/cgesdd.f#L186
|
| 467 |
+
inline int64_t computeLRWorkDim(const char jobz, int64_t m, int64_t n) {
|
| 468 |
+
auto mn = std::min(m, n);
|
| 469 |
+
auto mx = std::max(m, n);
|
| 470 |
+
if (jobz == 'N') {
|
| 471 |
+
#ifdef __APPLE__
|
| 472 |
+
// According to `vecLib.framework/Headers/clapack.h` Accelerate.framework is based on LAPACK 3.2.1
|
| 473 |
+
return 7 * mn;
|
| 474 |
+
#else
|
| 475 |
+
// These setting is valid for on LAPACK 3.6+
|
| 476 |
+
return 5 * mn;
|
| 477 |
+
#endif
|
| 478 |
+
}
|
| 479 |
+
if (mx > 10 * mn) {
|
| 480 |
+
return 5 * mn * mn + 5 * mn;
|
| 481 |
+
}
|
| 482 |
+
return std::max(5 * mn * mn + 5 * mn, 2 * mx * mn + 2 * mn * mn + mn);
|
| 483 |
+
}
|
| 484 |
+
|
| 485 |
+
// This function checks whether the uplo argument input is valid
|
| 486 |
+
// Allowed strings are "u", "U", "l", "L"
|
| 487 |
+
inline void checkUplo(const c10::string_view uplo) {
|
| 488 |
+
// To use std::toupper safely with plain chars (or signed chars), the argument should first be converted to unsigned char
|
| 489 |
+
char uplo_uppercase = static_cast<char>(std::toupper(static_cast<unsigned char>(uplo[0])));
|
| 490 |
+
TORCH_CHECK(uplo.size() == 1 && (uplo_uppercase == 'U' || uplo_uppercase == 'L'),
|
| 491 |
+
"Expected UPLO argument to be 'L' or 'U', but got ", uplo);
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
inline void checkSameDevice(const std::string& fn_name, Tensor result, Tensor input, const std::string& result_name = "result") {
|
| 495 |
+
TORCH_CHECK(
|
| 496 |
+
result.device() == input.device(),
|
| 497 |
+
fn_name,
|
| 498 |
+
": Expected ", result_name, " and input tensors to be on the same device, but got ",
|
| 499 |
+
result_name, " on ", result.device(), " and input on ", input.device());
|
| 500 |
+
}
|
| 501 |
+
|
| 502 |
+
// Check the dtype of result and input tensors (for _out variants).
|
| 503 |
+
// Most linear algebra functions have the same dtype for input and output
|
| 504 |
+
// (either floating or complex type input), so we can check whether input's dtype can be casted to result's dtype.
|
| 505 |
+
// According to https://github.com/pytorch/pytorch/wiki/Developer-FAQ#how-does-out-work-in-pytorch
|
| 506 |
+
// c10::canCast is used for checking the "safe copy" dtype requirements.
|
| 507 |
+
inline void checkLinalgCompatibleDtype(const std::string& fn_name, Tensor result, Tensor input, const std::string& result_name = "result") {
|
| 508 |
+
bool can_cast = c10::canCast(input.scalar_type(), result.scalar_type());
|
| 509 |
+
TORCH_CHECK(
|
| 510 |
+
can_cast,
|
| 511 |
+
fn_name,
|
| 512 |
+
": Expected ", result_name, " to be safely castable from ", input.scalar_type(), " dtype, but got ",
|
| 513 |
+
result_name, " with dtype ", result.scalar_type());
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
// Alternatively, we can check whether the specific expected output type (result_type) can be safely casted to out tensor dtype (out_type)
|
| 517 |
+
inline void checkLinalgCompatibleDtype(const std::string& fn_name, ScalarType out_type, ScalarType result_type, const std::string& out_name = "result") {
|
| 518 |
+
bool can_cast = c10::canCast(result_type, out_type);
|
| 519 |
+
TORCH_CHECK(
|
| 520 |
+
can_cast,
|
| 521 |
+
fn_name,
|
| 522 |
+
": Expected ", out_name, " to be safely castable from ", result_type, " dtype, but got ",
|
| 523 |
+
out_name, " with dtype ", out_type);
|
| 524 |
+
}
|
| 525 |
+
|
| 526 |
+
inline void checkNotComplexTolerance(const Tensor& tol, const c10::string_view f_name, const c10::string_view tol_name) {
|
| 527 |
+
TORCH_CHECK(!at::isComplexType(tol.scalar_type()),
|
| 528 |
+
f_name, ": ", tol_name, " tensor of complex type is not supported. Got ", tol.scalar_type());
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
/*
|
| 532 |
+
Two types of 'other' tensors are supported when solving
|
| 533 |
+
a system of linear equations matmul(input, x) = other:
|
| 534 |
+
* 1-dimensional (1D) tensor or batch of 1D tensors (vector case)
|
| 535 |
+
* 2-dimensional (2D) tensor or batch of 2D tensors (matrix case).
|
| 536 |
+
The original torch.solve supported only the matrix case, while NumPy works for both cases.
|
| 537 |
+
For the batched input we need to be able to distinguish them.
|
| 538 |
+
Let input.shape = (batch_dimensions, m, n), then 'other' is of vector type if other.shape == (batch_dimensions, m).
|
| 539 |
+
This rule is compatible with NumPy, see https://github.com/numpy/numpy/blob/v1.20.0/numpy/linalg/linalg.py#L384-L389
|
| 540 |
+
*/
|
| 541 |
+
inline bool linalg_solve_is_vector_rhs(const Tensor& input, const Tensor& other) {
|
| 542 |
+
auto expected_batched_rhs_shape = SymIntArrayRef(input.sym_sizes().data(), input.dim() - 1); // input.shape[:-1]
|
| 543 |
+
bool vector_case = other.dim() == 1 || (input.dim() - 1 == other.dim() && other.sym_sizes().equals(expected_batched_rhs_shape));
|
| 544 |
+
return vector_case;
|
| 545 |
+
}
|
| 546 |
+
|
| 547 |
+
/*
|
| 548 |
+
Computes linear indices for a tensor with original_shape to access its elements like it was a materialized broadcast tensor.
|
| 549 |
+
*/
|
| 550 |
+
inline Tensor get_linear_indices(int64_t numel, IntArrayRef original_shape, IntArrayRef broadcast_shape) {
|
| 551 |
+
TensorOptions options = at::TensorOptions().dtype(at::kLong).device(at::kCPU);
|
| 552 |
+
return at::arange(numel, options).view(original_shape).broadcast_to(broadcast_shape).contiguous();
|
| 553 |
+
}
|
| 554 |
+
|
| 555 |
+
class BroadcastLinearIndices {
|
| 556 |
+
private:
|
| 557 |
+
Tensor linear_indices_;
|
| 558 |
+
bool is_broadcasting_;
|
| 559 |
+
|
| 560 |
+
public:
|
| 561 |
+
BroadcastLinearIndices(
|
| 562 |
+
int64_t numel,
|
| 563 |
+
IntArrayRef original_shape,
|
| 564 |
+
IntArrayRef broadcast_shape) : is_broadcasting_(!original_shape.equals(broadcast_shape)) {
|
| 565 |
+
// The assumption is that the broadcast_shape is a materialized broadcast
|
| 566 |
+
// shape of the original_shape. We need to compute the linear indices
|
| 567 |
+
// compatible with the original_shape to access the elements in the original
|
| 568 |
+
// tensor corresponding to the broadcast tensor.
|
| 569 |
+
if (is_broadcasting_) {
|
| 570 |
+
linear_indices_ =
|
| 571 |
+
get_linear_indices(numel, original_shape, broadcast_shape);
|
| 572 |
+
}
|
| 573 |
+
}
|
| 574 |
+
int64_t operator()(int64_t broadcast_linear_index) {
|
| 575 |
+
return is_broadcasting_
|
| 576 |
+
? linear_indices_.data_ptr<int64_t>()[broadcast_linear_index]
|
| 577 |
+
: broadcast_linear_index;
|
| 578 |
+
}
|
| 579 |
+
};
|
| 580 |
+
|
| 581 |
+
inline bool is_blas_compatible_column_major_order(const Tensor& input) {
|
| 582 |
+
IntArrayRef input_strides = input.strides();
|
| 583 |
+
IntArrayRef input_sizes = input.sizes();
|
| 584 |
+
auto ndim = input.dim();
|
| 585 |
+
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(ndim >= 2);
|
| 586 |
+
if (ndim > 3) {
|
| 587 |
+
return input.transpose(-2, -1).is_contiguous();
|
| 588 |
+
}
|
| 589 |
+
auto leading_dimension = input_strides[ndim - 1];
|
| 590 |
+
auto rows = input_sizes[ndim - 2];
|
| 591 |
+
bool batch_stride_compatible = true;
|
| 592 |
+
if (ndim == 3) {
|
| 593 |
+
auto cols = input_sizes[ndim - 1];
|
| 594 |
+
batch_stride_compatible =
|
| 595 |
+
input_strides[ndim - 3] >= leading_dimension * cols;
|
| 596 |
+
}
|
| 597 |
+
return (input_strides[ndim - 2] == 1) &&
|
| 598 |
+
(leading_dimension >= std::max<int64_t>(1, rows)) &&
|
| 599 |
+
batch_stride_compatible;
|
| 600 |
+
}
|
| 601 |
+
|
| 602 |
+
inline bool is_blas_compatible_row_major_order(const Tensor& input) {
|
| 603 |
+
IntArrayRef input_strides = input.strides();
|
| 604 |
+
IntArrayRef input_sizes = input.sizes();
|
| 605 |
+
auto ndim = input.dim();
|
| 606 |
+
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(ndim >= 2);
|
| 607 |
+
if (ndim > 3) {
|
| 608 |
+
return input.is_contiguous();
|
| 609 |
+
}
|
| 610 |
+
auto leading_dimension = input_strides[ndim - 2];
|
| 611 |
+
auto cols = input_sizes[ndim - 1];
|
| 612 |
+
bool batch_stride_compatible = true;
|
| 613 |
+
if (ndim == 3) {
|
| 614 |
+
auto rows = input_sizes[ndim - 2];
|
| 615 |
+
batch_stride_compatible =
|
| 616 |
+
input_strides[ndim - 3] >= leading_dimension * rows;
|
| 617 |
+
}
|
| 618 |
+
return (input_strides[ndim - 1] == 1) &&
|
| 619 |
+
(leading_dimension >= std::max<int64_t>(1, cols)) &&
|
| 620 |
+
batch_stride_compatible;
|
| 621 |
+
}
|
| 622 |
+
|
| 623 |
+
} // namespace at::native
|
vllm/lib/python3.10/site-packages/torch/include/ATen/native/Math.h
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|