language stringclasses 1 value | repo stringclasses 346 values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | bokeh__bokeh | src/bokeh/util/browser.py | {
"start": 1776,
"end": 4694
} | class ____:
''' A "no-op" web-browser controller.
'''
def open(self, url: str, new: TargetCode = 0, autoraise: bool = True) -> bool:
''' Receive standard arguments and take no action. '''
return True
def get_browser_controller(browser: str | None = None) -> BrowserLike:
''' Return a browser controller.
Args:
browser (str or None) : browser name, or ``None`` (default: ``None``)
If passed the string ``'none'``, a dummy web browser controller
is returned.
Otherwise, use the value to select an appropriate controller using
the :doc:`webbrowser <python:library/webbrowser>` standard library
module. If the value is ``None``, a system default is used.
Returns:
controller : a web browser controller
'''
browser = settings.browser(browser)
if browser is None:
controller = cast(BrowserLike, webbrowser)
elif browser == "none":
controller = DummyWebBrowser()
else:
controller = webbrowser.get(browser)
return controller
def view(location: str, browser: str | None = None, new: BrowserTarget = "same", autoraise: bool = True) -> None:
''' Open a browser to view the specified location.
Args:
location (str) : Location to open
If location does not begin with "http:" it is assumed
to be a file path on the local filesystem.
browser (str or None) : what browser to use (default: None)
If ``None``, use the system default browser.
new (str) : How to open the location. Valid values are:
``'same'`` - open in the current tab
``'tab'`` - open a new tab in the current window
``'window'`` - open in a new window
autoraise (bool) : Whether to automatically raise the location
in a new browser window (default: True)
Returns:
None
'''
try:
new_id = NEW_PARAM[new]
except KeyError:
raise RuntimeError(f"invalid 'new' value passed to view: {new!r}, valid values are: 'same', 'window', or 'tab'")
if location.startswith("http"):
url = location
else:
url = "file://" + abspath(location)
try:
controller = get_browser_controller(browser)
controller.open(url, new=new_id, autoraise=autoraise)
except Exception:
pass
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| DummyWebBrowser |
python | django-compressor__django-compressor | compressor/tests/test_filters.py | {
"start": 8939,
"end": 9320
} | class ____(TestCase):
def test_jsmin_filter(self):
content = """/*!
* django-compressor
* Copyright (c) 2009-2014 Django Compressor authors
*/
var foo = "bar";"""
output = """/*!
* django-compressor
* Copyright (c) 2009-2014 Django Compressor authors
*/var foo="bar";"""
self.assertEqual(output, rJSMinFilter(content).output())
| JsMinTestCase |
python | neetcode-gh__leetcode | python/1721-swapping-nodes-in-a-linked-list.py | {
"start": 151,
"end": 703
} | class ____:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
right_pointer = head
for _ in range(1, k):
right_pointer = right_pointer.next
left_kth_node = right_pointer
left_pointer = head
while right_pointer is not None:
right_kth_node = left_pointer
right_pointer = right_pointer.next
left_pointer = left_pointer.next
left_kth_node.val, right_kth_node.val = right_kth_node.val, left_kth_node.val
return head
| Solution |
python | tensorflow__tensorflow | tensorflow/python/client/session.py | {
"start": 14695,
"end": 15800
} | class ____(_FetchMapper):
"""Fetch mapper for lists, tuples, and namedtuples."""
def __init__(self, fetches):
"""Creates a _ListFetchMapper.
Args:
fetches: List, tuple, or namedtuple of fetches.
"""
if isinstance(fetches, wrapt.ObjectProxy):
self._fetch_type = type(fetches.__wrapped__)
else:
self._fetch_type = type(fetches)
self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers)
def unique_fetches(self):
return self._unique_fetches
def build_results(self, values):
# Create the list of results for each mapper.
results = []
for m, vi in zip(self._mappers, self._value_indices):
results.append(m.build_results([values[j] for j in vi]))
# Return a value of the original type of the fetches.
if issubclass(self._fetch_type, list):
return results
elif self._fetch_type == tuple:
return tuple(results)
else:
# This is the code path for namedtuple.
return self._fetch_type(*results)
| _ListFetchMapper |
python | getsentry__sentry | src/sentry/hybridcloud/rpc/service.py | {
"start": 1682,
"end": 4362
} | class ____(SerializableFunctionSignature):
"""Represent the contract for an RPC method.
This class is responsible for serializing and deserializing arguments. If the
base service runs in the region silo, this class is also responsible for
resolving the arguments to the correct region for a remote call.
"""
def __init__(self, base_service_cls: type[RpcService], base_method: Callable[..., Any]) -> None:
self.base_service_cls = base_service_cls
super().__init__(base_method, is_instance_method=True)
self._region_resolution = self._extract_region_resolution()
def _setup_exception(self, message: str) -> RpcServiceSetupException:
return RpcServiceSetupException(
self.base_service_cls.__name__, self.base_function.__name__, message
)
@property
def service_key(self) -> str:
return self.base_service_cls.key
@property
def service_name(self) -> str:
return self.base_service_cls.__name__
@property
def method_name(self) -> str:
return self.base_function.__name__
def __repr__(self) -> str:
return f"{type(self).__name__}({self.service_name!r}, {self.method_name!r})"
def __str__(self) -> str:
return f"{self.service_name}.{self.method_name}"
def get_name_segments(self) -> Sequence[str]:
return self.service_name, self.method_name
def _extract_region_resolution(self) -> RegionResolutionStrategy | None:
region_resolution = getattr(self.base_function, _REGION_RESOLUTION_ATTR, None)
is_region_service = self.base_service_cls.local_mode == SiloMode.REGION
if not is_region_service and region_resolution is not None:
raise self._setup_exception(
"@regional_rpc_method should be used only on a service with "
"`local_mode = SiloMode.REGION`"
)
if is_region_service and region_resolution is None:
raise self._setup_exception("Needs @regional_rpc_method")
return region_resolution
def resolve_to_region(self, arguments: ArgumentDict) -> _RegionResolutionResult:
if self._region_resolution is None:
raise self._setup_exception("Does not run on the region silo")
try:
region = self._region_resolution.resolve(arguments)
return _RegionResolutionResult(region)
except RegionMappingNotFound:
if getattr(self.base_function, _REGION_RESOLUTION_OPTIONAL_RETURN_ATTR, False):
return _RegionResolutionResult(None, is_early_halt=True)
else:
raise
@dataclass(frozen=True)
| RpcMethodSignature |
python | pytorch__pytorch | torch/onnx/_internal/exporter/_errors.py | {
"start": 440,
"end": 535
} | class ____(ConversionError):
"""Error during ONNX graph construction."""
| GraphConstructionError |
python | Textualize__rich | tests/test_inspect.py | {
"start": 2155,
"end": 18850
} | class ____(Foo):
pass
def test_render():
console = Console(width=100, file=io.StringIO(), legacy_windows=False)
foo = Foo("hello")
inspect(foo, console=console, all=True, value=False)
result = console.file.getvalue()
print(repr(result))
expected = "โญโโโโโโโโโโโโโโ <class 'tests.test_inspect.Foo'> โโโโโโโโโโโโโโโฎ\nโ Foo test โ\nโ โ\nโ broken = InspectError() โ\nโ __init__ = def __init__(foo: int) -> None: constructor docs. โ\nโ method = def method(a, b) -> str: Multi line โ\nโฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ\n"
assert result == expected
@skip_pypy3
def test_inspect_text():
num_attributes = 34 if sys.version_info >= (3, 11) else 33
expected = (
"โญโโโโโโโโโโโโโโโโ <class 'str'> โโโโโโโโโโโโโโโโโโฎ\n"
"โ str(object='') -> str โ\n"
"โ str(bytes_or_buffer[, encoding[, errors]]) -> โ\n"
"โ str โ\n"
"โ โ\n"
f"โ {num_attributes} attribute(s) not shown. Run โ\n"
"โ inspect(inspect) for options. โ\n"
"โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ\n"
)
print(repr(expected))
assert render("Hello") == expected
@skip_pypy3
def test_inspect_empty_dict():
expected = (
"โญโโโโโโโโโโโโโโโโ <class 'dict'> โโโโโโโโโโโโโโโโโฎ\n"
"โ dict() -> new empty dictionary โ\n"
"โ dict(mapping) -> new dictionary initialized โ\n"
"โ from a mapping object's โ\n"
"โ (key, value) pairs โ\n"
"โ dict(iterable) -> new dictionary initialized โ\n"
"โ as if via: โ\n"
"โ d = {} โ\n"
"โ for k, v in iterable: โ\n"
"โ d[k] = v โ\n"
"โ dict(**kwargs) -> new dictionary initialized โ\n"
"โ with the name=value pairs โ\n"
"โ in the keyword argument list. For โ\n"
"โ example: dict(one=1, two=2) โ\n"
"โ โ\n"
)
assert render({}).startswith(expected)
@skip_py314
@skip_py313
@skip_py312
@skip_py311
@skip_pypy3
def test_inspect_builtin_function_except_python311():
# Pre-3.11 Python versions - print builtin has no signature available
expected = (
"โญโโโโโโโโโโ <built-in function print> โโโโโโโโโโโโฎ\n"
"โ def print(...) โ\n"
"โ โ\n"
"โ print(value, ..., sep=' ', end='\\n', โ\n"
"โ file=sys.stdout, flush=False) โ\n"
"โ โ\n"
"โ 29 attribute(s) not shown. Run โ\n"
"โ inspect(inspect) for options. โ\n"
"โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ\n"
)
assert render(print) == expected
@pytest.mark.skipif(
sys.version_info < (3, 11), reason="print builtin signature only available on 3.11+"
)
@skip_pypy3
def test_inspect_builtin_function_only_python311():
# On 3.11, the print builtin *does* have a signature, unlike in prior versions
expected = (
"โญโโโโโโโโโโ <built-in function print> โโโโโโโโโโโโฎ\n"
"โ def print(*args, sep=' ', end='\\n', file=None, โ\n"
"โ flush=False): โ\n"
"โ โ\n"
"โ Prints the values to a stream, or to โ\n"
"โ sys.stdout by default. โ\n"
"โ โ\n"
"โ 30 attribute(s) not shown. Run โ\n"
"โ inspect(inspect) for options. โ\n"
"โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ\n"
)
assert render(print) == expected
@skip_pypy3
def test_inspect_coroutine():
async def coroutine():
pass
expected = (
"โญโ <function test_inspect_coroutine.<locals>.corโโฎ\n"
"โ async def โ\n"
"โ test_inspect_coroutine.<locals>.coroutine(): โ\n"
)
assert render(coroutine).startswith(expected)
def test_inspect_integer():
expected = (
"โญโโโโโโ <class 'int'> โโโโโโโโฎ\n"
"โ int([x]) -> integer โ\n"
"โ int(x, base=10) -> integer โ\n"
"โ โ\n"
"โ denominator = 1 โ\n"
"โ imag = 0 โ\n"
"โ numerator = 1 โ\n"
"โ real = 1 โ\n"
"โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ\n"
)
assert expected == render(1)
def test_inspect_integer_with_value():
expected = "โญโโโโโโ <class 'int'> โโโโโโโโฎ\nโ int([x]) -> integer โ\nโ int(x, base=10) -> integer โ\nโ โ\nโ โญโโโโโโโโโโโโโโโโโโโโโโโโโฎ โ\nโ โ 1 โ โ\nโ โฐโโโโโโโโโโโโโโโโโโโโโโโโโฏ โ\nโ โ\nโ denominator = 1 โ\nโ imag = 0 โ\nโ numerator = 1 โ\nโ real = 1 โ\nโฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ\n"
value = render(1, value=True)
print(repr(value))
assert value == expected
@skip_py310
@skip_py311
@skip_py312
@skip_py313
@skip_py314
def test_inspect_integer_with_methods_python38_and_python39():
expected = (
"โญโโโโโโโโโโโโโโโโ <class 'int'> โโโโโโโโโโโโโโโโโโฎ\n"
"โ int([x]) -> integer โ\n"
"โ int(x, base=10) -> integer โ\n"
"โ โ\n"
"โ denominator = 1 โ\n"
"โ imag = 0 โ\n"
"โ numerator = 1 โ\n"
"โ real = 1 โ\n"
"โ as_integer_ratio = def as_integer_ratio(): โ\n"
"โ Return integer ratio. โ\n"
"โ bit_length = def bit_length(): Number of โ\n"
"โ bits necessary to represent โ\n"
"โ self in binary. โ\n"
"โ conjugate = def conjugate(...) Returns โ\n"
"โ self, the complex conjugate โ\n"
"โ of any int. โ\n"
"โ from_bytes = def from_bytes(bytes, โ\n"
"โ byteorder, *, โ\n"
"โ signed=False): Return the โ\n"
"โ integer represented by the โ\n"
"โ given array of bytes. โ\n"
"โ to_bytes = def to_bytes(length, โ\n"
"โ byteorder, *, โ\n"
"โ signed=False): Return an โ\n"
"โ array of bytes representing โ\n"
"โ an integer. โ\n"
"โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ\n"
)
assert render(1, methods=True) == expected
@skip_py38
@skip_py39
@skip_py311
@skip_py312
@skip_py313
@skip_py314
def test_inspect_integer_with_methods_python310only():
expected = (
"โญโโโโโโโโโโโโโโโโ <class 'int'> โโโโโโโโโโโโโโโโโโฎ\n"
"โ int([x]) -> integer โ\n"
"โ int(x, base=10) -> integer โ\n"
"โ โ\n"
"โ denominator = 1 โ\n"
"โ imag = 0 โ\n"
"โ numerator = 1 โ\n"
"โ real = 1 โ\n"
"โ as_integer_ratio = def as_integer_ratio(): โ\n"
"โ Return integer ratio. โ\n"
"โ bit_count = def bit_count(): Number of โ\n"
"โ ones in the binary โ\n"
"โ representation of the โ\n"
"โ absolute value of self. โ\n"
"โ bit_length = def bit_length(): Number of โ\n"
"โ bits necessary to represent โ\n"
"โ self in binary. โ\n"
"โ conjugate = def conjugate(...) Returns โ\n"
"โ self, the complex conjugate โ\n"
"โ of any int. โ\n"
"โ from_bytes = def from_bytes(bytes, โ\n"
"โ byteorder, *, โ\n"
"โ signed=False): Return the โ\n"
"โ integer represented by the โ\n"
"โ given array of bytes. โ\n"
"โ to_bytes = def to_bytes(length, โ\n"
"โ byteorder, *, โ\n"
"โ signed=False): Return an โ\n"
"โ array of bytes representing โ\n"
"โ an integer. โ\n"
"โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ\n"
)
assert render(1, methods=True) == expected
@skip_py38
@skip_py39
@skip_py310
@skip_py312
@skip_py313
@skip_py314
def test_inspect_integer_with_methods_python311():
# to_bytes and from_bytes methods on int had minor signature change -
# they now, as of 3.11, have default values for all of their parameters
expected = (
"โญโโโโโโโโโโโโโโโโ <class 'int'> โโโโโโโโโโโโโโโโโโฎ\n"
"โ int([x]) -> integer โ\n"
"โ int(x, base=10) -> integer โ\n"
"โ โ\n"
"โ denominator = 1 โ\n"
"โ imag = 0 โ\n"
"โ numerator = 1 โ\n"
"โ real = 1 โ\n"
"โ as_integer_ratio = def as_integer_ratio(): โ\n"
"โ Return integer ratio. โ\n"
"โ bit_count = def bit_count(): Number of โ\n"
"โ ones in the binary โ\n"
"โ representation of the โ\n"
"โ absolute value of self. โ\n"
"โ bit_length = def bit_length(): Number of โ\n"
"โ bits necessary to represent โ\n"
"โ self in binary. โ\n"
"โ conjugate = def conjugate(...) Returns โ\n"
"โ self, the complex conjugate โ\n"
"โ of any int. โ\n"
"โ from_bytes = def from_bytes(bytes, โ\n"
"โ byteorder='big', *, โ\n"
"โ signed=False): Return the โ\n"
"โ integer represented by the โ\n"
"โ given array of bytes. โ\n"
"โ to_bytes = def to_bytes(length=1, โ\n"
"โ byteorder='big', *, โ\n"
"โ signed=False): Return an โ\n"
"โ array of bytes representing โ\n"
"โ an integer. โ\n"
"โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ\n"
)
assert render(1, methods=True) == expected
@skip_pypy3
def test_broken_call_attr():
class NotCallable:
__call__ = 5 # Passes callable() but isn't really callable
def __repr__(self):
return "NotCallable()"
class Foo:
foo = NotCallable()
foo = Foo()
assert callable(foo.foo)
expected = "โญโ <class 'tests.test_inspect.test_broken_call_attr.<locals>.Foo'> โโฎ\nโ foo = NotCallable() โ\nโฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ\n"
result = render(foo, methods=True, width=100)
print(repr(result))
assert expected == result
def test_inspect_swig_edge_case():
"""Issue #1838 - Edge case with Faiss library - object with empty dir()"""
class Thing:
@property
def __class__(self):
raise AttributeError
thing = Thing()
try:
inspect(thing)
except Exception as e:
assert False, f"Object with no __class__ shouldn't raise {e}"
def test_inspect_module_with_class():
def function():
pass
class Thing:
"""Docstring"""
pass
module = ModuleType("my_module")
module.SomeClass = Thing
module.function = function
expected = (
"โญโโโโโโโโโโ <module 'my_module'> โโโโโโโโโโโฎ\n"
"โ function = def function(): โ\n"
"โ SomeClass = class SomeClass(): Docstring โ\n"
"โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ\n"
)
assert render(module, methods=True) == expected
@pytest.mark.parametrize(
"special_character,expected_replacement",
(
("\a", "\\a"),
("\b", "\\b"),
("\f", "\\f"),
("\r", "\\r"),
("\v", "\\v"),
),
)
def test_can_handle_special_characters_in_docstrings(
special_character: str, expected_replacement: str
) -> None:
class Something:
class Thing:
pass
Something.Thing.__doc__ = f"""
Multiline docstring
with {special_character} should be handled
"""
expected = """\
โญโ <class 'tests.test_inspect.test_can_handle_spโโฎ
โ class โ
โ test_can_handle_special_characters_in_docstrin โ
โ gs.<locals>.Something(): โ
โ โ
โ Thing = class Thing(): โ
โ Multiline docstring โ
โ with %s should be handled โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
""" % (
expected_replacement
)
assert render(Something, methods=True) == expected
@pytest.mark.parametrize(
"obj,expected_result",
(
[object, (object,)],
[object(), (object,)],
["hi", (str, object)],
[str, (str, object)],
[Foo(1), (Foo, object)],
[Foo, (Foo, object)],
[FooSubclass(1), (FooSubclass, Foo, object)],
[FooSubclass, (FooSubclass, Foo, object)],
),
)
def test_object_types_mro(obj: object, expected_result: Sequence[Type]):
assert get_object_types_mro(obj) == expected_result
@pytest.mark.parametrize(
"obj,expected_result",
(
# fmt: off
["hi", ["builtins.str", "builtins.object"]],
[str, ["builtins.str", "builtins.object"]],
[Foo(1), [f"{__name__}.Foo", "builtins.object"]],
[Foo, [f"{__name__}.Foo", "builtins.object"]],
[FooSubclass(1),
[f"{__name__}.FooSubclass", f"{__name__}.Foo", "builtins.object"]],
[FooSubclass,
[f"{__name__}.FooSubclass", f"{__name__}.Foo", "builtins.object"]],
# fmt: on
),
)
def test_object_types_mro_as_strings(obj: object, expected_result: Sequence[str]):
assert get_object_types_mro_as_strings(obj) == expected_result
@pytest.mark.parametrize(
"obj,types,expected_result",
(
# fmt: off
["hi", ["builtins.str"], True],
[str, ["builtins.str"], True],
["hi", ["builtins.str", "foo"], True],
[str, ["builtins.str", "foo"], True],
[Foo(1), [f"{__name__}.Foo"], True],
[Foo, [f"{__name__}.Foo"], True],
[Foo(1), ["builtins.str", f"{__name__}.Foo"], True],
[Foo, ["builtins.int", f"{__name__}.Foo"], True],
[Foo(1), [f"{__name__}.FooSubclass"], False],
[Foo, [f"{__name__}.FooSubclass"], False],
[Foo(1), [f"{__name__}.FooSubclass", f"{__name__}.Foo"], True],
[Foo, [f"{__name__}.Foo", f"{__name__}.FooSubclass"], True],
# fmt: on
),
)
def test_object_is_one_of_types(
obj: object, types: Sequence[str], expected_result: bool
):
assert is_object_one_of_types(obj, types) is expected_result
| FooSubclass |
python | huggingface__transformers | src/transformers/models/bert/modeling_bert.py | {
"start": 21239,
"end": 21849
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.transform = BertPredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
def forward(self, hidden_states):
hidden_states = self.transform(hidden_states)
hidden_states = self.decoder(hidden_states)
return hidden_states
| BertLMPredictionHead |
python | django__django | tests/auth_tests/test_decorators.py | {
"start": 4206,
"end": 9682
} | class ____(TestCase):
"""
Tests for the permission_required decorator
"""
factory = RequestFactory()
@classmethod
def setUpTestData(cls):
cls.user = models.User.objects.create(username="joe", password="qwerty")
# Add permissions auth.add_customuser and auth.change_customuser
perms = models.Permission.objects.filter(
codename__in=("add_customuser", "change_customuser")
)
cls.user.user_permissions.add(*perms)
@classmethod
async def auser(cls):
return cls.user
def test_wrapped_sync_function_is_not_coroutine_function(self):
def sync_view(request):
return HttpResponse()
wrapped_view = permission_required([])(sync_view)
self.assertIs(iscoroutinefunction(wrapped_view), False)
def test_wrapped_async_function_is_coroutine_function(self):
async def async_view(request):
return HttpResponse()
wrapped_view = permission_required([])(async_view)
self.assertIs(iscoroutinefunction(wrapped_view), True)
def test_many_permissions_pass(self):
@permission_required(
["auth_tests.add_customuser", "auth_tests.change_customuser"]
)
def a_view(request):
return HttpResponse()
request = self.factory.get("/rand")
request.user = self.user
resp = a_view(request)
self.assertEqual(resp.status_code, 200)
def test_many_permissions_in_set_pass(self):
@permission_required(
{"auth_tests.add_customuser", "auth_tests.change_customuser"}
)
def a_view(request):
return HttpResponse()
request = self.factory.get("/rand")
request.user = self.user
resp = a_view(request)
self.assertEqual(resp.status_code, 200)
def test_single_permission_pass(self):
@permission_required("auth_tests.add_customuser")
def a_view(request):
return HttpResponse()
request = self.factory.get("/rand")
request.user = self.user
resp = a_view(request)
self.assertEqual(resp.status_code, 200)
def test_permissioned_denied_redirect(self):
@permission_required(
[
"auth_tests.add_customuser",
"auth_tests.change_customuser",
"nonexistent-permission",
]
)
def a_view(request):
return HttpResponse()
request = self.factory.get("/rand")
request.user = self.user
resp = a_view(request)
self.assertEqual(resp.status_code, 302)
def test_permissioned_denied_exception_raised(self):
@permission_required(
[
"auth_tests.add_customuser",
"auth_tests.change_customuser",
"nonexistent-permission",
],
raise_exception=True,
)
def a_view(request):
return HttpResponse()
request = self.factory.get("/rand")
request.user = self.user
with self.assertRaises(PermissionDenied):
a_view(request)
async def test_many_permissions_pass_async_view(self):
@permission_required(
["auth_tests.add_customuser", "auth_tests.change_customuser"]
)
async def async_view(request):
return HttpResponse()
request = self.factory.get("/rand")
request.auser = self.auser
response = await async_view(request)
self.assertEqual(response.status_code, 200)
async def test_many_permissions_in_set_pass_async_view(self):
@permission_required(
{"auth_tests.add_customuser", "auth_tests.change_customuser"}
)
async def async_view(request):
return HttpResponse()
request = self.factory.get("/rand")
request.auser = self.auser
response = await async_view(request)
self.assertEqual(response.status_code, 200)
async def test_single_permission_pass_async_view(self):
@permission_required("auth_tests.add_customuser")
async def async_view(request):
return HttpResponse()
request = self.factory.get("/rand")
request.auser = self.auser
response = await async_view(request)
self.assertEqual(response.status_code, 200)
async def test_permissioned_denied_redirect_async_view(self):
@permission_required(
[
"auth_tests.add_customuser",
"auth_tests.change_customuser",
"nonexistent-permission",
]
)
async def async_view(request):
return HttpResponse()
request = self.factory.get("/rand")
request.auser = self.auser
response = await async_view(request)
self.assertEqual(response.status_code, 302)
async def test_permissioned_denied_exception_raised_async_view(self):
@permission_required(
[
"auth_tests.add_customuser",
"auth_tests.change_customuser",
"nonexistent-permission",
],
raise_exception=True,
)
async def async_view(request):
return HttpResponse()
request = self.factory.get("/rand")
request.auser = self.auser
with self.assertRaises(PermissionDenied):
await async_view(request)
| PermissionsRequiredDecoratorTest |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/metadata/external_metadata.py | {
"start": 739,
"end": 5040
} | class ____(TypedDict):
type: "ExternalMetadataType"
raw_value: InferrableExternalMetadataValue
# Infer the type from the raw value on the orchestration end
EXTERNAL_METADATA_TYPE_INFER = "__infer__"
ExternalMetadataType = Literal[
"__infer__",
"text",
"url",
"path",
"notebook",
"json",
"md",
"float",
"int",
"bool",
"dagster_run",
"asset",
"null",
"table",
"table_schema",
"table_column_lineage",
"timestamp",
]
EXTERNAL_METADATA_VALUE_KEYS = frozenset(ExternalMetadataValue.__annotations__.keys())
EXTERNAL_METADATA_TYPES = frozenset(get_args(ExternalMetadataType))
def metadata_map_from_external(
metadata: Mapping[str, ExternalMetadataValue],
) -> Mapping[str, "MetadataValue"]:
return {k: metadata_value_from_external(v["raw_value"], v["type"]) for k, v in metadata.items()}
def metadata_value_from_external(
value: Any, metadata_type: ExternalMetadataType
) -> "MetadataValue":
from dagster._core.definitions.metadata import MetadataValue, normalize_metadata_value
if metadata_type == EXTERNAL_METADATA_TYPE_INFER:
return normalize_metadata_value(value)
elif metadata_type == "text":
return MetadataValue.text(value)
elif metadata_type == "url":
return MetadataValue.url(value)
elif metadata_type == "path":
return MetadataValue.path(value)
elif metadata_type == "notebook":
return MetadataValue.notebook(value)
elif metadata_type == "json":
return MetadataValue.json(value)
elif metadata_type == "md":
return MetadataValue.md(value)
elif metadata_type == "float":
return MetadataValue.float(value)
elif metadata_type == "int":
return MetadataValue.int(value)
elif metadata_type == "bool":
return MetadataValue.bool(value)
elif metadata_type == "dagster_run":
return MetadataValue.dagster_run(value)
elif metadata_type == "asset":
return MetadataValue.asset(AssetKey.from_user_string(value))
elif metadata_type == "table":
value = check.mapping_param(value, "table_value", key_type=str)
return MetadataValue.table(
records=[TableRecord(record) for record in value["records"]],
schema=TableSchema(
columns=[
TableColumn(
name=column["name"],
type=column["type"],
description=column.get("description"),
tags=column.get("tags"),
constraints=TableColumnConstraints(**column["constraints"])
if column.get("constraints")
else None,
)
for column in value["schema"]
]
),
)
elif metadata_type == "table_schema":
value = check.mapping_param(value, "table_schema_value", key_type=str)
return MetadataValue.table_schema(
schema=TableSchema(
columns=[
TableColumn(
name=column["name"],
type=column["type"],
description=column.get("description"),
tags=column.get("tags"),
constraints=TableColumnConstraints(**column["constraints"])
if column.get("constraints")
else None,
)
for column in value["columns"]
]
)
)
elif metadata_type == "table_column_lineage":
value = check.mapping_param(value, "table_column_value", key_type=str)
return MetadataValue.column_lineage(
lineage=TableColumnLineage(
deps_by_column={
column: [TableColumnDep(**dep) for dep in deps]
for column, deps in value["deps_by_column"].items()
}
)
)
elif metadata_type == "timestamp":
return MetadataValue.timestamp(float(check.numeric_param(value, "timestamp")))
elif metadata_type == "null":
return MetadataValue.null()
else:
check.failed(f"Unexpected metadata type {metadata_type}")
| ExternalMetadataValue |
python | openai__openai-python | src/openai/types/upload.py | {
"start": 246,
"end": 1207
} | class ____(BaseModel):
id: str
"""The Upload unique identifier, which can be referenced in API endpoints."""
bytes: int
"""The intended number of bytes to be uploaded."""
created_at: int
"""The Unix timestamp (in seconds) for when the Upload was created."""
expires_at: int
"""The Unix timestamp (in seconds) for when the Upload will expire."""
filename: str
"""The name of the file to be uploaded."""
object: Literal["upload"]
"""The object type, which is always "upload"."""
purpose: str
"""The intended purpose of the file.
[Please refer here](https://platform.openai.com/docs/api-reference/files/object#files/object-purpose)
for acceptable values.
"""
status: Literal["pending", "completed", "cancelled", "expired"]
"""The status of the Upload."""
file: Optional[FileObject] = None
"""The `File` object represents a document that has been uploaded to OpenAI."""
| Upload |
python | pytorch__pytorch | torch/utils/data/datapipes/map/combining.py | {
"start": 2252,
"end": 3903
} | class ____(MapDataPipe[tuple[_T_co, ...]]):
r"""
Aggregates elements into a tuple from each of the input DataPipes (functional name: ``zip``).
This MataPipe is out of bound as soon as the shortest input DataPipe is exhausted.
Args:
*datapipes: Map DataPipes being aggregated
Example:
>>> # xdoctest: +SKIP
>>> from torchdata.datapipes.map import SequenceWrapper
>>> dp1 = SequenceWrapper(range(3))
>>> dp2 = SequenceWrapper(range(10, 13))
>>> zip_dp = dp1.zip(dp2)
>>> list(zip_dp)
[(0, 10), (1, 11), (2, 12)]
"""
datapipes: tuple[MapDataPipe[_T_co], ...]
def __init__(self, *datapipes: MapDataPipe[_T_co]) -> None:
if len(datapipes) == 0:
raise ValueError("Expected at least one DataPipe, but got nothing")
if not all(isinstance(dp, MapDataPipe) for dp in datapipes):
raise TypeError("Expected all inputs to be `MapDataPipe`")
if not all(isinstance(dp, Sized) for dp in datapipes):
raise TypeError("Expected all inputs to be `Sized`")
self.datapipes = datapipes
def __getitem__(self, index) -> tuple[_T_co, ...]:
res = []
for dp in self.datapipes:
try:
res.append(dp[index])
except IndexError as e:
raise IndexError(
f"Index {index} is out of range for one of the input MapDataPipes {dp}."
) from e
return tuple(res)
def __len__(self) -> int:
# pyrefly: ignore [bad-argument-type]
return min(len(dp) for dp in self.datapipes)
| ZipperMapDataPipe |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_project_stacktrace_link.py | {
"start": 8444,
"end": 14809
} | class ____(BaseProjectStacktraceLink):
def setUp(self) -> None:
BaseProjectStacktraceLink.setUp(self)
self.android_code_mapping = self._create_code_mapping(
stack_root="usr/src/getsentry/",
source_root="src/getsentry/",
)
self.flutter_code_mapping = self._create_code_mapping(
stack_root="a/b/",
source_root="",
)
self.cocoa_code_mapping_filename = self._create_code_mapping(
stack_root="AppDelegate",
source_root="src/AppDelegate",
)
self.cocoa_code_mapping_abs_path = self._create_code_mapping(
stack_root="/Users/user/code/SwiftySampleProject/",
source_root="src/",
)
@patch.object(ExampleIntegration, "get_stacktrace_link")
def test_munge_android_worked(self, mock_integration: MagicMock) -> None:
file_path = "src/getsentry/file.java"
mock_integration.side_effect = [f"{example_base_url}/{file_path}"]
response = self.get_success_response(
self.organization.slug,
self.project.slug,
qs_params={
"file": "file.java",
"absPath": "file.java",
"module": "usr.src.getsentry.file",
"platform": "java",
},
)
assert response.data["config"] == self.expected_configurations(self.android_code_mapping)
assert response.data["sourceUrl"] == f"{example_base_url}/{file_path}"
@patch.object(ExampleIntegration, "get_stacktrace_link")
def test_munge_android_failed_stack_root_mismatch(self, mock_integration: MagicMock) -> None:
"""
Returns a stack_root_mismatch if module doesn't match stack root
"""
file_path = "src/getsentry/file.java"
mock_integration.side_effect = [f"{example_base_url}/{file_path}"]
response = self.get_success_response(
self.organization.slug,
self.project.slug,
qs_params={
"file": "file.java",
"module": "foo.src.getsentry.file", # Should not match code mapping
"platform": "java",
},
)
assert not response.data["config"]
assert not response.data["sourceUrl"]
assert response.data["error"] == "stack_root_mismatch"
assert response.data["integrations"] == [serialized_integration(self.integration)]
@patch.object(ExampleIntegration, "get_stacktrace_link")
def test_cocoa_abs_path_success(self, mock_integration: MagicMock) -> None:
"""
Cocoa events with code mappings referencing the abs_path should apply correctly.
"""
filename = "AppDelegate.swift"
mock_integration.side_effect = [f"{example_base_url}/src/{filename}"]
response = self.get_success_response(
self.organization.slug,
self.project.slug,
qs_params={
"file": "AppDelegate.swift",
"absPath": f"/Users/user/code/SwiftySampleProject/{filename}",
"package": "SampleProject",
"platform": "cocoa",
},
)
mock_integration.assert_called_with(self.repo, f"src/{filename}", "master", None)
assert response.data["config"] == self.expected_configurations(
self.cocoa_code_mapping_abs_path
)
assert response.data["sourceUrl"] == f"{example_base_url}/src/{filename}"
@patch.object(ExampleIntegration, "get_stacktrace_link")
def test_cocoa_filename_success(self, mock_integration: MagicMock) -> None:
"""
Cocoa events with code mappings that match the file should apply correctly.
"""
filename = "AppDelegate.swift"
mock_integration.side_effect = [f"{example_base_url}/src/{filename}"]
response = self.get_success_response(
self.organization.slug,
self.project.slug,
qs_params={
"file": "AppDelegate.swift",
"absPath": f"/Foo/user/code/SwiftySampleProject/{filename}",
"package": "SampleProject",
"platform": "cocoa",
},
)
mock_integration.assert_called_with(self.repo, f"src/{filename}", "master", None)
assert response.data["config"] == self.expected_configurations(
self.cocoa_code_mapping_filename
)
assert response.data["sourceUrl"] == f"{example_base_url}/src/{filename}"
@patch.object(ExampleIntegration, "get_stacktrace_link")
def test_cocoa_failed_stack_root_mismatch(self, mock_integration: MagicMock) -> None:
"""
Should return stack_root_mismatch if stack root doesn't match file or abs_path
"""
filename = "OtherFile.swift"
mock_integration.side_effect = [f"{example_base_url}/src/{filename}"]
response = self.get_success_response(
self.organization.slug,
self.project.slug,
qs_params={
"file": filename,
"absPath": f"/Foo/user/code/SwiftySampleProject/{filename}",
"package": "SampleProject",
"platform": "cocoa",
},
)
assert not response.data["config"]
assert not response.data["sourceUrl"]
assert response.data["error"] == "stack_root_mismatch"
assert response.data["integrations"] == [serialized_integration(self.integration)]
@patch.object(ExampleIntegration, "get_stacktrace_link")
def test_munge_flutter_worked(self, mock_integration: MagicMock) -> None:
file_path = "a/b/main.dart"
mock_integration.side_effect = [f"{example_base_url}/{file_path}"]
response = self.get_success_response(
self.organization.slug,
self.project.slug,
qs_params={
"file": "main.dart",
"absPath": f"package:sentry_flutter_example/{file_path}",
"package": "sentry_flutter_example",
"platform": "other",
"sdkName": "sentry.dart.flutter",
},
)
assert response.data["config"] == self.expected_configurations(self.flutter_code_mapping)
assert response.data["sourceUrl"] == f"{example_base_url}/{file_path}"
| ProjectStacktraceLinkTestMobile |
python | numpy__numpy | numpy/_core/tests/test_deprecations.py | {
"start": 6693,
"end": 7535
} | class ____(_DeprecationTestCase):
# NumPy 1.20, 2020-09-03
message = "concatenate with `axis=None` will use same-kind casting"
def test_deprecated(self):
self.assert_deprecated(np.concatenate,
args=(([0.], [1.]),),
kwargs={'axis': None, 'out': np.empty(2, dtype=np.int64)})
def test_not_deprecated(self):
self.assert_not_deprecated(np.concatenate,
args=(([0.], [1.]),),
kwargs={'axis': None, 'out': np.empty(2, dtype=np.int64),
'casting': "unsafe"})
with assert_raises(TypeError):
# Tests should notice if the deprecation warning is given first...
np.concatenate(([0.], [1.]), out=np.empty(2, dtype=np.int64),
casting="same_kind")
| FlatteningConcatenateUnsafeCast |
python | streamlit__streamlit | lib/tests/streamlit/web/server/upload_file_request_handler_test.py | {
"start": 7010,
"end": 8791
} | class ____(tornado.testing.AsyncHTTPTestCase):
"""Tests the /upload_file endpoint."""
def get_app(self):
self.file_mgr = MemoryUploadedFileManager(upload_endpoint=UPLOAD_FILE_ENDPOINT)
return tornado.web.Application(
[
(
f"{UPLOAD_FILE_ENDPOINT}/(?P<session_id>[^/]+)/(?P<file_id>[^/]+)",
UploadFileRequestHandler,
dict(
file_mgr=self.file_mgr,
is_active_session=lambda session_id: False,
),
),
]
)
def _upload_files(self, files_body, session_id, file_id):
# We use requests.Request to construct our multipart/form-data request
# here, because they are absurdly fiddly to compose, and Tornado
# doesn't include a utility for building them. We then use self.fetch()
# to actually send the request to the test server.
req = requests.Request(
method="PUT",
url=self.get_url(f"{UPLOAD_FILE_ENDPOINT}/{session_id}/{file_id}"),
files=files_body,
).prepare()
return self.fetch(
req.url,
method=req.method,
headers=req.headers,
body=req.body,
)
def test_upload_one_file(self):
"""Upload should fail if the sessionId doesn't exist."""
file = MockFile("filename", b"123")
params = {file.name: file.data}
response = self._upload_files(params, session_id="sessionId", file_id="fileId")
assert response.code == 400
assert "Invalid session_id" in response.reason
assert self.file_mgr.get_files("sessionId", ["fileId"]) == []
| UploadFileRequestHandlerInvalidSessionTest |
python | pytorch__pytorch | test/dynamo/cpython/3_13/list_tests.py | {
"start": 667,
"end": 1654
} | class ____(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, path, target=None):
# Check if the import is the problematic one
if fullname in redirect_imports:
try:
# Attempt to import the standalone module
name = fullname.removeprefix("test.")
r = importlib.import_module(name)
# Redirect the module in sys.modules
sys.modules[fullname] = r
# Return a module spec from the found module
return importlib.util.find_spec(name)
except ImportError:
return None
return None
# Add the custom finder to sys.meta_path
sys.meta_path.insert(0, RedirectImportFinder())
# ======= END DYNAMO PATCH =======
"""
Tests common to list and UserList.UserList
"""
import sys
from functools import cmp_to_key
import seq_tests
from test.support import ALWAYS_EQ, NEVER_EQ, get_c_recursion_limit
| RedirectImportFinder |
python | joke2k__faker | tests/providers/test_python.py | {
"start": 4710,
"end": 5556
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker()
Faker.seed(0)
def test_pyint(self):
self.assertIsInstance(self.fake.pyint(), int)
def test_pyint_bounds(self):
self.assertTrue(0 <= self.fake.pyint() <= 9999)
def test_pyint_step(self):
random_int = self.fake.pyint(step=2)
self.assertEqual(0, random_int % 2)
def test_pyint_bound_0(self):
self.assertEqual(0, self.fake.pyint(min_value=0, max_value=0))
def test_pyint_bound_positive(self):
self.assertEqual(5, self.fake.pyint(min_value=5, max_value=5))
def test_pyint_bound_negative(self):
self.assertEqual(-5, self.fake.pyint(min_value=-5, max_value=-5))
def test_pyint_range(self):
self.assertTrue(0 <= self.fake.pyint(min_value=0, max_value=2) <= 2)
| TestPyint |
python | Lightning-AI__lightning | src/lightning/pytorch/callbacks/finetuning.py | {
"start": 1462,
"end": 13988
} | class ____(Callback):
r"""This class implements the base logic for writing your own Finetuning Callback.
.. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature.
Override ``freeze_before_training`` and ``finetune_function`` methods with your own logic.
``freeze_before_training``: This method is called before ``configure_optimizers``
and should be used to freeze any modules parameters.
``finetune_function``: This method is called on every train epoch start and should be used to
``unfreeze`` any parameters. Those parameters need to be added in a new ``param_group``
within the optimizer.
.. note:: Make sure to filter the parameters based on ``requires_grad``.
Example::
>>> from torch.optim import Adam
>>> class MyModel(pl.LightningModule):
... def configure_optimizer(self):
... # Make sure to filter the parameters based on `requires_grad`
... return Adam(filter(lambda p: p.requires_grad, self.parameters()))
...
>>> class FeatureExtractorFreezeUnfreeze(BaseFinetuning):
... def __init__(self, unfreeze_at_epoch=10):
... super().__init__()
... self._unfreeze_at_epoch = unfreeze_at_epoch
...
... def freeze_before_training(self, pl_module):
... # freeze any module you want
... # Here, we are freezing `feature_extractor`
... self.freeze(pl_module.feature_extractor)
...
... def finetune_function(self, pl_module, current_epoch, optimizer):
... # When `current_epoch` is 10, feature_extractor will start training.
... if current_epoch == self._unfreeze_at_epoch:
... self.unfreeze_and_add_param_group(
... modules=pl_module.feature_extractor,
... optimizer=optimizer,
... train_bn=True,
... )
"""
def __init__(self) -> None:
self._internal_optimizer_metadata: dict[int, list[dict[str, Any]]] = {}
self._restarting = False
@override
def state_dict(self) -> dict[str, Any]:
return {
"internal_optimizer_metadata": self._internal_optimizer_metadata,
}
@override
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
self._restarting = True
if "internal_optimizer_metadata" in state_dict: # noqa: SIM401
self._internal_optimizer_metadata = state_dict["internal_optimizer_metadata"]
else:
# compatibility to load from old checkpoints before PR #11887
self._internal_optimizer_metadata = state_dict # type: ignore[assignment]
@override
def on_fit_start(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None:
# restore the param_groups created during the previous training.
if self._restarting:
if self._internal_optimizer_metadata:
named_parameters = dict(pl_module.named_parameters())
for opt_idx, optimizer in enumerate(trainer.optimizers):
if opt_idx in self._internal_optimizer_metadata:
param_groups = self._apply_mapping_to_param_groups(
self._internal_optimizer_metadata[opt_idx], named_parameters
)
optimizer.param_groups = param_groups
self._restarting = False
@staticmethod
def flatten_modules(modules: Union[Module, Iterable[Union[Module, Iterable]]]) -> list[Module]:
"""This function is used to flatten a module or an iterable of modules into a list of its leaf modules (modules
with no children) and parent modules that have parameters directly themselves.
Args:
modules: A given module or an iterable of modules
Returns:
List of modules
"""
if isinstance(modules, ModuleDict):
modules = modules.values()
if isinstance(modules, Iterable):
_flatten_modules = []
for m in modules:
_flatten_modules.extend(BaseFinetuning.flatten_modules(m))
_modules = iter(_flatten_modules)
else:
_modules = modules.modules()
# Capture all leaf modules as well as parent modules that have parameters directly themselves
return [m for m in _modules if not list(m.children()) or m._parameters]
@staticmethod
def filter_params(
modules: Union[Module, Iterable[Union[Module, Iterable]]], train_bn: bool = True, requires_grad: bool = True
) -> Generator:
"""Yields the `requires_grad` parameters of a given module or list of modules.
Args:
modules: A given module or an iterable of modules
train_bn: Whether not to train the BatchNorm module
requires_grad: Whether to create a generator for trainable or non-trainable parameters.
Returns:
Generator
"""
modules = BaseFinetuning.flatten_modules(modules)
for mod in modules:
if isinstance(mod, _BatchNorm) and not train_bn:
continue
# recursion could yield duplicate parameters for parent modules w/ parameters so disabling it
for param in mod.parameters(recurse=False):
if param.requires_grad == requires_grad:
yield param
@staticmethod
def make_trainable(modules: Union[Module, Iterable[Union[Module, Iterable]]]) -> None:
"""Unfreezes the parameters of the provided modules.
Args:
modules: A given module or an iterable of modules
"""
modules = BaseFinetuning.flatten_modules(modules)
for module in modules:
if isinstance(module, _BatchNorm):
module.track_running_stats = True
# recursion could yield duplicate parameters for parent modules w/ parameters so disabling it
for param in module.parameters(recurse=False):
param.requires_grad = True
@staticmethod
def freeze_module(module: Module) -> None:
"""Freezes the parameters of the provided module.
Args:
module: A given module
"""
if isinstance(module, _BatchNorm):
module.track_running_stats = False
# recursion could yield duplicate parameters for parent modules w/ parameters so disabling it
for param in module.parameters(recurse=False):
param.requires_grad = False
@staticmethod
def freeze(modules: Union[Module, Iterable[Union[Module, Iterable]]], train_bn: bool = True) -> None:
"""Freezes the parameters of the provided modules.
Args:
modules: A given module or an iterable of modules
train_bn: If True, leave the BatchNorm layers in training mode
Returns:
None
"""
modules = BaseFinetuning.flatten_modules(modules)
for mod in modules:
if isinstance(mod, _BatchNorm) and train_bn:
BaseFinetuning.make_trainable(mod)
else:
BaseFinetuning.freeze_module(mod)
@staticmethod
def filter_on_optimizer(optimizer: Optimizer, params: Iterable) -> list:
"""This function is used to exclude any parameter which already exists in this optimizer.
Args:
optimizer: Optimizer used for parameter exclusion
params: Iterable of parameters used to check against the provided optimizer
Returns:
List of parameters not contained in this optimizer param groups
"""
out_params = []
removed_params = []
for param in params:
if not any(torch.equal(p, param) for group in optimizer.param_groups for p in group["params"]):
out_params.append(param)
else:
removed_params.append(param)
if removed_params:
rank_zero_warn(
"The provided params to be frozen already exist within another group of this optimizer."
" Those parameters will be skipped.\n"
"HINT: Did you init your optimizer in `configure_optimizer` as such:\n"
f" {type(optimizer)}(filter(lambda p: p.requires_grad, self.parameters()), ...) ",
)
return out_params
@staticmethod
def unfreeze_and_add_param_group(
modules: Union[Module, Iterable[Union[Module, Iterable]]],
optimizer: Optimizer,
lr: Optional[float] = None,
initial_denom_lr: float = 10.0,
train_bn: bool = True,
) -> None:
"""Unfreezes a module and adds its parameters to an optimizer.
Args:
modules: A module or iterable of modules to unfreeze.
Their parameters will be added to an optimizer as a new param group.
optimizer: The provided optimizer will receive new parameters and will add them to
`add_param_group`
lr: Learning rate for the new param group.
initial_denom_lr: If no lr is provided, the learning from the first param group will be used
and divided by `initial_denom_lr`.
train_bn: Whether to train the BatchNormalization layers.
"""
BaseFinetuning.make_trainable(modules)
params_lr = optimizer.param_groups[0]["lr"] if lr is None else float(lr)
denom_lr = initial_denom_lr if lr is None else 1.0
params = BaseFinetuning.filter_params(modules, train_bn=train_bn, requires_grad=True)
params = BaseFinetuning.filter_on_optimizer(optimizer, params)
if params:
optimizer.add_param_group({"params": params, "lr": params_lr / denom_lr})
@override
def setup(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule", stage: str) -> None:
self.freeze_before_training(pl_module)
from lightning.pytorch.strategies import DeepSpeedStrategy
if isinstance(trainer.strategy, DeepSpeedStrategy):
raise NotImplementedError(
"The Finetuning callback does not support running with the DeepSpeed strategy."
" Choose a different strategy or disable the callback."
)
@staticmethod
def _apply_mapping_to_param_groups(param_groups: list[dict[str, Any]], mapping: dict) -> list[dict[str, Any]]:
output = []
for g in param_groups:
# skip params to save memory
group_state = {k: v for k, v in g.items() if k != "params"}
group_state["params"] = [mapping[p] for p in g["params"]]
output.append(group_state)
return output
def _store(
self,
pl_module: "pl.LightningModule",
opt_idx: int,
num_param_groups: int,
current_param_groups: list[dict[str, Any]],
) -> None:
mapping = {p: n for n, p in pl_module.named_parameters()}
if opt_idx not in self._internal_optimizer_metadata:
self._internal_optimizer_metadata[opt_idx] = self._apply_mapping_to_param_groups(
current_param_groups, mapping
)
elif num_param_groups != len(current_param_groups):
# save new param_groups possibly created by the users.
self._internal_optimizer_metadata[opt_idx].extend(
self._apply_mapping_to_param_groups(current_param_groups[num_param_groups:], mapping)
)
@override
def on_train_epoch_start(self, trainer: "pl.Trainer", pl_module: "pl.LightningModule") -> None:
"""Called when the epoch begins."""
for opt_idx, optimizer in enumerate(trainer.optimizers):
num_param_groups = len(optimizer.param_groups)
self.finetune_function(pl_module, trainer.current_epoch, optimizer)
current_param_groups = optimizer.param_groups
self._store(pl_module, opt_idx, num_param_groups, current_param_groups)
def finetune_function(self, pl_module: "pl.LightningModule", epoch: int, optimizer: Optimizer) -> None:
"""Override to add your unfreeze logic."""
raise NotImplementedError
def freeze_before_training(self, pl_module: "pl.LightningModule") -> None:
"""Override to add your freeze logic."""
raise NotImplementedError
| BaseFinetuning |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/vertex_ai/test_dataset.py | {
"start": 1934,
"end": 10752
} | class ____:
def setup_method(self):
with mock.patch(
BASE_STRING.format("GoogleBaseHook.__init__"), new=mock_base_gcp_hook_default_project_id
):
self.hook = DatasetHook(gcp_conn_id=TEST_GCP_CONN_ID)
@mock.patch(DATASET_STRING.format("DatasetHook.get_dataset_service_client"))
def test_create_dataset(self, mock_client) -> None:
self.hook.create_dataset(
project_id=TEST_PROJECT_ID,
region=TEST_REGION,
dataset=TEST_DATASET,
)
mock_client.assert_called_once_with(TEST_REGION)
mock_client.return_value.create_dataset.assert_called_once_with(
request=dict(
parent=mock_client.return_value.common_location_path.return_value,
dataset=TEST_DATASET,
),
metadata=(),
retry=DEFAULT,
timeout=None,
)
mock_client.return_value.common_location_path.assert_called_once_with(TEST_PROJECT_ID, TEST_REGION)
@mock.patch(DATASET_STRING.format("DatasetHook.get_dataset_service_client"))
def test_delete_dataset(self, mock_client) -> None:
self.hook.delete_dataset(
project_id=TEST_PROJECT_ID,
region=TEST_REGION,
dataset=TEST_DATASET_ID,
)
mock_client.assert_called_once_with(TEST_REGION)
mock_client.return_value.delete_dataset.assert_called_once_with(
request=dict(
name=mock_client.return_value.dataset_path.return_value,
),
metadata=(),
retry=DEFAULT,
timeout=None,
)
mock_client.return_value.dataset_path.assert_called_once_with(
TEST_PROJECT_ID, TEST_REGION, TEST_DATASET_ID
)
@mock.patch(DATASET_STRING.format("DatasetHook.get_dataset_service_client"))
def test_export_data(self, mock_client) -> None:
self.hook.export_data(
project_id=TEST_PROJECT_ID,
region=TEST_REGION,
dataset=TEST_DATASET_ID,
export_config=TEST_EXPORT_CONFIG,
)
mock_client.assert_called_once_with(TEST_REGION)
mock_client.return_value.export_data.assert_called_once_with(
request=dict(
name=mock_client.return_value.dataset_path.return_value,
export_config=TEST_EXPORT_CONFIG,
),
metadata=(),
retry=DEFAULT,
timeout=None,
)
mock_client.return_value.dataset_path.assert_called_once_with(
TEST_PROJECT_ID, TEST_REGION, TEST_DATASET_ID
)
@mock.patch(DATASET_STRING.format("DatasetHook.get_dataset_service_client"))
def test_get_annotation_spec(self, mock_client) -> None:
self.hook.get_annotation_spec(
project_id=TEST_PROJECT_ID,
region=TEST_REGION,
dataset=TEST_DATASET_ID,
annotation_spec=TEST_ANNOTATION_SPEC,
)
mock_client.assert_called_once_with(TEST_REGION)
mock_client.return_value.get_annotation_spec.assert_called_once_with(
request=dict(
name=mock_client.return_value.annotation_spec_path.return_value,
read_mask=None,
),
metadata=(),
retry=DEFAULT,
timeout=None,
)
mock_client.return_value.annotation_spec_path.assert_called_once_with(
TEST_PROJECT_ID, TEST_REGION, TEST_DATASET_ID, TEST_ANNOTATION_SPEC
)
@mock.patch(DATASET_STRING.format("DatasetHook.get_dataset_service_client"))
def test_get_dataset(self, mock_client) -> None:
self.hook.get_dataset(
project_id=TEST_PROJECT_ID,
region=TEST_REGION,
dataset=TEST_DATASET_ID,
)
mock_client.assert_called_once_with(TEST_REGION)
mock_client.return_value.get_dataset.assert_called_once_with(
request=dict(
name=mock_client.return_value.dataset_path.return_value,
read_mask=None,
),
metadata=(),
retry=DEFAULT,
timeout=None,
)
mock_client.return_value.dataset_path.assert_called_once_with(
TEST_PROJECT_ID, TEST_REGION, TEST_DATASET_ID
)
@mock.patch(DATASET_STRING.format("DatasetHook.get_dataset_service_client"))
def test_import_data(self, mock_client) -> None:
self.hook.import_data(
project_id=TEST_PROJECT_ID,
region=TEST_REGION,
dataset=TEST_DATASET_ID,
import_configs=TEST_IMPORT_CONFIGS,
)
mock_client.assert_called_once_with(TEST_REGION)
mock_client.return_value.import_data.assert_called_once_with(
request=dict(
name=mock_client.return_value.dataset_path.return_value,
import_configs=TEST_IMPORT_CONFIGS,
),
metadata=(),
retry=DEFAULT,
timeout=None,
)
mock_client.return_value.dataset_path.assert_called_once_with(
TEST_PROJECT_ID, TEST_REGION, TEST_DATASET_ID
)
@mock.patch(DATASET_STRING.format("DatasetHook.get_dataset_service_client"))
def test_list_annotations(self, mock_client) -> None:
self.hook.list_annotations(
project_id=TEST_PROJECT_ID,
region=TEST_REGION,
dataset=TEST_DATASET_ID,
data_item=TEST_DATA_ITEM,
)
mock_client.assert_called_once_with(TEST_REGION)
mock_client.return_value.list_annotations.assert_called_once_with(
request=dict(
parent=mock_client.return_value.data_item_path.return_value,
filter=None,
page_size=None,
page_token=None,
read_mask=None,
order_by=None,
),
metadata=(),
retry=DEFAULT,
timeout=None,
)
mock_client.return_value.data_item_path.assert_called_once_with(
TEST_PROJECT_ID, TEST_REGION, TEST_DATASET_ID, TEST_DATA_ITEM
)
@mock.patch(DATASET_STRING.format("DatasetHook.get_dataset_service_client"))
def test_list_data_items(self, mock_client) -> None:
self.hook.list_data_items(
project_id=TEST_PROJECT_ID,
region=TEST_REGION,
dataset=TEST_DATASET_ID,
)
mock_client.assert_called_once_with(TEST_REGION)
mock_client.return_value.list_data_items.assert_called_once_with(
request=dict(
parent=mock_client.return_value.dataset_path.return_value,
filter=None,
page_size=None,
page_token=None,
read_mask=None,
order_by=None,
),
metadata=(),
retry=DEFAULT,
timeout=None,
)
mock_client.return_value.dataset_path.assert_called_once_with(
TEST_PROJECT_ID, TEST_REGION, TEST_DATASET_ID
)
@mock.patch(DATASET_STRING.format("DatasetHook.get_dataset_service_client"))
def test_list_datasets(self, mock_client) -> None:
self.hook.list_datasets(
project_id=TEST_PROJECT_ID,
region=TEST_REGION,
)
mock_client.assert_called_once_with(TEST_REGION)
mock_client.return_value.list_datasets.assert_called_once_with(
request=dict(
parent=mock_client.return_value.common_location_path.return_value,
filter=None,
page_size=None,
page_token=None,
read_mask=None,
order_by=None,
),
metadata=(),
retry=DEFAULT,
timeout=None,
)
mock_client.return_value.common_location_path.assert_called_once_with(TEST_PROJECT_ID, TEST_REGION)
@mock.patch(DATASET_STRING.format("DatasetHook.get_dataset_service_client"))
def test_update_dataset(self, mock_client) -> None:
self.hook.update_dataset(
project_id=TEST_PROJECT_ID,
region=TEST_REGION,
dataset_id=TEST_DATASET_ID,
dataset=TEST_DATASET,
update_mask=TEST_UPDATE_MASK,
)
mock_client.assert_called_once_with(TEST_REGION)
mock_client.return_value.update_dataset.assert_called_once_with(
request=dict(
dataset=TEST_DATASET,
update_mask=TEST_UPDATE_MASK,
),
metadata=(),
retry=DEFAULT,
timeout=None,
)
mock_client.return_value.dataset_path.assert_called_once_with(
TEST_PROJECT_ID, TEST_REGION, TEST_DATASET_ID
)
| TestVertexAIWithDefaultProjectIdHook |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_datacatalog.py | {
"start": 5691,
"end": 9679
} | class ____:
@mock.patch(
"airflow.providers.google.cloud.operators.datacatalog.CloudDataCatalogHook",
**{"return_value.create_entry.return_value": TEST_ENTRY},
)
def test_assert_valid_hook_call(self, mock_hook) -> None:
with pytest.warns(AirflowProviderDeprecationWarning):
task = CloudDataCatalogCreateEntryOperator(
task_id="task_id",
location=TEST_LOCATION,
entry_group=TEST_ENTRY_GROUP_ID,
entry_id=TEST_ENTRY_ID,
entry=TEST_ENTRY,
project_id=TEST_PROJECT_ID,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
mock_ti = mock.MagicMock()
mock_context = {"ti": mock_ti}
if not AIRFLOW_V_3_0_PLUS:
mock_context["task"] = task # type: ignore[assignment]
result = task.execute(context=mock_context) # type: ignore[arg-type]
mock_hook.assert_called_once_with(
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
mock_hook.return_value.create_entry.assert_called_once_with(
location=TEST_LOCATION,
entry_group=TEST_ENTRY_GROUP_ID,
entry_id=TEST_ENTRY_ID,
entry=TEST_ENTRY,
project_id=TEST_PROJECT_ID,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
)
mock_ti.xcom_push.assert_any_call(
key="entry_id",
value=TEST_ENTRY_ID,
)
assert result == TEST_ENTRY_DICT
@mock.patch("airflow.providers.google.cloud.operators.datacatalog.CloudDataCatalogHook")
def test_assert_valid_hook_call_when_exists(self, mock_hook) -> None:
mock_hook.return_value.create_entry.side_effect = AlreadyExists(message="message")
mock_hook.return_value.get_entry.return_value = TEST_ENTRY
with pytest.warns(AirflowProviderDeprecationWarning):
task = CloudDataCatalogCreateEntryOperator(
task_id="task_id",
location=TEST_LOCATION,
entry_group=TEST_ENTRY_GROUP_ID,
entry_id=TEST_ENTRY_ID,
entry=TEST_ENTRY,
project_id=TEST_PROJECT_ID,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
mock_ti = mock.MagicMock()
mock_context = {"ti": mock_ti}
if not AIRFLOW_V_3_0_PLUS:
mock_context["task"] = task # type: ignore[assignment]
result = task.execute(context=mock_context) # type: ignore[arg-type]
mock_hook.assert_called_once_with(
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
mock_hook.return_value.create_entry.assert_called_once_with(
location=TEST_LOCATION,
entry_group=TEST_ENTRY_GROUP_ID,
entry_id=TEST_ENTRY_ID,
entry=TEST_ENTRY,
project_id=TEST_PROJECT_ID,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
)
mock_hook.return_value.get_entry.assert_called_once_with(
location=TEST_LOCATION,
entry_group=TEST_ENTRY_GROUP_ID,
entry=TEST_ENTRY_ID,
project_id=TEST_PROJECT_ID,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
)
mock_ti.xcom_push.assert_any_call(
key="entry_id",
value=TEST_ENTRY_ID,
)
assert result == TEST_ENTRY_DICT
| TestCloudDataCatalogCreateEntryOperator |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 995249,
"end": 1004980
} | class ____(FieldChannelMixin, core.SecondaryFieldDef):
r"""
XError schema wrapper.
A field definition of a secondary channel that shares a scale with another primary channel.
For example, ``x2``, ``xError`` and ``xError2`` share the same scale with ``x``.
Parameters
----------
shorthand : str, dict, Sequence[str], :class:`RepeatRef`
shorthand for field, aggregate, and type
aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :class:`NonArgAggregateOp`, Literal['average', 'count', 'distinct', 'max', 'mean', 'median', 'min', 'missing', 'product', 'q1', 'q3', 'ci0', 'ci1', 'stderr', 'stdev', 'stdevp', 'sum', 'valid', 'values', 'variance', 'variancep', 'exponential', 'exponentialb']
Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``,
``"min"``, ``"max"``, ``"count"``).
**Default value:** ``undefined`` (None)
**See also:** `aggregate <https://vega.github.io/vega-lite/docs/aggregate.html>`__
documentation.
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be positioned at the beginning of the band if set to ``0``,
and at the middle of the band if set to ``0.5``.
bin : None
A flag for binning a ``quantitative`` field, `an object defining binning parameters
<https://vega.github.io/vega-lite/docs/bin.html#bin-parameters>`__, or indicating
that the data for ``x`` or ``y`` channel are binned before they are imported into
Vega-Lite (``"binned"``).
* If ``true``, default `binning parameters
<https://vega.github.io/vega-lite/docs/bin.html#bin-parameters>`__ will be
applied.
* If ``"binned"``, this indicates that the data for the ``x`` (or ``y``) channel are
already binned. You can map the bin-start field to ``x`` (or ``y``) and the
bin-end field to ``x2`` (or ``y2``). The scale and axis will be formatted similar
to binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can
also set the axis's `tickMinStep
<https://vega.github.io/vega-lite/docs/axis.html#ticks>`__ property.
**Default value:** ``false``
**See also:** `bin <https://vega.github.io/vega-lite/docs/bin.html>`__
documentation.
field : str, dict, :class:`Field`, :class:`FieldName`, :class:`RepeatRef`
**Required.** A string defining the name of the field from which to pull a data
value or an object defining iterated values from the `repeat
<https://vega.github.io/vega-lite/docs/repeat.html>`__ operator.
**See also:** `field <https://vega.github.io/vega-lite/docs/field.html>`__
documentation.
**Notes:** 1) Dots (``.``) and brackets (``[`` and ``]``) can be used to access
nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"``). If
field names contain dots or brackets but are not nested, you can use ``\\`` to
escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"``). See more details
about escaping in the `field documentation
<https://vega.github.io/vega-lite/docs/field.html>`__. 2) ``field`` is not required
if ``aggregate`` is ``count``.
timeUnit : dict, :class:`TimeUnit`, :class:`MultiTimeUnit`, :class:`BinnedTimeUnit`, :class:`SingleTimeUnit`, :class:`TimeUnitParams`, :class:`UtcMultiTimeUnit`, :class:`UtcSingleTimeUnit`, :class:`LocalMultiTimeUnit`, :class:`LocalSingleTimeUnit`, Literal['binnedyear', 'binnedyearquarter', 'binnedyearquartermonth', 'binnedyearmonth', 'binnedyearmonthdate', 'binnedyearmonthdatehours', 'binnedyearmonthdatehoursminutes', 'binnedyearmonthdatehoursminutesseconds', 'binnedyearweek', 'binnedyearweekday', 'binnedyearweekdayhours', 'binnedyearweekdayhoursminutes', 'binnedyearweekdayhoursminutesseconds', 'binnedyeardayofyear', 'binnedutcyear', 'binnedutcyearquarter', 'binnedutcyearquartermonth', 'binnedutcyearmonth', 'binnedutcyearmonthdate', 'binnedutcyearmonthdatehours', 'binnedutcyearmonthdatehoursminutes', 'binnedutcyearmonthdatehoursminutesseconds', 'binnedutcyearweek', 'binnedutcyearweekday', 'binnedutcyearweekdayhours', 'binnedutcyearweekdayhoursminutes', 'binnedutcyearweekdayhoursminutesseconds', 'binnedutcyeardayofyear', 'utcyear', 'utcquarter', 'utcmonth', 'utcweek', 'utcday', 'utcdayofyear', 'utcdate', 'utchours', 'utcminutes', 'utcseconds', 'utcmilliseconds', 'year', 'quarter', 'month', 'week', 'day', 'dayofyear', 'date', 'hours', 'minutes', 'seconds', 'milliseconds', 'utcyearquarter', 'utcyearquartermonth', 'utcyearmonth', 'utcyearmonthdate', 'utcyearmonthdatehours', 'utcyearmonthdatehoursminutes', 'utcyearmonthdatehoursminutesseconds', 'utcyearweek', 'utcyearweekday', 'utcyearweekdayhours', 'utcyearweekdayhoursminutes', 'utcyearweekdayhoursminutesseconds', 'utcyeardayofyear', 'utcquartermonth', 'utcmonthdate', 'utcmonthdatehours', 'utcmonthdatehoursminutes', 'utcmonthdatehoursminutesseconds', 'utcweekday', 'utcweekdayhours', 'utcweekdayhoursminutes', 'utcweekdayhoursminutesseconds', 'utcdayhours', 'utcdayhoursminutes', 'utcdayhoursminutesseconds', 'utchoursminutes', 'utchoursminutesseconds', 'utcminutesseconds', 'utcsecondsmilliseconds', 'yearquarter', 'yearquartermonth', 'yearmonth', 'yearmonthdate', 'yearmonthdatehours', 'yearmonthdatehoursminutes', 'yearmonthdatehoursminutesseconds', 'yearweek', 'yearweekday', 'yearweekdayhours', 'yearweekdayhoursminutes', 'yearweekdayhoursminutesseconds', 'yeardayofyear', 'quartermonth', 'monthdate', 'monthdatehours', 'monthdatehoursminutes', 'monthdatehoursminutesseconds', 'weekday', 'weekdayhours', 'weekdayhoursminutes', 'weekdayhoursminutesseconds', 'dayhours', 'dayhoursminutes', 'dayhoursminutesseconds', 'hoursminutes', 'hoursminutesseconds', 'minutesseconds', 'secondsmilliseconds']
Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours``) for a temporal
field. or `a temporal field that gets casted as ordinal
<https://vega.github.io/vega-lite/docs/type.html#cast>`__.
**Default value:** ``undefined`` (None)
**See also:** `timeUnit <https://vega.github.io/vega-lite/docs/timeunit.html>`__
documentation.
title : str, :class:`Text`, Sequence[str], None
A title for the field. If ``null``, the title will be removed.
**Default value:** derived from the field's name and transformation function
(``aggregate``, ``bin`` and ``timeUnit``). If the field has an aggregate function,
the function is displayed as part of the title (e.g., ``"Sum of Profit"``). If the
field is binned or has a time unit applied, the applied function is shown in
parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"``).
Otherwise, the title is simply the field name.
**Notes**:
1) You can customize the default field title format by providing the `fieldTitle
<https://vega.github.io/vega-lite/docs/config.html#top-level-config>`__ property in
the `config <https://vega.github.io/vega-lite/docs/config.html>`__ or `fieldTitle
function via the compile function's options
<https://vega.github.io/vega-lite/usage/compile.html#field-title>`__.
2) If both field definition's ``title`` and axis, header, or legend ``title`` are
defined, axis/header/legend title will be used.
"""
_class_is_valid_at_instantiation = False
_encoding_name = "xError"
@overload
def aggregate(self, _: NonArgAggregateOp_T, /) -> XError: ...
@overload
def aggregate(
self, *, argmax: Optional[str | SchemaBase] = Undefined
) -> XError: ...
@overload
def aggregate(
self, *, argmin: Optional[str | SchemaBase] = Undefined
) -> XError: ...
@overload
def bandPosition(self, _: float, /) -> XError: ...
@overload
def bin(self, _: None, /) -> XError: ...
@overload
def field(self, _: str | RepeatRef, /) -> XError: ...
@overload
def field(
self,
*,
repeat: Optional[Literal["row", "column", "repeat", "layer"]] = Undefined,
) -> XError: ...
@overload
def timeUnit(
self,
_: TimeUnitParams | MultiTimeUnit_T | BinnedTimeUnit_T | SingleTimeUnit_T,
/,
) -> XError: ...
@overload
def timeUnit(
self,
*,
binned: Optional[bool] = Undefined,
maxbins: Optional[float] = Undefined,
step: Optional[float] = Undefined,
unit: Optional[SchemaBase | MultiTimeUnit_T | SingleTimeUnit_T] = Undefined,
utc: Optional[bool] = Undefined,
) -> XError: ...
@overload
def title(self, _: str | Sequence[str] | None, /) -> XError: ...
def __init__(
self,
shorthand: Optional[str | SchemaBase | Sequence[str] | Map] = Undefined,
aggregate: Optional[SchemaBase | Map | NonArgAggregateOp_T] = Undefined,
bandPosition: Optional[float] = Undefined,
bin: Optional[None] = Undefined,
field: Optional[str | SchemaBase | Map] = Undefined,
timeUnit: Optional[
SchemaBase | Map | MultiTimeUnit_T | BinnedTimeUnit_T | SingleTimeUnit_T
] = Undefined,
title: Optional[str | SchemaBase | Sequence[str] | None] = Undefined,
**kwds,
):
super().__init__(
shorthand=shorthand,
aggregate=aggregate,
bandPosition=bandPosition,
bin=bin,
field=field,
timeUnit=timeUnit,
title=title,
**kwds,
)
@with_property_setters
| XError |
python | numba__numba | numba/core/compiler_machinery.py | {
"start": 477,
"end": 731
} | class ____(object):
"""
A simple context managed timer
"""
def __enter__(self):
self.ts = timeit.default_timer()
return self
def __exit__(self, *exc):
self.elapsed = timeit.default_timer() - self.ts
| SimpleTimer |
python | miyuchina__mistletoe | mistletoe/span_token.py | {
"start": 3884,
"end": 4111
} | class ____(SpanToken):
"""
Strikethrough token. ("~~some text~~")
This is an inline token. Its children are inline (span) tokens.
"""
pattern = re.compile(r"(?<!\\)(?:\\\\)*~~(.+?)~~", re.DOTALL)
| Strikethrough |
python | huggingface__transformers | src/transformers/models/grounding_dino/modeling_grounding_dino.py | {
"start": 67148,
"end": 71099
} | class ____(PreTrainedModel):
config: GroundingDinoConfig
base_model_prefix = "model"
main_input_name = "pixel_values"
input_modalities = ("image", "text")
@torch.no_grad()
def _init_weights(self, module):
std = self.config.init_std
if isinstance(module, GroundingDinoLearnedPositionEmbedding):
init.uniform_(module.row_embeddings.weight)
init.uniform_(module.column_embeddings.weight)
elif isinstance(module, GroundingDinoMultiscaleDeformableAttention):
init.constant_(module.sampling_offsets.weight, 0.0)
default_dtype = torch.get_default_dtype()
thetas = torch.arange(module.n_heads, dtype=torch.int64).to(default_dtype) * (
2.0 * math.pi / module.n_heads
)
grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
grid_init = (
(grid_init / grid_init.abs().max(-1, keepdim=True)[0])
.view(module.n_heads, 1, 1, 2)
.repeat(1, module.n_levels, module.n_points, 1)
)
for i in range(module.n_points):
grid_init[:, :, i, :] *= i + 1
init.copy_(module.sampling_offsets.bias, grid_init.view(-1))
init.constant_(module.attention_weights.weight, 0.0)
init.constant_(module.attention_weights.bias, 0.0)
init.xavier_uniform_(module.value_proj.weight)
init.constant_(module.value_proj.bias, 0.0)
init.xavier_uniform_(module.output_proj.weight)
init.constant_(module.output_proj.bias, 0.0)
elif isinstance(module, GroundingDinoBiMultiHeadAttention):
init.xavier_uniform_(module.vision_proj.weight)
init.zeros_(module.vision_proj.bias)
init.xavier_uniform_(module.text_proj.weight)
init.zeros_(module.text_proj.bias)
init.xavier_uniform_(module.values_vision_proj.weight)
init.zeros_(module.values_vision_proj.bias)
init.xavier_uniform_(module.values_text_proj.weight)
init.zeros_(module.values_text_proj.bias)
init.xavier_uniform_(module.out_vision_proj.weight)
init.zeros_(module.out_vision_proj.bias)
init.xavier_uniform_(module.out_text_proj.weight)
init.zeros_(module.out_text_proj.bias)
elif isinstance(module, GroundingDinoFusionLayer):
init.constant_(module.vision_param, 1e-4)
init.constant_(module.text_param, 1e-4)
elif isinstance(module, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)):
init.normal_(module.weight, mean=0.0, std=std)
if module.bias is not None:
init.zeros_(module.bias)
elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
init.ones_(module.weight)
init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
init.normal_(module.weight, mean=0.0, std=std)
# Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
init.zeros_(module.weight[module.padding_idx])
elif isinstance(module, GroundingDinoMLPPredictionHead):
init.constant_(module.layers[-1].weight, 0)
init.constant_(module.layers[-1].bias, 0)
if hasattr(module, "reference_points") and not self.config.two_stage:
init.xavier_uniform_(module.reference_points.weight, gain=1.0)
init.constant_(module.reference_points.bias, 0.0)
if hasattr(module, "level_embed"):
init.normal_(module.level_embed)
def _set_gradient_checkpointing(self, module, value=False):
if isinstance(module, GroundingDinoDecoder):
module.gradient_checkpointing = value
| GroundingDinoPreTrainedModel |
python | pallets__jinja | src/jinja2/exceptions.py | {
"start": 4458,
"end": 4625
} | class ____(TemplateError):
"""A generic runtime error in the template engine. Under some situations
Jinja may raise this exception.
"""
| TemplateRuntimeError |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_with_poly.py | {
"start": 5132,
"end": 5202
} | class ____(_WithPolymorphicBase, _Polymorphic):
pass
| PolymorphicTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 24922,
"end": 25291
} | class ____(sgqlc.types.Enum):
"""Properties by which gist connections can be ordered.
Enumeration Choices:
* `CREATED_AT`: Order gists by creation time
* `PUSHED_AT`: Order gists by push time
* `UPDATED_AT`: Order gists by update time
"""
__schema__ = github_schema
__choices__ = ("CREATED_AT", "PUSHED_AT", "UPDATED_AT")
| GistOrderField |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/emr.py | {
"start": 20421,
"end": 25270
} | class ____(EmrBaseSensor):
"""
Poll the state of the step until it reaches any of the target states; raise AirflowException on failure.
With the default target states, sensor waits step to be completed.
.. seealso::
For more information on how to use this sensor, take a look at the guide:
:ref:`howto/sensor:EmrStepSensor`
:param job_flow_id: job_flow_id which contains the step check the state of
:param step_id: step to check the state of
:param target_states: the target states, sensor waits until
step reaches any of these states. In case of deferrable sensor it will
for reach to terminal state
:param failed_states: the failure states, sensor fails when
step reaches any of these states
:param max_attempts: Maximum number of tries before failing
:param deferrable: Run sensor in the deferrable mode.
"""
template_fields: Sequence[str] = aws_template_fields(
"job_flow_id", "step_id", "target_states", "failed_states"
)
template_ext: Sequence[str] = ()
operator_extra_links = (
EmrClusterLink(),
EmrLogsLink(),
)
def __init__(
self,
*,
job_flow_id: str,
step_id: str,
target_states: Iterable[str] | None = None,
failed_states: Iterable[str] | None = None,
max_attempts: int = 60,
deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
**kwargs,
):
super().__init__(**kwargs)
self.job_flow_id = job_flow_id
self.step_id = step_id
self.target_states = target_states or ["COMPLETED"]
self.failed_states = failed_states or ["CANCELLED", "FAILED", "INTERRUPTED"]
self.max_attempts = max_attempts
self.deferrable = deferrable
def get_emr_response(self, context: Context) -> dict[str, Any]:
"""
Make an API call with boto3 and get details about the cluster step.
.. seealso::
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/emr.html#EMR.Client.describe_step
:return: response
"""
self.log.info("Poking step %s on cluster %s", self.step_id, self.job_flow_id)
response = self.hook.conn.describe_step(ClusterId=self.job_flow_id, StepId=self.step_id)
EmrClusterLink.persist(
context=context,
operator=self,
region_name=self.hook.conn_region_name,
aws_partition=self.hook.conn_partition,
job_flow_id=self.job_flow_id,
)
EmrLogsLink.persist(
context=context,
operator=self,
region_name=self.hook.conn_region_name,
aws_partition=self.hook.conn_partition,
job_flow_id=self.job_flow_id,
log_uri=get_log_uri(emr_client=self.hook.conn, job_flow_id=self.job_flow_id),
)
return response
@staticmethod
def state_from_response(response: dict[str, Any]) -> str:
"""
Get state from response dictionary.
:param response: response from AWS API
:return: execution state of the cluster step
"""
return response["Step"]["Status"]["State"]
@staticmethod
def failure_message_from_response(response: dict[str, Any]) -> str | None:
"""
Get failure message from response dictionary.
:param response: response from AWS API
:return: failure message
"""
fail_details = response["Step"]["Status"].get("FailureDetails")
if fail_details:
return (
f"for reason {fail_details.get('Reason')} "
f"with message {fail_details.get('Message')} and log file {fail_details.get('LogFile')}"
)
return None
def execute(self, context: Context) -> None:
if not self.deferrable:
super().execute(context=context)
elif not self.poke(context):
self.defer(
timeout=timedelta(seconds=self.max_attempts * self.poke_interval),
trigger=EmrStepSensorTrigger(
job_flow_id=self.job_flow_id,
step_id=self.step_id,
waiter_delay=int(self.poke_interval),
waiter_max_attempts=self.max_attempts,
aws_conn_id=self.aws_conn_id,
),
method_name="execute_complete",
)
def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> None:
validated_event = validate_execute_complete_event(event)
if validated_event["status"] != "success":
raise AirflowException(f"Error while running job: {validated_event}")
self.log.info("Job %s completed.", self.job_flow_id)
| EmrStepSensor |
python | chroma-core__chroma | chromadb/test/api/test_schema_e2e.py | {
"start": 2106,
"end": 9477
} | class ____(EmbeddingFunction[List[str]]):
"""Embedding function that records inputs for search embedding tests."""
def __init__(self, label: str = "default") -> None:
self._label = label
self.call_inputs: List[List[str]] = []
self.query_inputs: List[List[str]] = []
def __call__(self, input: List[str]) -> Embeddings:
self.call_inputs.append(list(input))
vectors = [[float(len(text)), float(len(text)) + 0.5] for text in input]
return cast(Embeddings, vectors)
def embed_query(self, input: List[str]) -> Embeddings:
self.query_inputs.append(list(input))
vectors = [[float(len(text)), float(len(text)) + 1.5] for text in input]
return cast(Embeddings, vectors)
@staticmethod
def name() -> str:
return "recording_search_ef"
def get_config(self) -> Dict[str, Any]:
return {"label": self._label}
@staticmethod
def build_from_config(config: Dict[str, Any]) -> "RecordingSearchEmbeddingFunction":
return RecordingSearchEmbeddingFunction(config.get("label", "default"))
def test_schema_vector_config_persistence(
client_factories: "ClientFactories",
) -> None:
"""Ensure schema-provided SPANN settings persist across client restarts."""
client = client_factories.create_client_from_system()
client.reset()
collection_name = f"schema_spann_{uuid4().hex}"
schema = Schema()
schema.create_index(
config=VectorIndexConfig(
space="cosine",
spann=SpannIndexConfig(
search_nprobe=16,
write_nprobe=32,
ef_construction=120,
max_neighbors=24,
),
)
)
collection = client.get_or_create_collection(
name=collection_name,
schema=schema,
)
persisted_schema = collection.schema
assert persisted_schema is not None
print(persisted_schema.serialize_to_json())
embedding_override = persisted_schema.keys["#embedding"].float_list
assert embedding_override is not None
vector_index = embedding_override.vector_index
assert vector_index is not None
assert vector_index.enabled is True
assert vector_index.config is not None
assert vector_index.config.space is not None
assert vector_index.config.space == "cosine"
client_reloaded = client_factories.create_client_from_system()
reloaded_collection = client_reloaded.get_collection(
name=collection_name,
)
reloaded_schema = reloaded_collection.schema
assert reloaded_schema is not None
reloaded_embedding_override = reloaded_schema.keys["#embedding"].float_list
assert reloaded_embedding_override is not None
reloaded_vector_index = reloaded_embedding_override.vector_index
assert reloaded_vector_index is not None
assert reloaded_vector_index.config is not None
assert reloaded_vector_index.config.space is not None
assert reloaded_vector_index.config.space == "cosine"
def test_schema_vector_config_persistence_with_ef(
client_factories: "ClientFactories",
) -> None:
"""Ensure schema-provided SPANN settings persist across client restarts."""
client = client_factories.create_client_from_system()
client.reset()
collection_name = f"schema_spann_{uuid4().hex}"
schema = Schema()
embedding_function = SimpleEmbeddingFunction(dim=6)
schema.create_index(
config=VectorIndexConfig(
space="cosine",
embedding_function=embedding_function,
spann=SpannIndexConfig(
search_nprobe=16,
write_nprobe=32,
ef_construction=120,
max_neighbors=24,
),
)
)
collection = client.get_or_create_collection(
name=collection_name,
schema=schema,
)
persisted_schema = collection.schema
assert persisted_schema is not None
print(persisted_schema.serialize_to_json())
embedding_override = persisted_schema.keys["#embedding"].float_list
assert embedding_override is not None
vector_index = embedding_override.vector_index
assert vector_index is not None
assert vector_index.enabled is True
assert vector_index.config is not None
assert vector_index.config.space is not None
assert vector_index.config.space == "cosine"
if not is_spann_disabled_mode:
assert vector_index.config.spann is not None
spann_config = vector_index.config.spann
assert spann_config.search_nprobe == 16
assert spann_config.write_nprobe == 32
assert spann_config.ef_construction == 120
assert spann_config.max_neighbors == 24
else:
assert vector_index.config.spann is None
assert vector_index.config.hnsw is not None
hnsw_config = vector_index.config.hnsw
assert hnsw_config.ef_construction == 100
assert hnsw_config.ef_search == 100
assert hnsw_config.max_neighbors == 16
assert hnsw_config.resize_factor == 1.2
ef = vector_index.config.embedding_function
assert ef is not None
assert ef.name() == "simple_ef"
assert ef.get_config() == {"dim": 6}
persisted_json = persisted_schema.serialize_to_json()
if not is_spann_disabled_mode:
spann_json = persisted_json["keys"]["#embedding"]["float_list"]["vector_index"][
"config"
]["spann"]
assert spann_json["search_nprobe"] == 16
assert spann_json["write_nprobe"] == 32
else:
hnsw_json = persisted_json["keys"]["#embedding"]["float_list"]["vector_index"][
"config"
]["hnsw"]
assert hnsw_json["ef_construction"] == 100
assert hnsw_json["ef_search"] == 100
assert hnsw_json["max_neighbors"] == 16
client_reloaded = client_factories.create_client_from_system()
reloaded_collection = client_reloaded.get_collection(
name=collection_name,
)
reloaded_schema = reloaded_collection.schema
assert reloaded_schema is not None
reloaded_embedding_override = reloaded_schema.keys["#embedding"].float_list
assert reloaded_embedding_override is not None
reloaded_vector_index = reloaded_embedding_override.vector_index
assert reloaded_vector_index is not None
assert reloaded_vector_index.config is not None
assert reloaded_vector_index.config.space is not None
assert reloaded_vector_index.config.space == "cosine"
if not is_spann_disabled_mode:
assert reloaded_vector_index.config.spann is not None
assert reloaded_vector_index.config.spann.search_nprobe == 16
assert reloaded_vector_index.config.spann.write_nprobe == 32
else:
assert reloaded_vector_index.config.hnsw is not None
assert reloaded_vector_index.config.hnsw.ef_construction == 100
assert reloaded_vector_index.config.hnsw.ef_search == 100
assert reloaded_vector_index.config.hnsw.max_neighbors == 16
assert reloaded_vector_index.config.hnsw.resize_factor == 1.2
config = reloaded_collection.configuration
assert config is not None
config_ef = config.get("embedding_function")
assert config_ef is not None
assert config_ef.name() == "simple_ef"
assert config_ef.get_config() == {"dim": 6}
@register_sparse_embedding_function
| RecordingSearchEmbeddingFunction |
python | chardet__chardet | chardet/enums.py | {
"start": 1370,
"end": 1683
} | class ____:
"""
This enum represents the different categories language models for
``SingleByteCharsetProber`` put characters into.
Anything less than CONTROL is considered a letter.
"""
UNDEFINED = 255
LINE_BREAK = 254
SYMBOL = 253
DIGIT = 252
CONTROL = 251
| CharacterCategory |
python | getsentry__sentry | tests/sentry/relocation/api/endpoints/artifacts/test_details.py | {
"start": 1010,
"end": 1953
} | class ____(APITestCase):
endpoint = "sentry-api-0-relocations-artifacts-details"
method = "GET"
def setUp(self) -> None:
super().setUp()
self.owner = self.create_user(email="owner@example.com", is_superuser=False, is_staff=False)
self.superuser = self.create_user(is_superuser=True)
self.staff_user = self.create_user(is_staff=True)
self.relocation: Relocation = Relocation.objects.create(
date_added=TEST_DATE_ADDED,
creator_id=self.owner.id,
owner_id=self.owner.id,
status=Relocation.Status.PAUSE.value,
step=Relocation.Step.PREPROCESSING.value,
want_org_slugs=["foo"],
want_usernames=["alice", "bob"],
latest_notified=Relocation.EmailKind.STARTED.value,
latest_task=OrderedTask.PREPROCESSING_SCAN.name,
latest_task_attempts=1,
)
| GetRelocationArtifactDetailsTest |
python | tiangolo__fastapi | tests/test_no_schema_split.py | {
"start": 701,
"end": 7800
} | class ____(BaseModel):
input: str
output: MessageOutput
app = FastAPI(title="Minimal FastAPI App", version="1.0.0")
@app.post("/messages", response_model=Message)
async def create_message(input_message: str) -> Message:
return Message(
input=input_message,
output=MessageOutput(body=f"Processed: {input_message}"),
)
client = TestClient(app)
def test_create_message():
response = client.post("/messages", params={"input_message": "Hello"})
assert response.status_code == 200, response.text
assert response.json() == {
"input": "Hello",
"output": {"body": "Processed: Hello", "events": []},
}
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "Minimal FastAPI App", "version": "1.0.0"},
"paths": {
"/messages": {
"post": {
"summary": "Create Message",
"operationId": "create_message_messages_post",
"parameters": [
{
"name": "input_message",
"in": "query",
"required": True,
"schema": {"type": "string", "title": "Input Message"},
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Message"
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
}
},
"components": {
"schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError"
},
"type": "array",
"title": "Detail",
}
},
"type": "object",
"title": "HTTPValidationError",
},
"Message": {
"properties": {
"input": {"type": "string", "title": "Input"},
"output": {"$ref": "#/components/schemas/MessageOutput"},
},
"type": "object",
"required": ["input", "output"],
"title": "Message",
},
"MessageEvent": {
"properties": {
"event_type": pydantic_snapshot(
v2=snapshot(
{
"$ref": "#/components/schemas/MessageEventType",
"default": "alpha",
}
),
v1=snapshot(
{
"allOf": [
{
"$ref": "#/components/schemas/MessageEventType"
}
],
"default": "alpha",
}
),
),
"output": {"type": "string", "title": "Output"},
},
"type": "object",
"required": ["output"],
"title": "MessageEvent",
},
"MessageEventType": pydantic_snapshot(
v2=snapshot(
{
"type": "string",
"enum": ["alpha", "beta"],
"title": "MessageEventType",
}
),
v1=snapshot(
{
"type": "string",
"enum": ["alpha", "beta"],
"title": "MessageEventType",
"description": "An enumeration.",
}
),
),
"MessageOutput": {
"properties": {
"body": {"type": "string", "title": "Body", "default": ""},
"events": {
"items": {"$ref": "#/components/schemas/MessageEvent"},
"type": "array",
"title": "Events",
"default": [],
},
},
"type": "object",
"title": "MessageOutput",
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
"type": "array",
"title": "Location",
},
"msg": {"type": "string", "title": "Message"},
"type": {"type": "string", "title": "Error Type"},
},
"type": "object",
"required": ["loc", "msg", "type"],
"title": "ValidationError",
},
}
},
}
)
| Message |
python | wandb__wandb | wandb/sdk/artifacts/storage_policy.py | {
"start": 671,
"end": 2546
} | class ____(ABC):
_api: InternalApi | None = None
def __init_subclass__(cls, **kwargs: Any) -> None:
super().__init_subclass__(**kwargs)
_POLICY_REGISTRY[cls.name()] = cls
@classmethod
def lookup_by_name(cls, name: str) -> type[StoragePolicy]:
if policy := _POLICY_REGISTRY.get(name):
return policy
raise ValueError(f"Failed to find storage policy {name!r}")
@classmethod
@abstractmethod
def name(cls) -> str:
raise NotImplementedError
@classmethod
@abstractmethod
def from_config(cls, config: StoragePolicyConfig) -> StoragePolicy:
raise NotImplementedError
@abstractmethod
def config(self) -> dict[str, Any]:
raise NotImplementedError
@abstractmethod
def load_file(
self,
artifact: Artifact,
manifest_entry: ArtifactManifestEntry,
dest_path: str | None = None,
executor: concurrent.futures.Executor | None = None,
) -> FilePathStr:
raise NotImplementedError
@abstractmethod
def store_file(
self,
artifact_id: str,
artifact_manifest_id: str,
entry: ArtifactManifestEntry,
preparer: StepPrepare,
progress_callback: ProgressFn | None = None,
) -> bool:
raise NotImplementedError
@abstractmethod
def store_reference(
self,
artifact: Artifact,
path: URIStr | FilePathStr,
name: str | None = None,
checksum: bool = True,
max_objects: int | None = None,
) -> list[ArtifactManifestEntry]:
raise NotImplementedError
@abstractmethod
def load_reference(
self,
manifest_entry: ArtifactManifestEntry,
local: bool = False,
dest_path: str | None = None,
) -> FilePathStr | URIStr:
raise NotImplementedError
| StoragePolicy |
python | getsentry__sentry | tests/sentry/relocation/tasks/test_process.py | {
"start": 76821,
"end": 84051
} | class ____(RelocationTaskTestCase, TransactionTestCase):
def setUp(self) -> None:
RelocationTaskTestCase.setUp(self)
TransactionTestCase.setUp(self)
self.relocation.step = Relocation.Step.VALIDATING.value
self.relocation.latest_task = OrderedTask.VALIDATING_COMPLETE.name
self.relocation.save()
self.storage = get_relocation_storage()
def test_success_self_hosted(self, postprocessing_mock: Mock, fake_kms_client: Mock) -> None:
self.mock_kms_client(fake_kms_client)
org_count = Organization.objects.filter(slug__startswith="testing").count()
importing(self.uuid)
assert postprocessing_mock.call_count == 1
assert Organization.objects.filter(slug__startswith="testing").count() == org_count + 1
assert (
Organization.objects.filter(
slug__startswith="testing", status=OrganizationStatus.RELOCATION_PENDING_APPROVAL
).count()
== 1
)
assert RegionImportChunk.objects.filter(import_uuid=self.uuid).count() == 9
assert sorted(RegionImportChunk.objects.values_list("model", flat=True)) == [
"sentry.organization",
"sentry.organizationmember",
"sentry.organizationmemberteam",
"sentry.project",
"sentry.projectkey",
"sentry.projectoption",
"sentry.projectteam",
"sentry.rule",
"sentry.team",
]
with assume_test_silo_mode(SiloMode.CONTROL):
assert ControlImportChunk.objects.filter(import_uuid=self.uuid).count() == 2
assert sorted(ControlImportChunk.objects.values_list("model", flat=True)) == [
"sentry.user",
"sentry.useremail",
]
def test_success_saas_to_saas(self, postprocessing_mock: Mock, fake_kms_client: Mock) -> None:
org_count = Organization.objects.filter(slug__startswith="testing").count()
with assume_test_silo_mode(SiloMode.CONTROL):
user_count = User.objects.all().count()
# Create an export checkpointer, so that we can validate that it stores checkpoints properly
# over multiple export attempts.
decryptor = LocalFileDecryptor(BytesIO(self.priv_key_pem))
encryptor = LocalFileEncryptor(BytesIO(self.pub_key_pem))
export_checkpointer = StorageBackedCheckpointExporter(
crypto=EncryptorDecryptorPair(
encryptor=encryptor,
decryptor=decryptor,
),
uuid=self.relocation.uuid,
storage=self.storage,
)
with TemporaryDirectory() as tmp_dir:
tmp_priv_key_path = Path(tmp_dir).joinpath("key")
tmp_pub_key_path = Path(tmp_dir).joinpath("key.pub")
with open(tmp_priv_key_path, "wb") as f:
f.write(self.priv_key_pem)
with open(tmp_pub_key_path, "wb") as f:
f.write(self.pub_key_pem)
# Export the existing state of the `testing` organization, so that we retain exact ids.
export_contents = BytesIO()
export_in_organization_scope(
export_contents,
org_filter=set(self.relocation.want_org_slugs),
printer=Printer(),
checkpointer=export_checkpointer,
)
# Verify cache writes, to the checkpoint cache.
(_, num_checkpoints) = self.storage.listdir(
f"runs/{self.relocation.uuid}/saas_to_saas_export/_checkpoints/"
)
assert len(num_checkpoints) > 0
# Export again, to sanity-check the export checkpointer.
reexport_contents = BytesIO()
export_in_organization_scope(
reexport_contents,
org_filter=set(self.relocation.want_org_slugs),
printer=Printer(),
checkpointer=export_checkpointer,
)
# Verify no cache writes, to the checkpoint cache on the second pass, then check for output
# equality.
(_, num_recheckpoints) = self.storage.listdir(
f"runs/{self.relocation.uuid}/saas_to_saas_export/_checkpoints/"
)
assert num_checkpoints == num_recheckpoints
assert export_contents.getvalue() == reexport_contents.getvalue()
export_contents.seek(0)
# Convert this into a `SAAS_TO_SAAS` relocation, and use the data we just exported as the
# import blob.
file = RelocationFile.objects.get(relocation=self.relocation).file
self.tarball = create_encrypted_export_tarball(
json.load(export_contents), encryptor
).getvalue()
file.putfile(BytesIO(self.tarball), blob_size=RELOCATION_BLOB_SIZE)
self.mock_kms_client(fake_kms_client)
self.relocation.provenance = Relocation.Provenance.SAAS_TO_SAAS
self.relocation.save()
# Now, try importing again, which should enable user merging.
importing(self.uuid)
with assume_test_silo_mode(SiloMode.CONTROL):
# User counts should NOT change, since `merge_users` should be enabled.
assert User.objects.all().count() == user_count
common_user = User.objects.get(username="existing_org_owner@example.com")
# The existing user should now be in both orgs.
assert OrganizationMember.objects.filter(user_id=common_user.id).count() == 2
assert postprocessing_mock.call_count == 1
assert Organization.objects.filter(slug__startswith="testing").count() == org_count + 1
assert (
Organization.objects.filter(
slug__startswith="testing", status=OrganizationStatus.RELOCATION_PENDING_APPROVAL
).count()
== 1
)
with assume_test_silo_mode(SiloMode.CONTROL):
assert ControlImportChunk.objects.filter(import_uuid=self.uuid).count() == 1
assert sorted(ControlImportChunk.objects.values_list("model", flat=True)) == [
"sentry.user",
# We don't overwrite `sentry.useremail`, retaining the existing value instead.
]
def test_pause(self, postprocessing_mock: Mock, fake_kms_client: Mock) -> None:
self.mock_kms_client(fake_kms_client)
self.relocation.scheduled_pause_at_step = Relocation.Step.IMPORTING.value
self.relocation.save()
importing(self.uuid)
assert fake_kms_client.return_value.asymmetric_decrypt.call_count == 0
assert fake_kms_client.return_value.get_public_key.call_count == 0
assert postprocessing_mock.call_count == 0
relocation: Relocation = Relocation.objects.get(uuid=self.uuid)
assert relocation.status == Relocation.Status.PAUSE.value
assert relocation.step == Relocation.Step.IMPORTING.value
assert relocation.scheduled_pause_at_step is None
assert relocation.latest_task == OrderedTask.IMPORTING.name
@patch("sentry.relocation.utils.MessageBuilder")
@patch("sentry.signals.relocated.send_robust")
@patch("sentry.signals.relocation_redeem_promo_code.send_robust")
@patch("sentry.relocation.tasks.process.notifying_unhide.apply_async")
@patch("sentry.analytics.record")
| ImportingTest |
python | ray-project__ray | python/ray/data/tests/unit/test_datatype.py | {
"start": 2489,
"end": 3607
} | class ____:
"""Test DataType validation and initialization."""
@pytest.mark.parametrize(
"valid_type",
[
pa.int64(),
pa.string(),
pa.timestamp("s"),
np.dtype("int32"),
np.dtype("float64"),
int,
str,
float,
],
)
def test_post_init_accepts_valid_types(self, valid_type):
"""Test that __post_init__ accepts valid type objects."""
# Should not raise
dt = DataType(valid_type)
assert dt._physical_dtype == valid_type
@pytest.mark.parametrize(
"invalid_type",
[
"string",
123,
[1, 2, 3],
{"key": "value"},
object(),
],
)
def test_post_init_rejects_invalid_types(self, invalid_type):
"""Test that __post_init__ rejects invalid type objects."""
with pytest.raises(
TypeError,
match="DataType supports only PyArrow DataType, NumPy dtype, or Python type",
):
DataType(invalid_type)
| TestDataTypeValidation |
python | lepture__authlib | tests/flask/test_oauth2/test_client_registration_endpoint_oidc.py | {
"start": 404,
"end": 21030
} | class ____(_ClientRegistrationEndpoint):
software_statement_alg_values_supported = ["RS256"]
def authenticate_token(self, request):
auth_header = request.headers.get("Authorization")
if auth_header:
request.user_id = 1
return auth_header
def resolve_public_key(self, request):
return read_file_path("rsa_public.pem")
def save_client(self, client_info, client_metadata, request):
client = Client(user_id=request.user_id, **client_info)
client.set_client_metadata(client_metadata)
db.session.add(client)
db.session.commit()
return client
@pytest.fixture
def metadata():
return {}
@pytest.fixture(autouse=True)
def server(server, app, metadata):
class MyClientRegistration(ClientRegistrationEndpoint):
def get_server_metadata(self):
return metadata
server.register_endpoint(
MyClientRegistration(
claims_classes=[OAuth2ClientMetadataClaims, OIDCClientMetadataClaims]
)
)
@app.route("/create_client", methods=["POST"])
def create_client():
return server.create_endpoint_response("client_registration")
return server
def test_application_type(test_client):
# Nominal case
body = {
"application_type": "web",
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["application_type"] == "web"
# Default case
# The default, if omitted, is that any algorithm supported by the OP and the RP MAY be used.
body = {
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["application_type"] == "web"
# Error case
body = {
"application_type": "invalid",
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
def test_token_endpoint_auth_signing_alg_supported(test_client, metadata):
metadata["token_endpoint_auth_signing_alg_values_supported"] = ["RS256", "ES256"]
# Nominal case
body = {
"token_endpoint_auth_signing_alg": "ES256",
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["token_endpoint_auth_signing_alg"] == "ES256"
# Default case
# The default, if omitted, is that any algorithm supported by the OP and the RP MAY be used.
body = {
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
# Error case
body = {
"token_endpoint_auth_signing_alg": "RS512",
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
def test_subject_types_supported(test_client, metadata):
metadata["subject_types_supported"] = ["public", "pairwise"]
# Nominal case
body = {"subject_type": "public", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["subject_type"] == "public"
# Error case
body = {"subject_type": "invalid", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
def test_id_token_signing_alg_values_supported(test_client, metadata):
metadata["id_token_signing_alg_values_supported"] = ["RS256", "ES256"]
# Default
# The default, if omitted, is RS256.
body = {"client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["id_token_signed_response_alg"] == "RS256"
# Nominal case
body = {"id_token_signed_response_alg": "ES256", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["id_token_signed_response_alg"] == "ES256"
# Error case
body = {"id_token_signed_response_alg": "RS512", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] == "invalid_client_metadata"
def test_id_token_signing_alg_values_none(test_client, metadata):
# The value none MUST NOT be used as the ID Token alg value unless the Client uses
# only Response Types that return no ID Token from the Authorization Endpoint
# (such as when only using the Authorization Code Flow).
metadata["id_token_signing_alg_values_supported"] = ["none", "RS256", "ES256"]
# Nominal case
body = {
"id_token_signed_response_alg": "none",
"client_name": "Authlib",
"response_type": "code",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["id_token_signed_response_alg"] == "none"
# Error case
body = {
"id_token_signed_response_alg": "none",
"client_name": "Authlib",
"response_type": "id_token",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] == "invalid_client_metadata"
def test_id_token_encryption_alg_values_supported(test_client, metadata):
metadata["id_token_encryption_alg_values_supported"] = ["RS256", "ES256"]
# Default case
body = {"client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert "id_token_encrypted_response_enc" not in resp
# If id_token_encrypted_response_alg is specified, the default
# id_token_encrypted_response_enc value is A128CBC-HS256.
body = {"id_token_encrypted_response_alg": "RS256", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["id_token_encrypted_response_enc"] == "A128CBC-HS256"
# Nominal case
body = {"id_token_encrypted_response_alg": "ES256", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["id_token_encrypted_response_alg"] == "ES256"
# Error case
body = {"id_token_encrypted_response_alg": "RS512", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
def test_id_token_encryption_enc_values_supported(test_client, metadata):
metadata["id_token_encryption_enc_values_supported"] = ["A128CBC-HS256", "A256GCM"]
# Nominal case
body = {
"id_token_encrypted_response_alg": "RS256",
"id_token_encrypted_response_enc": "A256GCM",
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["id_token_encrypted_response_alg"] == "RS256"
assert resp["id_token_encrypted_response_enc"] == "A256GCM"
# Error case: missing id_token_encrypted_response_alg
body = {"id_token_encrypted_response_enc": "A256GCM", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
# Error case: alg not in server metadata
body = {"id_token_encrypted_response_enc": "A128GCM", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
def test_userinfo_signing_alg_values_supported(test_client, metadata):
metadata["userinfo_signing_alg_values_supported"] = ["RS256", "ES256"]
# Nominal case
body = {"userinfo_signed_response_alg": "ES256", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["userinfo_signed_response_alg"] == "ES256"
# Error case
body = {"userinfo_signed_response_alg": "RS512", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
def test_userinfo_encryption_alg_values_supported(test_client, metadata):
metadata["userinfo_encryption_alg_values_supported"] = ["RS256", "ES256"]
# Nominal case
body = {"userinfo_encrypted_response_alg": "ES256", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["userinfo_encrypted_response_alg"] == "ES256"
# Error case
body = {"userinfo_encrypted_response_alg": "RS512", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
def test_userinfo_encryption_enc_values_supported(test_client, metadata):
metadata["userinfo_encryption_enc_values_supported"] = ["A128CBC-HS256", "A256GCM"]
# Default case
body = {"client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert "userinfo_encrypted_response_enc" not in resp
# If userinfo_encrypted_response_alg is specified, the default
# userinfo_encrypted_response_enc value is A128CBC-HS256.
body = {"userinfo_encrypted_response_alg": "RS256", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["userinfo_encrypted_response_enc"] == "A128CBC-HS256"
# Nominal case
body = {
"userinfo_encrypted_response_alg": "RS256",
"userinfo_encrypted_response_enc": "A256GCM",
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["userinfo_encrypted_response_alg"] == "RS256"
assert resp["userinfo_encrypted_response_enc"] == "A256GCM"
# Error case: no userinfo_encrypted_response_alg
body = {"userinfo_encrypted_response_enc": "A256GCM", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
# Error case: alg not in server metadata
body = {"userinfo_encrypted_response_enc": "A128GCM", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
def test_acr_values_supported(test_client, metadata):
metadata["acr_values_supported"] = [
"urn:mace:incommon:iap:silver",
"urn:mace:incommon:iap:bronze",
]
# Nominal case
body = {
"default_acr_values": ["urn:mace:incommon:iap:silver"],
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["default_acr_values"] == ["urn:mace:incommon:iap:silver"]
# Error case
body = {
"default_acr_values": [
"urn:mace:incommon:iap:silver",
"urn:mace:incommon:iap:gold",
],
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
def test_request_object_signing_alg_values_supported(test_client, metadata):
metadata["request_object_signing_alg_values_supported"] = ["RS256", "ES256"]
# Nominal case
body = {"request_object_signing_alg": "ES256", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["request_object_signing_alg"] == "ES256"
# Error case
body = {"request_object_signing_alg": "RS512", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
def test_request_object_encryption_alg_values_supported(test_client, metadata):
metadata["request_object_encryption_alg_values_supported"] = ["RS256", "ES256"]
# Nominal case
body = {
"request_object_encryption_alg": "ES256",
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["request_object_encryption_alg"] == "ES256"
# Error case
body = {
"request_object_encryption_alg": "RS512",
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
def test_request_object_encryption_enc_values_supported(test_client, metadata):
metadata["request_object_encryption_enc_values_supported"] = [
"A128CBC-HS256",
"A256GCM",
]
# Default case
body = {"client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert "request_object_encryption_enc" not in resp
# If request_object_encryption_alg is specified, the default
# request_object_encryption_enc value is A128CBC-HS256.
body = {"request_object_encryption_alg": "RS256", "client_name": "Authlib"}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["request_object_encryption_enc"] == "A128CBC-HS256"
# Nominal case
body = {
"request_object_encryption_alg": "RS256",
"request_object_encryption_enc": "A256GCM",
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["request_object_encryption_alg"] == "RS256"
assert resp["request_object_encryption_enc"] == "A256GCM"
# Error case: missing request_object_encryption_alg
body = {
"request_object_encryption_enc": "A256GCM",
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
# Error case: alg not in server metadata
body = {
"request_object_encryption_enc": "A128GCM",
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
def test_require_auth_time(test_client):
# Default case
body = {
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["require_auth_time"] is False
# Nominal case
body = {
"require_auth_time": True,
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["require_auth_time"] is True
# Error case
body = {
"require_auth_time": "invalid",
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
def test_redirect_uri(test_client):
"""RFC6749 indicate that fragments are forbidden in redirect_uri.
The redirection endpoint URI MUST be an absolute URI as defined by
[RFC3986] Section 4.3. [...] The endpoint URI MUST NOT include a
fragment component.
https://www.rfc-editor.org/rfc/rfc6749#section-3.1.2
"""
# Nominal case
body = {
"redirect_uris": ["https://client.test"],
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert "client_id" in resp
assert resp["client_name"] == "Authlib"
assert resp["redirect_uris"] == ["https://client.test"]
# Error case
body = {
"redirect_uris": ["https://client.test#fragment"],
"client_name": "Authlib",
}
rv = test_client.post(
"/create_client", json=body, headers={"Authorization": "bearer abc"}
)
resp = json.loads(rv.data)
assert resp["error"] in "invalid_client_metadata"
| ClientRegistrationEndpoint |
python | huggingface__transformers | tests/models/depth_anything/test_modeling_depth_anything.py | {
"start": 9270,
"end": 12815
} | class ____(unittest.TestCase):
def test_inference(self):
# -- `relative` depth model --
image_processor = DPTImageProcessor.from_pretrained("LiheYoung/depth-anything-small-hf")
model = DepthAnythingForDepthEstimation.from_pretrained("LiheYoung/depth-anything-small-hf").to(torch_device)
image = prepare_img()
inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
# forward pass
with torch.no_grad():
outputs = model(**inputs)
predicted_depth = outputs.predicted_depth
# verify the predicted depth
expected_shape = torch.Size([1, 518, 686])
self.assertEqual(predicted_depth.shape, expected_shape)
expected_slice = torch.tensor(
[[8.8223, 8.6483, 8.6216], [8.3332, 8.6047, 8.7545], [8.6547, 8.6885, 8.7472]],
).to(torch_device)
torch.testing.assert_close(predicted_depth[0, :3, :3], expected_slice, rtol=1e-6, atol=1e-6)
# -- `metric` depth model --
image_processor = DPTImageProcessor.from_pretrained("depth-anything/depth-anything-V2-metric-indoor-small-hf")
model = DepthAnythingForDepthEstimation.from_pretrained(
"depth-anything/depth-anything-V2-metric-indoor-small-hf"
).to(torch_device)
inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
# forward pass
with torch.no_grad():
outputs = model(**inputs)
predicted_depth = outputs.predicted_depth
# verify the predicted depth
expected_shape = torch.Size([1, 518, 686])
self.assertEqual(predicted_depth.shape, expected_shape)
expected_slice = torch.tensor(
[[1.3349, 1.2947, 1.2802], [1.2794, 1.2338, 1.2901], [1.2630, 1.2219, 1.2478]],
).to(torch_device)
torch.testing.assert_close(predicted_depth[0, :3, :3], expected_slice, rtol=1e-4, atol=1e-4)
@pytest.mark.torch_export_test
def test_export(self):
for strict in [False, True]:
with self.subTest(strict=strict):
if strict and get_torch_major_and_minor_version() == "2.7":
self.skipTest(reason="`strict=True` is currently failing with torch 2.7.")
if not is_torch_greater_or_equal_than_2_4:
self.skipTest(reason="This test requires torch >= 2.4 to run.")
model = (
DepthAnythingForDepthEstimation.from_pretrained("LiheYoung/depth-anything-small-hf")
.to(torch_device)
.eval()
)
image_processor = DPTImageProcessor.from_pretrained("LiheYoung/depth-anything-small-hf")
image = prepare_img()
inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
exported_program = torch.export.export(
model,
args=(inputs["pixel_values"],),
strict=strict,
)
with torch.no_grad():
eager_outputs = model(**inputs)
exported_outputs = exported_program.module().forward(inputs["pixel_values"])
self.assertEqual(eager_outputs.predicted_depth.shape, exported_outputs.predicted_depth.shape)
self.assertTrue(
torch.allclose(eager_outputs.predicted_depth, exported_outputs.predicted_depth, atol=1e-4)
)
| DepthAnythingModelIntegrationTest |
python | django__django | tests/test_runner_apps/failures/tests_failures.py | {
"start": 142,
"end": 234
} | class ____(TestCase):
def test_sample(self):
raise Exception("test")
| ErrorTestCase |
python | eth-brownie__brownie | brownie/typing.py | {
"start": 666,
"end": 1001
} | class ____(TypedDict):
name: str | Literal["(anonymous)", "(unknown)"]
data: List[EventData]
decoded: bool
address: ChecksumAddress
# Transactions
TransactionReceiptType = TypeVar("TransactionReceiptType", bound="TransactionReceipt")
# PROJECT
Start = int
Stop = int
Offset = Tuple[Start, Stop]
# Build
| FormattedEvent |
python | fluentpython__example-code-2e | 12-seq-hacking/vector_v5.py | {
"start": 4479,
"end": 7051
} | class ____:
typecode = 'd'
def __init__(self, components):
self._components = array(self.typecode, components)
def __iter__(self):
return iter(self._components)
def __repr__(self):
components = reprlib.repr(self._components)
components = components[components.find('['):-1]
return f'Vector({components})'
def __str__(self):
return str(tuple(self))
def __bytes__(self):
return (bytes([ord(self.typecode)]) +
bytes(self._components))
def __eq__(self, other):
return (len(self) == len(other) and
all(a == b for a, b in zip(self, other)))
def __hash__(self):
hashes = (hash(x) for x in self)
return functools.reduce(operator.xor, hashes, 0)
def __abs__(self):
return math.hypot(*self)
def __bool__(self):
return bool(abs(self))
def __len__(self):
return len(self._components)
def __getitem__(self, key):
if isinstance(key, slice):
cls = type(self)
return cls(self._components[key])
index = operator.index(key)
return self._components[index]
__match_args__ = ('x', 'y', 'z', 't')
def __getattr__(self, name):
cls = type(self)
try:
pos = cls.__match_args__.index(name)
except ValueError:
pos = -1
if 0 <= pos < len(self._components):
return self._components[pos]
msg = f'{cls.__name__!r} object has no attribute {name!r}'
raise AttributeError(msg)
def angle(self, n): # <2>
r = math.hypot(*self[n:])
a = math.atan2(r, self[n-1])
if (n == len(self) - 1) and (self[-1] < 0):
return math.pi * 2 - a
else:
return a
def angles(self): # <3>
return (self.angle(n) for n in range(1, len(self)))
def __format__(self, fmt_spec=''):
if fmt_spec.endswith('h'): # hyperspherical coordinates
fmt_spec = fmt_spec[:-1]
coords = itertools.chain([abs(self)],
self.angles()) # <4>
outer_fmt = '<{}>' # <5>
else:
coords = self
outer_fmt = '({})' # <6>
components = (format(c, fmt_spec) for c in coords) # <7>
return outer_fmt.format(', '.join(components)) # <8>
@classmethod
def frombytes(cls, octets):
typecode = chr(octets[0])
memv = memoryview(octets[1:]).cast(typecode)
return cls(memv)
# end::VECTOR_V5[]
| Vector |
python | falconry__falcon | examples/asgilook/asgilook/images.py | {
"start": 910,
"end": 1368
} | class ____:
def __init__(self, store):
self._store = store
async def on_get(self, req, resp, image_id, width, height):
image = self._store.get(str(image_id))
if not image:
raise falcon.HTTPNotFound
if req.path not in image.thumbnails():
raise falcon.HTTPNotFound
resp.content_type = falcon.MEDIA_JPEG
resp.data = await self._store.make_thumbnail(image, (width, height))
| Thumbnails |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/events.py | {
"start": 4427,
"end": 4722
} | class ____(NodeEvent):
__slots__ = 'style'
def __init__(self, anchor, start_mark=None, end_mark=None, style=None, comment=None):
# type: (Any, Any, Any, Any, Any) -> None
NodeEvent.__init__(self, anchor, start_mark, end_mark, comment)
self.style = style
| AliasEvent |
python | openai__openai-python | src/openai/types/beta/threads/run_create_params.py | {
"start": 1078,
"end": 7801
} | class ____(TypedDict, total=False):
assistant_id: Required[str]
"""
The ID of the
[assistant](https://platform.openai.com/docs/api-reference/assistants) to use to
execute this run.
"""
include: List[RunStepInclude]
"""A list of additional fields to include in the response.
Currently the only supported value is
`step_details.tool_calls[*].file_search.results[*].content` to fetch the file
search result content.
See the
[file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings)
for more information.
"""
additional_instructions: Optional[str]
"""Appends additional instructions at the end of the instructions for the run.
This is useful for modifying the behavior on a per-run basis without overriding
other instructions.
"""
additional_messages: Optional[Iterable[AdditionalMessage]]
"""Adds additional messages to the thread before creating the run."""
instructions: Optional[str]
"""
Overrides the
[instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant)
of the assistant. This is useful for modifying the behavior on a per-run basis.
"""
max_completion_tokens: Optional[int]
"""
The maximum number of completion tokens that may be used over the course of the
run. The run will make a best effort to use only the number of completion tokens
specified, across multiple turns of the run. If the run exceeds the number of
completion tokens specified, the run will end with status `incomplete`. See
`incomplete_details` for more info.
"""
max_prompt_tokens: Optional[int]
"""The maximum number of prompt tokens that may be used over the course of the run.
The run will make a best effort to use only the number of prompt tokens
specified, across multiple turns of the run. If the run exceeds the number of
prompt tokens specified, the run will end with status `incomplete`. See
`incomplete_details` for more info.
"""
metadata: Optional[Metadata]
"""Set of 16 key-value pairs that can be attached to an object.
This can be useful for storing additional information about the object in a
structured format, and querying for objects via API or the dashboard.
Keys are strings with a maximum length of 64 characters. Values are strings with
a maximum length of 512 characters.
"""
model: Union[str, ChatModel, None]
"""
The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to
be used to execute this run. If a value is provided here, it will override the
model associated with the assistant. If not, the model associated with the
assistant will be used.
"""
parallel_tool_calls: bool
"""
Whether to enable
[parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling)
during tool use.
"""
reasoning_effort: Optional[ReasoningEffort]
"""
Constrains effort on reasoning for
[reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently
supported values are `none`, `minimal`, `low`, `medium`, and `high`. Reducing
reasoning effort can result in faster responses and fewer tokens used on
reasoning in a response.
- `gpt-5.1` defaults to `none`, which does not perform reasoning. The supported
reasoning values for `gpt-5.1` are `none`, `low`, `medium`, and `high`. Tool
calls are supported for all reasoning values in gpt-5.1.
- All models before `gpt-5.1` default to `medium` reasoning effort, and do not
support `none`.
- The `gpt-5-pro` model defaults to (and only supports) `high` reasoning effort.
"""
response_format: Optional[AssistantResponseFormatOptionParam]
"""Specifies the format that the model must output.
Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o),
[GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4),
and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.
Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured
Outputs which ensures the model will match your supplied JSON schema. Learn more
in the
[Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).
Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the
message the model generates is valid JSON.
**Important:** when using JSON mode, you **must** also instruct the model to
produce JSON yourself via a system or user message. Without this, the model may
generate an unending stream of whitespace until the generation reaches the token
limit, resulting in a long-running and seemingly "stuck" request. Also note that
the message content may be partially cut off if `finish_reason="length"`, which
indicates the generation exceeded `max_tokens` or the conversation exceeded the
max context length.
"""
temperature: Optional[float]
"""What sampling temperature to use, between 0 and 2.
Higher values like 0.8 will make the output more random, while lower values like
0.2 will make it more focused and deterministic.
"""
tool_choice: Optional[AssistantToolChoiceOptionParam]
"""
Controls which (if any) tool is called by the model. `none` means the model will
not call any tools and instead generates a message. `auto` is the default value
and means the model can pick between generating a message or calling one or more
tools. `required` means the model must call one or more tools before responding
to the user. Specifying a particular tool like `{"type": "file_search"}` or
`{"type": "function", "function": {"name": "my_function"}}` forces the model to
call that tool.
"""
tools: Optional[Iterable[AssistantToolParam]]
"""Override the tools the assistant can use for this run.
This is useful for modifying the behavior on a per-run basis.
"""
top_p: Optional[float]
"""
An alternative to sampling with temperature, called nucleus sampling, where the
model considers the results of the tokens with top_p probability mass. So 0.1
means only the tokens comprising the top 10% probability mass are considered.
We generally recommend altering this or temperature but not both.
"""
truncation_strategy: Optional[TruncationStrategy]
"""Controls for how a thread will be truncated prior to the run.
Use this to control the initial context window of the run.
"""
| RunCreateParamsBase |
python | kamyu104__LeetCode-Solutions | Python/robot-bounded-in-circle.py | {
"start": 29,
"end": 568
} | class ____(object):
def isRobotBounded(self, instructions):
"""
:type instructions: str
:rtype: bool
"""
directions = [[ 1, 0], [0, -1], [-1, 0], [0, 1]]
x, y, i = 0, 0, 0
for instruction in instructions:
if instruction == 'R':
i = (i+1) % 4
elif instruction == 'L':
i = (i-1) % 4
else:
x += directions[i][0]
y += directions[i][1]
return (x == 0 and y == 0) or i > 0
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-recharge/source_recharge/source.py | {
"start": 504,
"end": 913
} | class ____(YamlDeclarativeSource):
def __init__(self) -> None:
super().__init__(**{"path_to_yaml": "manifest.yaml"})
def streams(self, config: Mapping[str, Any]) -> List[Stream]:
auth = RechargeTokenAuthenticator(token=config["access_token"])
streams = super().streams(config=config)
streams.append(Orders(config, authenticator=auth))
return streams
| SourceRecharge |
python | kamyu104__LeetCode-Solutions | Python/find-unique-binary-string.py | {
"start": 29,
"end": 361
} | class ____(object):
def findDifferentBinaryString(self, nums):
"""
:type nums: List[str]
:rtype: str
"""
return "".join("01"[nums[i][i] == '0'] for i in xrange(len(nums)))
# Time: O(k * n) = O(n^2), k is len(nums)
# , n is len(nums[0])
# Space: O(k) = O(n)
| Solution |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 352,
"end": 497
} | class ____(StringEnum):
draft = "draft"
committing = "committing"
committed = "committed"
published = "published"
| VersionStatusEnum |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 601,
"end": 4486
} | class ____(Operation):
def __init__(self, k=1, axes=(0, 1), *, name=None):
super().__init__(name=name)
self.k = k
self.axes = axes
def call(self, array):
return backend.numpy.rot90(array, k=self.k, axes=self.axes)
def compute_output_spec(self, array):
array_shape = list(array.shape)
if len(array_shape) < 2:
raise ValueError(
"Input array must have at least 2 dimensions. "
f"Received: array.shape={array_shape}"
)
if len(self.axes) != 2 or self.axes[0] == self.axes[1]:
raise ValueError(
f"Invalid axes: {self.axes}. "
"Axes must be a tuple of two different dimensions."
)
axis1, axis2 = self.axes
array_shape[axis1], array_shape[axis2] = (
array_shape[axis2],
array_shape[axis1],
)
return KerasTensor(shape=array_shape, dtype=array.dtype)
@keras_export(["keras.ops.rot90", "keras.ops.numpy.rot90"])
def rot90(array, k=1, axes=(0, 1)):
"""Rotate an array by 90 degrees in the plane specified by axes.
This function rotates an array counterclockwise
by 90 degrees `k` times in the plane specified by `axes`.
Supports arrays of two or more dimensions.
Args:
array: Input array to rotate.
k: Number of times the array is rotated by 90 degrees.
axes: A tuple of two integers specifying the
plane of rotation (defaults to `(0, 1)`).
Returns:
Rotated array.
Examples:
>>> import numpy as np
>>> from keras import ops
>>> m = np.array([[1, 2], [3, 4]])
>>> rotated = ops.rot90(m)
>>> rotated
array([[2, 4],
[1, 3]])
>>> m = np.arange(8).reshape((2, 2, 2))
>>> rotated = ops.rot90(m, k=1, axes=(1, 2))
>>> rotated
array([[[1, 3],
[0, 2]],
[[5, 7],
[4, 6]]])
"""
if any_symbolic_tensors((array,)):
return Rot90(k=k, axes=axes).symbolic_call(array)
return backend.numpy.rot90(array, k=k, axes=axes)
def shape_equal(shape1, shape2, axis=None, allow_none=True):
"""Check if two shapes are equal.
Args:
shape1: A list or tuple of integers for first shape to be compared.
shape2: A list or tuple of integers for second shape to be compared.
axis: An integer, list, or tuple of integers (optional):
Axes to ignore during comparison. Defaults to `None`.
allow_none (bool, optional): If `True`, allows `None` in a shape
to match any value in the corresponding position of the other shape.
Defaults to `True`.
Returns:
bool: `True` if shapes are considered equal based on the criteria,
`False` otherwise.
Examples:
>>> shape_equal((32, 64, 128), (32, 64, 128))
True
>>> shape_equal((32, 64, 128), (32, 64, 127))
False
>>> shape_equal((32, 64, None), (32, 64, 128), allow_none=True)
True
>>> shape_equal((32, 64, None), (32, 64, 128), allow_none=False)
False
>>> shape_equal((32, 64, 128), (32, 63, 128), axis=1)
True
>>> shape_equal((32, 64, 128), (32, 63, 127), axis=(1, 2))
True
>>> shape_equal((32, 64, 128), (32, 63, 127), axis=[1,2])
True
>>> shape_equal((32, 64), (32, 64, 128))
False
"""
if len(shape1) != len(shape2):
return False
shape1 = list(shape1)
shape2 = list(shape2)
if axis is not None:
if isinstance(axis, int):
axis = [axis]
for ax in axis:
shape1[ax] = -1
shape2[ax] = -1
if allow_none:
for i in range(len(shape1)):
if shape1[i] is None:
shape1[i] = shape2[i]
if shape2[i] is None:
shape2[i] = shape1[i]
return shape1 == shape2
| Rot90 |
python | getsentry__sentry | tests/sentry/core/endpoints/test_team_release_count.py | {
"start": 148,
"end": 6388
} | class ____(APITestCase):
endpoint = "sentry-api-0-team-release-count"
def test_simple(self) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.organization
org2 = self.create_organization()
org.flags.allow_joinleave = False
org.save()
team1 = self.create_team(organization=org)
team2 = self.create_team(organization=org)
project1 = self.create_project(teams=[team1], organization=org)
project2 = self.create_project(teams=[team2], organization=org2)
project3 = self.create_project(teams=[team1], organization=org)
self.create_member(teams=[team1], user=user, organization=org)
self.login_as(user=user)
release1 = Release.objects.create(
organization_id=org.id, version="1", date_added=before_now(days=15)
)
release1.add_project(project1)
release2 = Release.objects.create(
organization_id=org2.id, version="2", date_added=before_now(days=12)
) # This release isn't returned, its in another org
release2.add_project(project2)
release3 = Release.objects.create(
organization_id=org.id,
version="3",
date_added=before_now(days=10),
date_released=before_now(days=10),
)
release3.add_project(project1)
release4 = Release.objects.create(
organization_id=org.id, version="4", date_added=before_now(days=5)
)
release4.add_project(project3)
release5 = Release.objects.create(
organization_id=org.id, version="5", date_added=before_now(days=5)
)
release5.add_project(project3)
response = self.get_success_response(org.slug, team1.slug)
assert len(response.data) == 3
assert len(response.data["release_counts"]) == 90
assert len(response.data["project_avgs"]) == 2
assert len(response.data["last_week_totals"]) == 1
assert response.data["last_week_totals"][project3.id] == 2
assert response.data["release_counts"][str(before_now(days=0).date())] == 0
assert response.data["release_counts"][str(before_now(days=5).date())] == 2
assert response.data["release_counts"][str(before_now(days=10).date())] == 1
assert response.data["release_counts"][str(before_now(days=15).date())] == 1
release4.add_project(project1) # up the last week total for project1 by 1
response = self.get_success_response(org.slug, team1.slug)
assert len(response.data) == 3
assert len(response.data["release_counts"]) == 90
assert len(response.data["project_avgs"]) == 2
assert len(response.data["last_week_totals"]) == 2
assert response.data["last_week_totals"][project1.id] == 1
assert response.data["last_week_totals"][project3.id] == 2
def test_projects_only_for_current_team(self) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.organization
org.flags.allow_joinleave = False
org.save()
team1 = self.create_team(organization=org)
team2 = self.create_team(organization=org)
project1 = self.create_project(teams=[team1], organization=org)
# Project 2 does not belong to the current team, but shares a release
project2 = self.create_project(teams=[team2], organization=org)
self.create_member(teams=[team1], user=user, organization=org)
self.login_as(user=user)
release1 = Release.objects.create(
organization_id=org.id, version="1", date_added=before_now(days=15)
)
release1.add_project(project1)
release1.add_project(project2)
response = self.get_success_response(org.slug, team1.slug)
assert project2.id not in response.data["project_avgs"]
def test_multi_project_release(self) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.organization
org2 = self.create_organization()
org.flags.allow_joinleave = False
org.save()
team1 = self.create_team(organization=org)
team2 = self.create_team(organization=org)
project1 = self.create_project(teams=[team1], organization=org)
project2 = self.create_project(teams=[team2], organization=org2)
project3 = self.create_project(teams=[team1], organization=org)
self.create_member(teams=[team1], user=user, organization=org)
self.login_as(user=user)
release1 = Release.objects.create(
organization_id=org.id, version="1", date_added=before_now(days=15)
)
release1.add_project(project1)
release1.add_project(project3)
release2 = Release.objects.create(
organization_id=org2.id, version="2", date_added=before_now(days=12)
) # This release isn't returned, its in another org
release2.add_project(project2)
release3 = Release.objects.create(
organization_id=org.id,
version="3",
date_added=before_now(days=10),
date_released=before_now(days=10),
)
release3.add_project(project1)
release4 = Release.objects.create(
organization_id=org.id, version="4", date_added=before_now(days=5)
)
release4.add_project(project3)
release5 = Release.objects.create(
organization_id=org.id, version="5", date_added=before_now(days=5)
)
release5.add_project(project3)
response = self.get_success_response(org.slug, team1.slug)
assert len(response.data) == 3
assert len(response.data["release_counts"]) == 90
assert len(response.data["project_avgs"]) == 2
assert len(response.data["last_week_totals"]) == 1
assert response.data["release_counts"][str(before_now(days=0).date())] == 0
assert response.data["release_counts"][str(before_now(days=5).date())] == 2
assert response.data["release_counts"][str(before_now(days=10).date())] == 1
assert response.data["release_counts"][str(before_now(days=15).date())] == 1
| TeamReleaseCountTest |
python | dask__dask | dask/dataframe/dask_expr/_shuffle.py | {
"start": 37630,
"end": 38004
} | class ____(Blockwise):
_parameters = ["frame", "new_divisions", "ascending", "na_position"]
_defaults = {"ascending": True, "na_position": "last"}
operation = staticmethod(set_partitions_pre)
_is_length_preserving = True
@functools.cached_property
def _meta(self):
return make_meta(self.frame._meta._constructor([0]))
| _SetPartitionsPreSetIndex |
python | huggingface__transformers | src/transformers/models/vit/modeling_vit.py | {
"start": 12720,
"end": 13946
} | class ____(GradientCheckpointingLayer):
"""This corresponds to the Block class in the timm implementation."""
def __init__(self, config: ViTConfig):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = ViTAttention(config)
self.intermediate = ViTIntermediate(config)
self.output = ViTOutput(config)
self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states_norm = self.layernorm_before(hidden_states)
attention_output = self.attention(hidden_states_norm)
# first residual connection
hidden_states = attention_output + hidden_states
# in ViT, layernorm is also applied after self-attention
layer_output = self.layernorm_after(hidden_states)
layer_output = self.intermediate(layer_output)
# second residual connection is done here
layer_output = self.output(layer_output, hidden_states)
return layer_output
| ViTLayer |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mssql/information_schema.py | {
"start": 672,
"end": 832
} | class ____(TypeDecorator):
impl = Unicode
cache_ok = True
def bind_expression(self, bindvalue):
return _cast_on_2005(bindvalue)
| CoerceUnicode |
python | tensorflow__tensorflow | tensorflow/python/ops/summary_ops_v2.py | {
"start": 2689,
"end": 9227
} | class ____:
"""Context manager to implement SummaryWriter.as_default()."""
# Note: this is a class so that it's possible to implement `set_as_default()`
# simply via `as_default().__enter__()`. We can't do that with @contextmanager
# because the `finally` block will be executed when the generator is GCed.
def __init__(self, writer, step=None):
self._writer = writer
self._step = step
self._old_writer = None
self._old_step = None
def __enter__(self):
self._old_writer = _summary_state.writer
_summary_state.writer = self._writer
if self._step is not None:
self._old_step = _summary_state.step
_summary_state.step = self._step
return self._writer
def __exit__(self, *exc):
# Flushes the summary writer in eager mode or in graph functions, but
# not in legacy graph mode (you're on your own there).
_summary_state.writer.flush()
_summary_state.writer = self._old_writer
if self._step is not None:
_summary_state.step = self._old_step
return False
def _should_record_summaries_internal(default_state):
"""Returns boolean Tensor if summaries should/shouldn't be recorded.
Now the summary condition is decided by logical "and" of below conditions:
First, summary writer must be set. Given this constraint is met,
ctx.summary_recording and ctx.summary_recording_distribution_strategy.
The former one is usually set by user, and the latter one is controlled
by DistributionStrategy (tf.distribute.ReplicaContext).
Args:
default_state: can be True or False. The default summary behavior when
summary writer is set and the user does not specify
ctx.summary_recording and ctx.summary_recording_distribution_strategy
is True.
"""
if _summary_state.writer is None:
return constant_op.constant(False)
if not callable(_summary_state.is_recording):
static_cond = tensor_util.constant_value(_summary_state.is_recording)
if static_cond is not None and not static_cond:
return constant_op.constant(False)
resolve = lambda x: x() if callable(x) else x
cond_distributed = resolve(_summary_state.is_recording_distribution_strategy)
cond = resolve(_summary_state.is_recording)
if cond is None:
cond = default_state
return math_ops.logical_and(cond_distributed, cond)
@tf_export("summary.should_record_summaries", v1=[])
def should_record_summaries():
"""Returns boolean Tensor which is True if summaries will be recorded.
If no default summary writer is currently registered, this always returns
False. Otherwise, this reflects the recording condition has been set via
`tf.summary.record_if()` (except that it may return False for some replicas
when using `tf.distribute.Strategy`). If no recording condition is active,
it defaults to True.
"""
return _should_record_summaries_internal(default_state=True)
# Legacy symbol used by tf.contrib.summary.should_record_summaries.
def _legacy_contrib_should_record_summaries():
"""Returns boolean Tensor which is true if summaries should be recorded."""
return _should_record_summaries_internal(default_state=False)
def is_recording_summaries():
"""Returns non-Tensor boolean indicating if summaries are being recorded."""
if _summary_state.writer is None:
return False
if _summary_state.is_recording is None:
return False
return _summary_state.is_recording
@tf_export("summary.record_if", v1=[])
@tf_contextlib.contextmanager
def record_if(condition):
"""Sets summary recording on or off per the provided boolean value.
The provided value can be a python boolean, a scalar boolean Tensor, or
or a callable providing such a value; if a callable is passed it will be
invoked on-demand to determine whether summary writing will occur. Note that
when calling record_if() in an eager mode context, if you intend to provide a
varying condition like `step % 100 == 0`, you must wrap this in a
callable to avoid immediate eager evaluation of the condition. In particular,
using a callable is the only way to have your condition evaluated as part of
the traced body of an @tf.function that is invoked from within the
`record_if()` context.
Args:
condition: can be True, False, a bool Tensor, or a callable providing such.
Yields:
Returns a context manager that sets this value on enter and restores the
previous value on exit.
"""
old = _summary_state.is_recording
try:
_summary_state.is_recording = condition
yield
finally:
_summary_state.is_recording = old
def has_default_writer():
"""Returns a boolean indicating whether a default summary writer exists."""
return _summary_state.writer is not None
# TODO(apassos) consider how to handle local step here.
def record_summaries_every_n_global_steps(n, global_step=None):
"""Sets the should_record_summaries Tensor to true if global_step % n == 0."""
if global_step is None:
global_step = training_util.get_or_create_global_step()
with ops.device("cpu:0"):
should = lambda: math_ops.equal(global_step % n, 0)
if not context.executing_eagerly():
should = should()
return record_if(should)
def always_record_summaries():
"""Sets the should_record_summaries Tensor to always true."""
return record_if(True)
def never_record_summaries():
"""Sets the should_record_summaries Tensor to always false."""
return record_if(False)
@tf_export("summary.experimental.get_step", v1=[])
def get_step():
"""Returns the default summary step for the current thread.
Returns:
The step set by `tf.summary.experimental.set_step()` if one has been set,
otherwise None.
"""
return _summary_state.step
@tf_export("summary.experimental.set_step", v1=[])
def set_step(step):
"""Sets the default summary step for the current thread.
For convenience, this function sets a default value for the `step` parameter
used in summary-writing functions elsewhere in the API so that it need not
be explicitly passed in every such invocation. The value can be a constant
or a variable, and can be retrieved via `tf.summary.experimental.get_step()`.
Note: when using this with @tf.functions, the step value will be captured at
the time the function is traced, so changes to the step outside the function
will not be reflected inside the function unless using a `tf.Variable` step.
Args:
step: An `int64`-castable default step value, or None to unset.
"""
_summary_state.step = step
@tf_export("summary.SummaryWriter", v1=[])
| _SummaryContextManager |
python | PyCQA__pylint | tests/functional/t/type/typedDict.py | {
"start": 148,
"end": 190
} | class ____(TypedDict):
var: int
| CustomTD |
python | sympy__sympy | sympy/core/expr.py | {
"start": 141444,
"end": 142807
} | class ____(Expr):
"""
Expression that is not evaluated unless released.
Examples
========
>>> from sympy import UnevaluatedExpr
>>> from sympy.abc import x
>>> x*(1/x)
1
>>> x*UnevaluatedExpr(1/x)
x*1/x
"""
def __new__(cls, arg, **kwargs):
arg = _sympify(arg)
obj = Expr.__new__(cls, arg, **kwargs)
return obj
def doit(self, **hints):
if hints.get("deep", True):
return self.args[0].doit(**hints)
else:
return self.args[0]
def unchanged(func, *args):
"""Return True if `func` applied to the `args` is unchanged.
Can be used instead of `assert foo == foo`.
Examples
========
>>> from sympy import Piecewise, cos, pi
>>> from sympy.core.expr import unchanged
>>> from sympy.abc import x
>>> unchanged(cos, 1) # instead of assert cos(1) == cos(1)
True
>>> unchanged(cos, pi)
False
Comparison of args uses the builtin capabilities of the object's
arguments to test for equality so args can be defined loosely. Here,
the ExprCondPair arguments of Piecewise compare as equal to the
tuples that can be used to create the Piecewise:
>>> unchanged(Piecewise, (x, x > 1), (0, True))
True
"""
f = func(*args)
return f.func == func and f.args == args
| UnevaluatedExpr |
python | ray-project__ray | python/ray/tests/test_runtime_env_plugin.py | {
"start": 7101,
"end": 11308
} | class ____(DummyPlugin):
name = FAULT_PLUGIN_NAME
async def create(
self,
uri: str,
runtime_env: "RuntimeEnv",
ctx: RuntimeEnvContext,
logger: logging.Logger, # noqa: F821
) -> float:
action = os.environ.get(FAULT_PLUGIN_KEY, "raise")
if action == "raise":
raise RuntimeError(
"Ever tried. Ever failed. No matter. Try again. Fail again. Fail "
"better. -- Waiting for Godot, Samuel Beckett"
)
elif action == "sleep":
await asyncio.sleep(3600)
elif action == "ok":
return
else:
raise ValueError(f"unknown action {action}")
@pytest.mark.parametrize(
"set_runtime_env_plugins",
[
'[{"class":"' + FAULT_PLUGIN_CLASS_PATH + '"}]',
],
indirect=True,
)
def test_task_fails_on_rt_env_failure(
set_runtime_env_plugins,
monkeypatch,
ray_start_cluster,
):
"""
Simulate runtime env failure on a node. The task should fail but the raylet should
not die. See https://github.com/ray-project/ray/pull/46991
"""
cluster = ray_start_cluster
cluster.add_node(num_cpus=0)
ray.init(address=cluster.address)
with monkeypatch.context() as m:
m.setenv(FAULT_PLUGIN_KEY, "raise")
fault_node = cluster.add_node(num_cpus=1)
@ray.remote(num_cpus=0.1, runtime_env={FAULT_PLUGIN_NAME: {}})
def s(a, b):
return a + b
two = ray.put(2)
three = ray.put(3)
mortal = s.remote(two, three)
immortal = s.options(max_retries=-1).remote(two, three)
with pytest.raises(RuntimeEnvSetupError) as e:
ray.get(mortal)
assert "Samuel Beckett" in str(e.value)
# Note: even immortal task will fail because a rt env failure cancels tasks.
with pytest.raises(RuntimeEnvSetupError) as e:
ray.get(immortal)
assert "Samuel Beckett" in str(e.value)
# Assert that the raylet is still alive.
for _ in range(5):
time.sleep(1)
assert (
fault_node.all_processes[ray_constants.PROCESS_TYPE_RAYLET][
0
].process.poll()
is None
)
@pytest.mark.parametrize(
"set_runtime_env_plugins",
[
'[{"class":"' + FAULT_PLUGIN_CLASS_PATH + '"}]',
],
indirect=True,
)
def test_actor_fails_on_rt_env_failure(
set_runtime_env_plugins,
monkeypatch,
ray_start_cluster,
):
"""
Simulate runtime env failure on a node. The actor should be dead, but the raylet
should not die. See https://github.com/ray-project/ray/pull/46991
"""
cluster = ray_start_cluster
cluster.add_node(num_cpus=0)
ray.init(address=cluster.address)
with monkeypatch.context() as m:
m.setenv(FAULT_PLUGIN_KEY, "raise")
fault_node = cluster.add_node(num_cpus=1)
@ray.remote(num_cpus=0.1, runtime_env={FAULT_PLUGIN_NAME: {}})
class Actor:
def __init__(self, a, b):
self.a = a
self.b = b
def ping(self):
return self.a + self.b
two = ray.put(2)
three = ray.put(3)
mortal = Actor.remote(two, three)
immortal = Actor.options(max_restarts=-1).remote(two, three)
with pytest.raises(RuntimeEnvSetupError) as e:
ray.get(mortal.ping.remote())
assert "Samuel Beckett" in str(e.value)
# Note: even immortal actor will die because a rt env failure cancels tasks.
with pytest.raises(RuntimeEnvSetupError) as e:
ray.get(immortal.ping.remote())
assert "Samuel Beckett" in str(e.value)
# Assert that the raylet is still alive.
for _ in range(5):
time.sleep(1)
assert (
fault_node.all_processes[ray_constants.PROCESS_TYPE_RAYLET][
0
].process.poll()
is None
)
PRIORITY_TEST_PLUGIN1_CLASS_PATH = (
"ray.tests.test_runtime_env_plugin.PriorityTestPlugin1"
)
PRIORITY_TEST_PLUGIN1_NAME = "PriorityTestPlugin1"
PRIORITY_TEST_PLUGIN2_CLASS_PATH = (
"ray.tests.test_runtime_env_plugin.PriorityTestPlugin2"
)
PRIORITY_TEST_PLUGIN2_NAME = "PriorityTestPlugin2"
PRIORITY_TEST_ENV_VAR_NAME = "PriorityTestEnv"
| FaultPlugin |
python | fsspec__filesystem_spec | fsspec/caching.py | {
"start": 25592,
"end": 34260
} | class ____(BaseCache):
"""
Cache holding memory as a set of blocks with pre-loading of
the next block in the background.
Requests are only ever made ``blocksize`` at a time, and are
stored in an LRU cache. The least recently accessed block is
discarded when more than ``maxblocks`` are stored. If the
next block is not in cache, it is loaded in a separate thread
in non-blocking way.
Parameters
----------
blocksize : int
The number of bytes to store in each block.
Requests are only ever made for ``blocksize``, so this
should balance the overhead of making a request against
the granularity of the blocks.
fetcher : Callable
size : int
The total size of the file being cached.
maxblocks : int
The maximum number of blocks to cache for. The maximum memory
use for this cache is then ``blocksize * maxblocks``.
"""
name: ClassVar[str] = "background"
def __init__(
self, blocksize: int, fetcher: Fetcher, size: int, maxblocks: int = 32
) -> None:
super().__init__(blocksize, fetcher, size)
self.nblocks = math.ceil(size / blocksize)
self.maxblocks = maxblocks
self._fetch_block_cached = UpdatableLRU(self._fetch_block, maxblocks)
self._thread_executor = ThreadPoolExecutor(max_workers=1)
self._fetch_future_block_number: int | None = None
self._fetch_future: Future[bytes] | None = None
self._fetch_future_lock = threading.Lock()
def cache_info(self) -> UpdatableLRU.CacheInfo:
"""
The statistics on the block cache.
Returns
-------
NamedTuple
Returned directly from the LRU Cache used internally.
"""
return self._fetch_block_cached.cache_info()
def __getstate__(self) -> dict[str, Any]:
state = self.__dict__
del state["_fetch_block_cached"]
del state["_thread_executor"]
del state["_fetch_future_block_number"]
del state["_fetch_future"]
del state["_fetch_future_lock"]
return state
def __setstate__(self, state) -> None:
self.__dict__.update(state)
self._fetch_block_cached = UpdatableLRU(self._fetch_block, state["maxblocks"])
self._thread_executor = ThreadPoolExecutor(max_workers=1)
self._fetch_future_block_number = None
self._fetch_future = None
self._fetch_future_lock = threading.Lock()
def _fetch(self, start: int | None, end: int | None) -> bytes:
if start is None:
start = 0
if end is None:
end = self.size
if start >= self.size or start >= end:
return b""
# byte position -> block numbers
start_block_number = start // self.blocksize
end_block_number = end // self.blocksize
fetch_future_block_number = None
fetch_future = None
with self._fetch_future_lock:
# Background thread is running. Check we we can or must join it.
if self._fetch_future is not None:
assert self._fetch_future_block_number is not None
if self._fetch_future.done():
logger.info("BlockCache joined background fetch without waiting.")
self._fetch_block_cached.add_key(
self._fetch_future.result(), self._fetch_future_block_number
)
# Cleanup the fetch variables. Done with fetching the block.
self._fetch_future_block_number = None
self._fetch_future = None
else:
# Must join if we need the block for the current fetch
must_join = bool(
start_block_number
<= self._fetch_future_block_number
<= end_block_number
)
if must_join:
# Copy to the local variables to release lock
# before waiting for result
fetch_future_block_number = self._fetch_future_block_number
fetch_future = self._fetch_future
# Cleanup the fetch variables. Have a local copy.
self._fetch_future_block_number = None
self._fetch_future = None
# Need to wait for the future for the current read
if fetch_future is not None:
logger.info("BlockCache waiting for background fetch.")
# Wait until result and put it in cache
self._fetch_block_cached.add_key(
fetch_future.result(), fetch_future_block_number
)
# these are cached, so safe to do multiple calls for the same start and end.
for block_number in range(start_block_number, end_block_number + 1):
self._fetch_block_cached(block_number)
# fetch next block in the background if nothing is running in the background,
# the block is within file and it is not already cached
end_block_plus_1 = end_block_number + 1
with self._fetch_future_lock:
if (
self._fetch_future is None
and end_block_plus_1 <= self.nblocks
and not self._fetch_block_cached.is_key_cached(end_block_plus_1)
):
self._fetch_future_block_number = end_block_plus_1
self._fetch_future = self._thread_executor.submit(
self._fetch_block, end_block_plus_1, "async"
)
return self._read_cache(
start,
end,
start_block_number=start_block_number,
end_block_number=end_block_number,
)
def _fetch_block(self, block_number: int, log_info: str = "sync") -> bytes:
"""
Fetch the block of data for `block_number`.
"""
if block_number > self.nblocks:
raise ValueError(
f"'block_number={block_number}' is greater than "
f"the number of blocks ({self.nblocks})"
)
start = block_number * self.blocksize
end = start + self.blocksize
logger.info("BlockCache fetching block (%s) %d", log_info, block_number)
self.total_requested_bytes += end - start
self.miss_count += 1
block_contents = super()._fetch(start, end)
return block_contents
def _read_cache(
self, start: int, end: int, start_block_number: int, end_block_number: int
) -> bytes:
"""
Read from our block cache.
Parameters
----------
start, end : int
The start and end byte positions.
start_block_number, end_block_number : int
The start and end block numbers.
"""
start_pos = start % self.blocksize
end_pos = end % self.blocksize
# kind of pointless to count this as a hit, but it is
self.hit_count += 1
if start_block_number == end_block_number:
block = self._fetch_block_cached(start_block_number)
return block[start_pos:end_pos]
else:
# read from the initial
out = [self._fetch_block_cached(start_block_number)[start_pos:]]
# intermediate blocks
# Note: it'd be nice to combine these into one big request. However
# that doesn't play nicely with our LRU cache.
out.extend(
map(
self._fetch_block_cached,
range(start_block_number + 1, end_block_number),
)
)
# final block
out.append(self._fetch_block_cached(end_block_number)[:end_pos])
return b"".join(out)
caches: dict[str | None, type[BaseCache]] = {
# one custom case
None: BaseCache,
}
def register_cache(cls: type[BaseCache], clobber: bool = False) -> None:
"""'Register' cache implementation.
Parameters
----------
clobber: bool, optional
If set to True (default is False) - allow to overwrite existing
entry.
Raises
------
ValueError
"""
name = cls.name
if not clobber and name in caches:
raise ValueError(f"Cache with name {name!r} is already known: {caches[name]}")
caches[name] = cls
for c in (
BaseCache,
MMapCache,
BytesCache,
ReadAheadCache,
BlockCache,
FirstChunkCache,
AllBytes,
KnownPartsOfAFile,
BackgroundBlockCache,
):
register_cache(c)
| BackgroundBlockCache |
python | Textualize__textual | tests/command_palette/test_no_results.py | {
"start": 112,
"end": 1066
} | class ____(App[None]):
COMMANDS = set()
def on_mount(self) -> None:
self.action_command_palette()
async def test_no_results() -> None:
"""Receiving no results from a search for a command should not be a problem."""
async with CommandPaletteApp().run_test() as pilot:
assert CommandPalette.is_open(pilot.app)
results = pilot.app.screen.query_one(OptionList)
assert results.visible is False
assert results.option_count == 0
await pilot.press("a")
# https://github.com/Textualize/textual/issues/3700 -- note the
# little bit of wiggle room to allow for Windows.
await pilot.pause(delay=CommandPalette._NO_MATCHES_COUNTDOWN + 0.1)
assert results.visible is True
assert results.option_count == 1
assert "No matches found" in str(results.get_option_at_index(0).prompt)
assert results.get_option_at_index(0).disabled is True
| CommandPaletteApp |
python | celery__celery | t/unit/worker/test_consumer.py | {
"start": 883,
"end": 1580
} | class ____:
def get_consumer(self, no_hub=False, **kwargs):
consumer = Consumer(
on_task_request=Mock(),
init_callback=Mock(),
pool=Mock(),
app=self.app,
timer=Mock(),
controller=Mock(),
hub=None if no_hub else Mock(),
**kwargs
)
consumer.blueprint = Mock(name='blueprint')
consumer.pool.num_processes = 2
consumer._restart_state = Mock(name='_restart_state')
consumer.connection = _amqp_connection()
consumer.connection_errors = (socket.error, OSError,)
consumer.conninfo = consumer.connection
return consumer
| ConsumerTestCase |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0006_add_domain_models.py | {
"start": 100,
"end": 1998
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0005_sync_project_model"),
]
operations = [
migrations.CreateModel(
name="Domain",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("url", models.URLField(unique=True, verbose_name="URL")),
(
"machine",
models.BooleanField(default=False, help_text="This URL was auto-created"),
),
(
"cname",
models.BooleanField(
default=False, help_text="This URL is a CNAME for the project"
),
),
(
"canonical",
models.BooleanField(
default=False,
help_text="This URL is the primary one where the documentation is served from.",
),
),
(
"count",
models.IntegerField(
default=0, help_text="Number of times this domain has been hit."
),
),
(
"project",
models.ForeignKey(
related_name="domains",
to="projects.Project",
on_delete=models.CASCADE,
),
),
],
options={
"ordering": ("-canonical", "-machine", "url"),
},
),
]
| Migration |
python | ray-project__ray | rllib/examples/algorithms/dqn/benchmark_dqn_atari.py | {
"start": 9976,
"end": 13227
} | class ____(Stopper):
def __init__(self, benchmark_envs):
self.benchmark_envs = benchmark_envs
def __call__(self, trial_id, result):
# Stop training if the mean reward is reached.
if (
result[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN]
>= self.benchmark_envs[result["env"]][
f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}"
]
):
return True
# Otherwise check, if the total number of timesteps is exceeded.
elif (
result[f"{NUM_ENV_STEPS_SAMPLED_LIFETIME}"]
>= self.benchmark_envs[result["env"]][f"{NUM_ENV_STEPS_SAMPLED_LIFETIME}"]
):
return True
# Otherwise continue training.
else:
return False
# Note, this needs to implemented b/c the parent class is abstract.
def stop_all(self):
return False
# See Table 1 in the Rainbow paper for the hyperparameters.
config = (
DQNConfig()
.environment(
env=tune.grid_search(list(benchmark_envs.keys())),
env_config={
"max_episode_steps": 108000,
"obs_type": "grayscale",
# The authors actually use an action repetition of 4.
"repeat_action_probability": 0.25,
},
clip_rewards=True,
)
.env_runners(
# Every 4 agent steps a training update is performed.
rollout_fragment_length=4,
num_env_runners=1,
env_to_module_connector=_make_env_to_module_connector,
)
# TODO (simon): Adjust to new model_config_dict.
.training(
# Note, the paper uses also an Adam epsilon of 0.00015.
lr=0.0000625,
n_step=3,
tau=1.0,
train_batch_size=32,
target_network_update_freq=32000,
replay_buffer_config={
"type": "PrioritizedEpisodeReplayBuffer",
"capacity": 1000000,
"alpha": 0.5,
# Note the paper used a linear schedule for beta.
"beta": 0.4,
},
# Note, these are frames.
num_steps_sampled_before_learning_starts=80000,
noisy=True,
num_atoms=51,
v_min=-10.0,
v_max=10.0,
double_q=True,
dueling=True,
model={
"cnn_filter_specifiers": [[32, 8, 4], [64, 4, 2], [64, 3, 1]],
"fcnet_activation": "tanh",
"post_fcnet_hiddens": [512],
"post_fcnet_activation": "relu",
"post_fcnet_weights_initializer": "orthogonal_",
"post_fcnet_weights_initializer_config": {"gain": 0.01},
},
learner_connector=_make_learner_connector,
)
.reporting(
metrics_num_episodes_for_smoothing=10,
min_sample_timesteps_per_iteration=1000,
)
.evaluation(
evaluation_duration="auto",
evaluation_interval=1,
evaluation_num_env_runners=1,
evaluation_parallel_to_training=True,
evaluation_config={
"explore": False,
},
)
)
tuner = tune.Tuner(
"DQN",
param_space=config,
run_config=tune.RunConfig(
stop=BenchmarkStopper(benchmark_envs=benchmark_envs),
name="benchmark_dqn_atari",
),
)
tuner.fit()
| BenchmarkStopper |
python | PrefectHQ__prefect | src/prefect/server/utilities/messaging/memory.py | {
"start": 6513,
"end": 8143
} | class ____:
_topics: dict[str, "Topic"] = {}
name: str
_subscriptions: list[Subscription]
def __init__(self, name: str) -> None:
self.name = name
self._subscriptions = []
@classmethod
def by_name(cls, name: str) -> "Topic":
try:
return cls._topics[name]
except KeyError:
topic = cls(name)
cls._topics[name] = topic
return topic
@classmethod
def clear_all(cls) -> None:
for topic in cls._topics.values():
topic.clear()
cls._topics = {}
def subscribe(self, **subscription_kwargs: Any) -> Subscription:
subscription = Subscription(self, **subscription_kwargs)
self._subscriptions.append(subscription)
return subscription
def unsubscribe(self, subscription: Subscription) -> None:
self._subscriptions.remove(subscription)
def clear(self) -> None:
for subscription in self._subscriptions:
self.unsubscribe(subscription)
self._subscriptions = []
async def publish(self, message: MemoryMessage) -> None:
for subscription in self._subscriptions:
# Ensure that each subscription gets its own copy of the message
await subscription.deliver(copy.deepcopy(message))
@asynccontextmanager
async def break_topic():
from unittest import mock
publishing_mock = mock.AsyncMock(side_effect=ValueError("oops"))
with mock.patch(
"prefect.server.utilities.messaging.memory.Topic.publish",
publishing_mock,
):
yield
M = TypeVar("M", bound=Message)
| Topic |
python | pytorch__pytorch | torch/_inductor/output_code.py | {
"start": 13070,
"end": 14111
} | class ____:
"""Wrapper class that unwraps constants from a compiled fx graph. This
version of the class only supports directly grabbing the saved constants off of
a CompiledFxGraph.
With freezing, FxGraphCache doesn't store the constants of the input
GraphModule it gets from AOTAutograd. Instead, it saves just the **names**
of those constants, and grabs the constant values directly from the graph module
passed in at runtime.
Thing is, we don't always *have* the graph module available at runtime, hence
the existence of this class and its CompiledFxGraphConstantsWithGm counterpart.
To support freezing, FXGraphCache gets passed a CompiledFxGraphConstantsWithGm during
post compile. Otherwise, CompiledFxGraphConstants supports the basic case of loading
the value of constants directly off of the original saved object.
"""
def unwrap(self, g: CompiledFxGraph) -> dict[str, torch.Tensor]:
assert g.constants is not None
return g.constants
| CompiledFxGraphConstants |
python | django__django | tests/postgres_tests/models.py | {
"start": 4367,
"end": 4957
} | class ____(PostgreSQLModel):
parent = models.ForeignKey(RangesModel, models.SET_NULL, blank=True, null=True)
integer = models.IntegerField(blank=True, null=True)
big_integer = models.BigIntegerField(blank=True, null=True)
float = models.FloatField(blank=True, null=True)
timestamp = models.DateTimeField(blank=True, null=True)
date = models.DateField(blank=True, null=True)
small_integer = models.SmallIntegerField(blank=True, null=True)
decimal_field = models.DecimalField(
max_digits=5, decimal_places=2, blank=True, null=True
)
| RangeLookupsModel |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 687624,
"end": 688122
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of LinkProjectV2ToRepository"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "repository")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
repository = sgqlc.types.Field("Repository", graphql_name="repository")
"""The repository the project is linked to."""
| LinkProjectV2ToRepositoryPayload |
python | django__django | tests/select_related/tests.py | {
"start": 9144,
"end": 11805
} | class ____(SimpleTestCase):
"""
select_related() should thrown an error on fields that do not exist and
non-relational fields.
"""
non_relational_error = (
"Non-relational field given in select_related: '%s'. Choices are: %s"
)
invalid_error = (
"Invalid field name(s) given in select_related: '%s'. Choices are: %s"
)
def test_non_relational_field(self):
with self.assertRaisesMessage(
FieldError, self.non_relational_error % ("name", "genus")
):
list(Species.objects.select_related("name__some_field"))
with self.assertRaisesMessage(
FieldError, self.non_relational_error % ("name", "genus")
):
list(Species.objects.select_related("name"))
with self.assertRaisesMessage(
FieldError, self.non_relational_error % ("name", "(none)")
):
list(Domain.objects.select_related("name"))
def test_non_relational_field_nested(self):
with self.assertRaisesMessage(
FieldError, self.non_relational_error % ("name", "family")
):
list(Species.objects.select_related("genus__name"))
def test_many_to_many_field(self):
with self.assertRaisesMessage(
FieldError, self.invalid_error % ("toppings", "(none)")
):
list(Pizza.objects.select_related("toppings"))
def test_reverse_relational_field(self):
with self.assertRaisesMessage(
FieldError, self.invalid_error % ("child_1", "genus")
):
list(Species.objects.select_related("child_1"))
def test_invalid_field(self):
with self.assertRaisesMessage(
FieldError, self.invalid_error % ("invalid_field", "genus")
):
list(Species.objects.select_related("invalid_field"))
with self.assertRaisesMessage(
FieldError, self.invalid_error % ("related_invalid_field", "family")
):
list(Species.objects.select_related("genus__related_invalid_field"))
with self.assertRaisesMessage(
FieldError, self.invalid_error % ("invalid_field", "(none)")
):
list(Domain.objects.select_related("invalid_field"))
def test_generic_relations(self):
with self.assertRaisesMessage(FieldError, self.invalid_error % ("tags", "")):
list(Bookmark.objects.select_related("tags"))
with self.assertRaisesMessage(
FieldError, self.invalid_error % ("content_object", "content_type")
):
list(TaggedItem.objects.select_related("content_object"))
| SelectRelatedValidationTests |
python | numba__numba | numba/core/errors.py | {
"start": 20561,
"end": 20808
} | class ____(NumbaError):
"""
For wrapping internal error occurred within the compiler
"""
def __init__(self, exception):
super(InternalError, self).__init__(str(exception))
self.old_exception = exception
| InternalError |
python | huggingface__transformers | src/transformers/models/auto/modeling_auto.py | {
"start": 86760,
"end": 86992
} | class ____(_BaseAutoModelClass):
_model_mapping = MODEL_FOR_IMAGE_SEGMENTATION_MAPPING
AutoModelForImageSegmentation = auto_class_update(AutoModelForImageSegmentation, head_doc="image segmentation")
| AutoModelForImageSegmentation |
python | dagster-io__dagster | python_modules/dagster/dagster/components/scaffold/scaffold.py | {
"start": 2678,
"end": 3317
} | class ____(Generic[TModel]):
"""Details about the current scaffolding operation.
This is passed to the :py:class:`Scaffolder` class when scaffolding a target.
"""
# fully qualified class name of the decorated object
type_name: str
# target path for the scaffold request. Typically used to construct absolute paths
target_path: Path
# yaml or python
scaffold_format: ScaffoldFormatOptions
# the root of the dg project
project_root: Optional[Path]
# optional params for scaffolding
params: TModel
# whether to append to an existing file
append: bool = False
@public
| ScaffoldRequest |
python | weaviate__weaviate-python-client | weaviate/exceptions.py | {
"start": 12298,
"end": 12638
} | class ____(WeaviateBaseError):
"""Is raised when a request to Weaviate times out."""
def __init__(self, message: str = "") -> None:
msg = f"""The request to Weaviate timed out while awaiting a response. Try adjusting the timeout config for your client. Details: {message}"""
super().__init__(msg)
| WeaviateTimeoutError |
python | pytorch__pytorch | scripts/release_notes/categorize.py | {
"start": 366,
"end": 7143
} | class ____:
def __init__(self, path, category="Uncategorized", use_classifier: bool = False):
self.cache = get_commit_data_cache()
self.commits = CommitList.from_existing(path)
if use_classifier:
print("Using a classifier to aid with categorization.")
device = "cuda" if torch.cuda.is_available() else "cpu"
classifier_config = CategoryConfig(common.categories)
author_map = get_author_map(
Path("results/classifier"), regen_data=False, assert_stored=True
)
file_map = get_file_map(
Path("results/classifier"), regen_data=False, assert_stored=True
)
self.classifier = CommitClassifier(
XLMR_BASE, author_map, file_map, classifier_config
).to(device)
self.classifier.load_state_dict(
torch.load(Path("results/classifier/commit_classifier.pt"))
)
self.classifier.eval()
else:
self.classifier = None
# Special categories: 'Uncategorized'
# All other categories must be real
self.category = category
def categorize(self):
commits = self.commits.filter(category=self.category)
total_commits = len(self.commits.commits)
already_done = total_commits - len(commits)
i = 0
while i < len(commits):
cur_commit = commits[i]
next_commit = commits[i + 1] if i + 1 < len(commits) else None
jump_to = self.handle_commit(
cur_commit, already_done + i + 1, total_commits, commits
)
# Increment counter
if jump_to is not None:
i = jump_to
elif next_commit is None:
i = len(commits)
else:
i = commits.index(next_commit)
def features(self, commit):
return self.cache.get(commit.commit_hash)
def potential_reverts_of(self, commit, commits):
submodule_update_str = [
"Update TensorPipe submodule",
"Updating submodules",
"Automated submodule update",
]
if any(a in commit.title for a in submodule_update_str):
return []
features = self.features(commit)
if "Reverted" in features.labels:
reasons = {"GithubBot": "Reverted"}
else:
reasons = {}
index = commits.index(commit)
# -8 to remove the (#35011)
cleaned_title = commit.title[:-10]
# NB: the index + 2 is sketch
reasons.update(
{
(index + 2 + delta): cand
for delta, cand in enumerate(commits[index + 1 :])
if cleaned_title in cand.title
and commit.commit_hash != cand.commit_hash
}
)
return reasons
def handle_commit(self, commit, i, total, commits):
potential_reverts = self.potential_reverts_of(commit, commits)
if potential_reverts:
potential_reverts = f"!!!POTENTIAL REVERTS!!!: {potential_reverts}"
else:
potential_reverts = ""
features = self.features(commit)
if self.classifier is not None:
# Some commits don't have authors:
author = features.author if features.author else "Unknown"
files = " ".join(features.files_changed)
classifier_input = CommitClassifierInputs(
title=[features.title], files=[files], author=[author]
)
classifier_category = self.classifier.get_most_likely_category_name(
classifier_input
)[0]
else:
classifier_category = commit.category
breaking_alarm = ""
if "module: bc-breaking" in features.labels:
breaking_alarm += "\n!!!!!! BC BREAKING !!!!!!"
if "module: deprecation" in features.labels:
breaking_alarm += "\n!!!!!! DEPRECATION !!!!!!"
os.system("clear")
view = textwrap.dedent(
f"""\
[{i}/{total}]
================================================================================
{features.title}
{potential_reverts} {breaking_alarm}
{features.body}
Files changed: {features.files_changed}
Labels: {features.labels}
Current category: {commit.category}
Select from: {", ".join(common.categories)}
"""
)
print(view)
cat_choice = None
while cat_choice is None:
print("Enter category: ")
value = input(f"{classifier_category} ").strip()
if len(value) == 0:
# The user just pressed enter and likes the default value
cat_choice = classifier_category
continue
choices = [cat for cat in common.categories if cat.startswith(value)]
if len(choices) != 1:
print(f"Possible matches: {choices}, try again")
continue
cat_choice = choices[0]
print(f"\nSelected: {cat_choice}")
print(f"\nCurrent topic: {commit.topic}")
print(f"""Select from: {", ".join(topics)}""")
topic_choice = None
while topic_choice is None:
value = input("topic> ").strip()
if len(value) == 0:
topic_choice = commit.topic
continue
choices = [cat for cat in topics if cat.startswith(value)]
if len(choices) != 1:
print(f"Possible matches: {choices}, try again")
continue
topic_choice = choices[0]
print(f"\nSelected: {topic_choice}")
self.update_commit(commit, cat_choice, topic_choice)
return None
def update_commit(self, commit, category, topic):
assert category in common.categories
assert topic in topics
commit.category = category
commit.topic = topic
self.commits.write_result()
def main():
parser = argparse.ArgumentParser(description="Tool to help categorize commits")
parser.add_argument(
"--category",
type=str,
default="Uncategorized",
help='Which category to filter by. "Uncategorized", None, or a category name',
)
parser.add_argument(
"--file",
help="The location of the commits CSV",
default="results/commitlist.csv",
)
parser.add_argument(
"--use_classifier",
action="store_true",
help="Whether or not to use a classifier to aid in categorization.",
)
args = parser.parse_args()
categorizer = Categorizer(args.file, args.category, args.use_classifier)
categorizer.categorize()
if __name__ == "__main__":
main()
| Categorizer |
python | pytest-dev__pytest-xdist | testing/test_newhooks.py | {
"start": 2553,
"end": 4463
} | class ____:
@pytest.fixture(autouse=True)
def create_test_file(self, pytester: pytest.Pytester) -> None:
pytester.makepyfile(
"""
import os
def test_a(): pass
def test_b(): os._exit(1)
def test_c(): pass
def test_d(): pass
"""
)
def test_handlecrashitem(self, pytester: pytest.Pytester) -> None:
"""Test pytest_handlecrashitem hook."""
pytester.makeconftest(
"""
test_runs = 0
def pytest_handlecrashitem(crashitem, report, sched):
global test_runs
if test_runs == 0:
sched.mark_test_pending(crashitem)
test_runs = 1
else:
print("HOOK: pytest_handlecrashitem")
"""
)
res = pytester.runpytest("-n2", "-s")
res.stdout.fnmatch_lines_random(["*HOOK: pytest_handlecrashitem"])
res.stdout.fnmatch_lines(["*3 passed*"])
def test_handlecrashitem_one(self, pytester: pytest.Pytester) -> None:
"""Test pytest_handlecrashitem hook with just one test."""
pytester.makeconftest(
"""
test_runs = 0
def pytest_handlecrashitem(crashitem, report, sched):
global test_runs
if test_runs == 0:
sched.mark_test_pending(crashitem)
test_runs = 1
else:
print("HOOK: pytest_handlecrashitem")
"""
)
res = pytester.runpytest("-n1", "-s", "-k", "test_b")
res.stdout.fnmatch_lines_random(["*HOOK: pytest_handlecrashitem"])
res.stdout.fnmatch_lines(
[
"FAILED test_handlecrashitem_one.py::test_b*",
"FAILED test_handlecrashitem_one.py::test_b*",
]
)
| TestCrashItem |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 403130,
"end": 403835
} | class ____(sgqlc.types.Interface):
"""Metadata for an audit entry with action oauth_application.*"""
__schema__ = github_schema
__field_names__ = ("oauth_application_name", "oauth_application_resource_path", "oauth_application_url")
oauth_application_name = sgqlc.types.Field(String, graphql_name="oauthApplicationName")
"""The name of the OAuth application."""
oauth_application_resource_path = sgqlc.types.Field(URI, graphql_name="oauthApplicationResourcePath")
"""The HTTP path for the OAuth application"""
oauth_application_url = sgqlc.types.Field(URI, graphql_name="oauthApplicationUrl")
"""The HTTP URL for the OAuth application"""
| OauthApplicationAuditEntryData |
python | pypa__pip | src/pip/_vendor/rich/align.py | {
"start": 7781,
"end": 10324
} | class ____(JupyterMixin):
"""Vertically aligns a renderable.
Warn:
This class is deprecated and may be removed in a future version. Use Align class with
`vertical="middle"`.
Args:
renderable (RenderableType): A renderable object.
style (StyleType, optional): An optional style to apply to the background. Defaults to None.
"""
def __init__(
self,
renderable: "RenderableType",
style: Optional[StyleType] = None,
) -> None:
self.renderable = renderable
self.style = style
def __repr__(self) -> str:
return f"VerticalCenter({self.renderable!r})"
def __rich_console__(
self, console: "Console", options: "ConsoleOptions"
) -> "RenderResult":
style = console.get_style(self.style) if self.style is not None else None
lines = console.render_lines(
self.renderable, options.update(height=None), pad=False
)
width, _height = Segment.get_shape(lines)
new_line = Segment.line()
height = options.height or options.size.height
top_space = (height - len(lines)) // 2
bottom_space = height - top_space - len(lines)
blank_line = Segment(f"{' ' * width}", style)
def blank_lines(count: int) -> Iterable[Segment]:
for _ in range(count):
yield blank_line
yield new_line
if top_space > 0:
yield from blank_lines(top_space)
for line in lines:
yield from line
yield new_line
if bottom_space > 0:
yield from blank_lines(bottom_space)
def __rich_measure__(
self, console: "Console", options: "ConsoleOptions"
) -> Measurement:
measurement = Measurement.get(console, options, self.renderable)
return measurement
if __name__ == "__main__": # pragma: no cover
from pip._vendor.rich.console import Console, Group
from pip._vendor.rich.highlighter import ReprHighlighter
from pip._vendor.rich.panel import Panel
highlighter = ReprHighlighter()
console = Console()
panel = Panel(
Group(
Align.left(highlighter("align='left'")),
Align.center(highlighter("align='center'")),
Align.right(highlighter("align='right'")),
),
width=60,
style="on dark_blue",
title="Align",
)
console.print(
Align.center(panel, vertical="middle", style="on red", height=console.height)
)
| VerticalCenter |
python | kubernetes-client__python | kubernetes/client/models/v1beta2_device_class.py | {
"start": 383,
"end": 6826
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'api_version': 'str',
'kind': 'str',
'metadata': 'V1ObjectMeta',
'spec': 'V1beta2DeviceClassSpec'
}
attribute_map = {
'api_version': 'apiVersion',
'kind': 'kind',
'metadata': 'metadata',
'spec': 'spec'
}
def __init__(self, api_version=None, kind=None, metadata=None, spec=None, local_vars_configuration=None): # noqa: E501
"""V1beta2DeviceClass - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._api_version = None
self._kind = None
self._metadata = None
self._spec = None
self.discriminator = None
if api_version is not None:
self.api_version = api_version
if kind is not None:
self.kind = kind
if metadata is not None:
self.metadata = metadata
self.spec = spec
@property
def api_version(self):
"""Gets the api_version of this V1beta2DeviceClass. # noqa: E501
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:return: The api_version of this V1beta2DeviceClass. # noqa: E501
:rtype: str
"""
return self._api_version
@api_version.setter
def api_version(self, api_version):
"""Sets the api_version of this V1beta2DeviceClass.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:param api_version: The api_version of this V1beta2DeviceClass. # noqa: E501
:type: str
"""
self._api_version = api_version
@property
def kind(self):
"""Gets the kind of this V1beta2DeviceClass. # noqa: E501
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:return: The kind of this V1beta2DeviceClass. # noqa: E501
:rtype: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""Sets the kind of this V1beta2DeviceClass.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:param kind: The kind of this V1beta2DeviceClass. # noqa: E501
:type: str
"""
self._kind = kind
@property
def metadata(self):
"""Gets the metadata of this V1beta2DeviceClass. # noqa: E501
:return: The metadata of this V1beta2DeviceClass. # noqa: E501
:rtype: V1ObjectMeta
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""Sets the metadata of this V1beta2DeviceClass.
:param metadata: The metadata of this V1beta2DeviceClass. # noqa: E501
:type: V1ObjectMeta
"""
self._metadata = metadata
@property
def spec(self):
"""Gets the spec of this V1beta2DeviceClass. # noqa: E501
:return: The spec of this V1beta2DeviceClass. # noqa: E501
:rtype: V1beta2DeviceClassSpec
"""
return self._spec
@spec.setter
def spec(self, spec):
"""Sets the spec of this V1beta2DeviceClass.
:param spec: The spec of this V1beta2DeviceClass. # noqa: E501
:type: V1beta2DeviceClassSpec
"""
if self.local_vars_configuration.client_side_validation and spec is None: # noqa: E501
raise ValueError("Invalid value for `spec`, must not be `None`") # noqa: E501
self._spec = spec
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1beta2DeviceClass):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1beta2DeviceClass):
return True
return self.to_dict() != other.to_dict()
| V1beta2DeviceClass |
python | sphinx-doc__sphinx | sphinx/transforms/__init__.py | {
"start": 5759,
"end": 6712
} | class ____(SphinxTransform):
"""Several code block related transformations."""
default_priority = 210
def apply(self, **kwargs: Any) -> None:
# move doctest blocks out of blockquotes
for node in self.document.findall(nodes.block_quote):
if all(isinstance(child, nodes.doctest_block) for child in node.children):
node.replace_self(node.children)
# combine successive doctest blocks
# for node in self.document.findall(nodes.doctest_block):
# if node not in node.parent.children:
# continue
# parindex = node.parent.index(node)
# while len(node.parent) > parindex+1 and \
# isinstance(node.parent[parindex+1], nodes.doctest_block):
# node[0] = nodes.Text(node[0] + '\n\n' +
# node.parent[parindex+1][0])
# del node.parent[parindex+1]
| HandleCodeBlocks |
python | Netflix__metaflow | metaflow/user_decorators/common.py | {
"start": 822,
"end": 5362
} | class ____:
def __init__(self):
self.root = _TrieNode(None, None)
self.inited = False
self._value_to_node = {} # type: Dict[type, _TrieNode]
def init(self, initial_nodes: Optional[List[Tuple[str, type]]] = None):
# We need to do this so we can delay import of STEP_DECORATORS
self.inited = True
for classpath_name, value in initial_nodes or []:
self.insert(classpath_name, value)
def insert(self, classpath_name: str, value: type):
node = self.root
components = reversed(classpath_name.split("."))
for c in components:
node = node.children.setdefault(c, _TrieNode(node, c))
node.traverse(value)
node.total_children -= (
1 # We do not count the last node as having itself as a child
)
node.value = value
self._value_to_node[value] = node
def search(self, classpath_name: str) -> Optional[type]:
node = self.root
components = reversed(classpath_name.split("."))
for c in components:
if c not in node.children:
return None
node = node.children[c]
return node.value
def remove(self, classpath_name: str):
components = list(reversed(classpath_name.split(".")))
def _remove(node: _TrieNode, components, depth):
if depth == len(components):
if node.value is not None:
del self._value_to_node[node.value]
node.value = None
return len(node.children) == 0
return False
c = components[depth]
if c not in node.children:
return False
did_delete_child = _remove(node.children[c], components, depth + 1)
if did_delete_child:
node.remove_child(c)
if node.total_children == 1:
# If we have one total child left, we have at least one
# child and that one has an end_value
for child in node.children.values():
assert (
child.end_value
), "Node with one child must have an end_value"
node.end_value = child.end_value
return node.total_children == 0
return False
_remove(self.root, components, 0)
def unique_prefix_value(self, classpath_name: str) -> Optional[type]:
node = self.root
components = reversed(classpath_name.split("."))
for c in components:
if c not in node.children:
return None
node = node.children[c]
# If we reach here, it means the classpath_name is a prefix.
# We check if it has only one path forward (end_value will be non None)
# If value is not None, we also consider this to be a unique "prefix"
# This happens since this trie is also filled with metaflow default decorators
return node.end_value or node.value
def unique_prefix_for_type(self, value: type) -> Optional[str]:
node = self._value_to_node.get(value, None)
if node is None:
return None
components = []
while node:
if node.end_value == value:
components = []
if node.component is not None:
components.append(node.component)
node = node.parent
return ".".join(components)
def get_unique_prefixes(self) -> Dict[str, type]:
"""
Get all unique prefixes in the trie.
Returns
-------
List[str]
A list of unique prefixes.
"""
to_return = {}
def _collect(node, current_prefix):
if node.end_value is not None:
to_return[current_prefix] = node.end_value
# We stop there and don't look further since we found the unique prefix
return
if node.value is not None:
to_return[current_prefix] = node.value
# We continue to look for more unique prefixes
for child_name, child_node in node.children.items():
_collect(
child_node,
f"{current_prefix}.{child_name}" if current_prefix else child_name,
)
_collect(self.root, "")
return {".".join(reversed(k.split("."))): v for k, v in to_return.items()}
| ClassPath_Trie |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/graph_compile.py | {
"start": 20862,
"end": 90895
} | class ____:
"""
A data structure to hold all the information needed to partition the
`joint_hop_gm` and joint graph and the restitch the `new_fw_hop_gm` and
`new_bw_hop_gm` into the bigger `joint_gm`.
"""
# To avoid re-partitioning subgraphs
partitioning_done: bool = False
old_num_fw_outputs: Optional[int] = None
old_num_fw_inputs: Optional[int] = None
new_fw_hop_gm: Optional[torch.fx.GraphModule] = None
new_bw_hop_gm: Optional[torch.fx.GraphModule] = None
new_num_sym_nodes: Optional[int] = None
new_num_saved_nodes: Optional[int] = None
def prepare_for_partitioner(mod, num_primals, num_fw_outputs):
# min-cut partitioner requires the placeholders to have primals and
# tangents string in the node.name. The signature of the joint graph is
# (*primals, *tangents)
# We also have to update the output signature which is right now
# (*grads, *fw_outs) and we have to change to (*fw_outs, *grads) for the
# partitioner to work.
new_graph = torch.fx.Graph()
env = {}
primals_counter = itertools.count(0)
tangents_counter = itertools.count(0)
for idx, node in enumerate(mod.graph.nodes):
if node.op == "placeholder":
if idx < num_primals:
env[node] = new_graph.placeholder(f"primals_{next(primals_counter)}")
else:
env[node] = new_graph.placeholder(f"tangents_{next(tangents_counter)}")
env[node].meta = copy.copy(node.meta)
elif node.op == "output":
# Reverse the (*grads, *fw_outs) to (*fw_outs, *grads)
# The reason for having the reversed signature in the first
# place is to simplify step 3.
old_outputs = node.args[0]
new_outputs = (
*old_outputs[-num_fw_outputs:],
*old_outputs[:-num_fw_outputs],
)
new_outputs = [env[n] if n else None for n in new_outputs]
new_graph.output(tuple(new_outputs))
else:
env[node] = new_graph.node_copy(node, lambda n: env[n])
env[node].meta = copy.copy(node.meta)
new_graph.lint()
out = torch.fx.GraphModule(mod, new_graph)
return out
def run_joint_graph_passes_on_hops(
joint_gm: torch.fx.GraphModule,
joint_inputs: Any,
aot_config: AOTConfig,
) -> torch.fx.GraphModule:
"""
This pass runs the joint graph passes on the HOP graph. In torch.compile, we
typically have many passes which work on the joint graph and then end with a
partitioner.
The partitioner part is quite mechanical to handle. HOP have their own
forward and backward graph. The process can be broken into following steps
1) Get a `joint_hop_gm` from the `fw_hop_gm` and `bw_hop_gm`
2) Run joint graph passes on the `joint_hop_gm` to get `new_fw_hop_gm` and `new_bw_hop_gm`
3) Stitch the `new_fw_hop_gm` and `new_bw_hop_gm` back into the `joint_gm`.
The terminology used in the code is
`joint_graph/joint_gm` : Refers to the main graph. This may contain many HOPs which have their own `hop_graph`
`fw_hop_graph/fw_hop_gm` : Refers to the forward graph associated with a HOP.
`bw_hop_graph/bw_hop_gm` : Refers to the backward graph associated with a HOP.
`joint_hop_graph/joint_hop_gm` : Refers to the subgraph associated with the HOP like invoke_subgraph.
`new_fw_hop_graph/new_fw_hop_gm` : Refers to the forward graph after partitioning is applied to `joint_hop_gm`.
`new_bw_hop_graph/new_bw_hop_gm` : Refers to the backward graph after partitioning is applied to `joint_hop_gm`.
NB: This pass works for invoke_subgraph today because we took extra care in
the Autograd.Dispatch key of invoke_subgraph to vastly simplify Step 1.
"""
from torch._higher_order_ops import invoke_subgraph
def num_outputs(mod):
return len(mod.graph.find_nodes(op="output")[0].args[0])
def num_inputs(mod):
return len(mod.graph.find_nodes(op="placeholder"))
new_hop_graphs: dict[str, InvokeSubgraphHopGraphs] = defaultdict(
lambda: InvokeSubgraphHopGraphs()
)
# Step 1 - Get a `joint_hop_gm` from the `fw_hop_gm` and `bw_hop_gm` This is
# easy to do for `invoke_subgraph` HOP. During the Autograd dispatch key
# tracing, we have put the joint_hop_graph in the backward hop graph itself.
# So to recover the joint_hop_gm, we just have to look at the backward
# HOP graphs.
# So we will merge step 1 and step 2 in this next section
# Save the fw and bwd hop nodes. We will later in-place modify the graph
# using these nodes.
fw_hop_nodes = []
bw_hop_nodes = []
for node in joint_gm.graph.nodes:
if (
node.op == "call_function"
and node.target is invoke_subgraph
and isinstance(node.args[1], str)
):
if node.args[1].startswith("fw"):
fw_hop_nodes.append(node)
elif node.args[1].startswith("bw"):
bw_hop_nodes.append(node)
if not bw_hop_nodes:
return joint_gm
assert len(fw_hop_nodes) == len(bw_hop_nodes)
# Create a bw to hop node mapping. This helps us in identifying the bw and
# fw subgraph pairs without relying on the identifier. This is important
# because we can have different subgraphs for bwd for same subgraph in the
# fwd because of differing strides in the backward.
bw_to_fw_hop_node = dict(zip(list(reversed(bw_hop_nodes)), fw_hop_nodes))
for node in bw_hop_nodes:
identifier = node.args[1].removeprefix("bw")
# If partitioning already done for this identifier, skip. This saves
# redundant joint graph passes for same subgraphs.
if new_hop_graphs[identifier].partitioning_done:
continue
# Collect some information from the forward hop graph
fw_hop_node = bw_to_fw_hop_node[node]
fw_hop_gm = getattr(joint_gm, fw_hop_node.args[0].target)
assert isinstance(fw_hop_gm, torch.fx.GraphModule)
num_fw_inputs = num_inputs(fw_hop_gm)
num_fw_outputs = num_outputs(fw_hop_gm)
new_hop_graphs[identifier].old_num_fw_inputs = num_fw_inputs
new_hop_graphs[identifier].old_num_fw_outputs = num_fw_outputs
# Step 1) - Get the `joint_hop_gm`. As mentioned earlier, the
# backward graph is the joint graph.
joint_hop_gm = getattr(joint_gm, node.args[0].target)
assert isinstance(joint_hop_gm, torch.fx.GraphModule)
# Prepare the graph for the partitioner
joint_hop_gm = prepare_for_partitioner(
joint_hop_gm, num_fw_inputs, num_fw_outputs
)
# TODO: invoke_subgraph should track which of its inputs static indices
# so it can propagate them to the partitioner (and use in cudagraphs)
static_lifetime_input_indices: list[int] = []
# Step 2) and 3) - Run joint graph passes and partitioner
new_fw_hop_gm, new_bw_hop_gm = aot_config.partition_fn(
joint_hop_gm,
[],
num_fwd_outputs=num_fw_outputs,
static_lifetime_input_indices=static_lifetime_input_indices,
)
# Save the new forward and backward graph modules
new_hop_graphs[identifier].new_fw_hop_gm = new_fw_hop_gm
new_hop_graphs[identifier].new_bw_hop_gm = new_bw_hop_gm
# Save the number of symints and saved tensors
new_fw_out_nodes = new_fw_hop_gm.graph.find_nodes(op="output")[0].args[0]
extra_outputs = new_fw_out_nodes[num_fw_outputs:]
symint_outputs = [n for n in extra_outputs if is_sym_node(n)]
new_hop_graphs[identifier].new_num_sym_nodes = len(symint_outputs)
new_hop_graphs[identifier].new_num_saved_nodes = len(extra_outputs) - len(
symint_outputs
)
new_hop_graphs[identifier].partitioning_done = True
# Step 3) Restitch the new fw and bw graphs back into the main graph.
#
# This is a very mechanical process. There are a quite a few pieces that we
# need to connect together to make it work. Lets try to understand the
# problem statement first.
#
# For the forward graph, the signature of the old_fw_hop_gm is
# inputs - (*primals)
# outputs - (*fw_outs)
# Now the signature of the new_fw_hop_gm is
# inputs - (*primals) -- This is same
# outputs - (*fw_outs, *saved_tensors) - This is different
# At a high level, this is an easy transformation, in the new graph we just
# have to replace the old_fw_hop_gm with the new_fw_hop_gm. Everything else
# falls into place, because the input signature (i.e. args) is same. And
# even though output signature is different, fw_outs are still at the same
# indexes as before. So the forward of the `joint_gm` works nicely.
#
# Now, lets look at the backward hop graph. Old signature
# inputs - (*primals, *tangents)
# outputs - (*grad_outs, *fw_outs)
# New signature
# inputs - (*saved_tensors, *tangents) -- Different
# outputs - (*grad_outs) -- Different
# Here both input and output signature change. The output signature handling
# is quite easy because the grads_out are sitting at the right place, so we
# dont have to do anything.
#
# For the input signature, we have to collect the saved tensors from the
# corresponding forward graph output. We collect all saved_tensors when we
# see the forward graph, and save it into a map and then later use it during
# the backward.
# The stack of fw_nodes for invoke_subgraph HOP. There is an implicit
# assumption about the graph structure, i.e., if we have hop1, hop2, hop3,
# ... in the forward part of the joint graph, we will have .., hop3, hop2,
# hop1 order for the backward. This structure allows us to just use a stack
# to collect all the information that we need to pass from the forward hop
# node to the corresponding backward node.
already_added_new_hop_mods = set()
def add_new_hop_gm(new_subgraph_mod, name):
new_subgraph_attr_name = f"partitioned_{name}"
if new_subgraph_attr_name in already_added_new_hop_mods:
return new_subgraph_attr_name
joint_gm.register_module(new_subgraph_attr_name, new_subgraph_mod)
already_added_new_hop_mods.add(new_subgraph_attr_name)
return new_subgraph_attr_name
def propagate_meta_info(new_hop_gm, new_call_function_node, old_call_function_node):
# Copy all the fields from the old call_function node. And then override
# the `val` meta field with the outputs of new_hop_gm.
new_call_function_node.meta = copy.copy(old_call_function_node.meta)
output = new_hop_gm.graph.find_nodes(op="output")[0]
out_example_vals = [n.meta["val"] if n else None for n in output.args[0]]
new_call_function_node.meta["val"] = tuple(out_example_vals)
for bw_node in reversed(bw_hop_nodes):
identifier = bw_node.args[1].removeprefix("bw")
# Make changes to the corresponding fw and bw node pair simultaneously.
# The removes the need of any bookkeeping.
# Fw node changes
# Insert the new_fw_hop_gm. This is straightforward. Get the
# new_fw_hop_gm, insert the hop_gm as a get_attr fw_node, and then
# add a call_function fw_node. Additionally, also use getitem
# call_functions to collect the saved_tensor nodes
fw_node = bw_to_fw_hop_node[bw_node]
new_fw_hop_gm = new_hop_graphs[identifier].new_fw_hop_gm
assert new_fw_hop_gm is not None
old_num_fw_outputs = new_hop_graphs[identifier].old_num_fw_outputs
new_num_sym_nodes = new_hop_graphs[identifier].new_num_sym_nodes
new_num_saved_nodes = new_hop_graphs[identifier].new_num_saved_nodes
assert old_num_fw_outputs is not None
assert new_num_sym_nodes is not None
assert new_num_saved_nodes is not None
total_outputs = old_num_fw_outputs + new_num_saved_nodes + new_num_sym_nodes
extra_fw_outputs = []
# Insert the new_fw_hop_gm into the joint_gm
with joint_gm.graph.inserting_after(fw_node):
new_fw_mod_attr_name = add_new_hop_gm(new_fw_hop_gm, f"fw{identifier}")
new_fw_mod_attr = joint_gm.graph.get_attr(new_fw_mod_attr_name)
new_fw_mod_attr.meta = copy.copy(fw_node.args[0].meta)
# new_hop_fw_gm output signature is (*fw_outs, *saved_tensors)
with joint_gm.graph.inserting_after(new_fw_mod_attr):
new_fw_node = joint_gm.graph.call_function(
the_function=invoke_subgraph,
args=(
new_fw_mod_attr,
new_fw_mod_attr_name,
*fw_node.args[2:],
),
)
propagate_meta_info(new_fw_hop_gm, new_fw_node, fw_node)
# old_num_fw_outputs = (*fw_outs)
# new_num_fw_outputs = (*fw_outs, *saved_tensors, *sym_nodes)
with joint_gm.graph.inserting_after(new_fw_node):
for fw_out_idx in range(old_num_fw_outputs, total_outputs):
saved_tensor_node = joint_gm.graph.call_function(
the_function=operator.getitem, args=(new_fw_node, fw_out_idx)
)
saved_tensor_node.meta = copy.copy(new_fw_node.meta)
saved_tensor_node.meta["val"] = new_fw_node.meta["val"][fw_out_idx]
extra_fw_outputs.append(saved_tensor_node)
fw_node.replace_all_uses_with(new_fw_node)
joint_gm.graph.erase_node(fw_node)
# Bw node changes
# Prepare the operands for the bwd graph
# Old bw graph signature : (*primals, *tangents)
# New signature will be : (*sym_nodes, *saved_tensors, *tangents)
# We have already collected the saved_tensors in the forward hop processing.
# extra_fw_outputs are in the order (*saved_nodes, *sym_nodes).
# Partitioner has this quirk where the backward wants sym_nodes
# first. So extract the sym and saved nodes.
new_bw_hop_gm = new_hop_graphs[identifier].new_bw_hop_gm
assert new_bw_hop_gm is not None
saved_tensor_nodes = extra_fw_outputs[:new_num_saved_nodes]
sym_nodes = extra_fw_outputs[new_num_saved_nodes:]
num_primals = new_hop_graphs[identifier].old_num_fw_inputs
assert num_primals is not None
tangents = list(bw_node.args[2 + num_primals :])
operands = sym_nodes + saved_tensor_nodes + tangents
# Insert the new_bw_hop_gm into the joint_gm
with joint_gm.graph.inserting_after(bw_node):
new_bw_mod_attr_name = add_new_hop_gm(new_bw_hop_gm, bw_node.args[1])
new_bw_mod_attr = joint_gm.graph.get_attr(new_bw_mod_attr_name)
new_bw_mod_attr.meta = copy.copy(bw_node.args[0].meta)
with joint_gm.graph.inserting_after(new_bw_mod_attr):
new_bw_node = joint_gm.graph.call_function(
the_function=invoke_subgraph,
args=(
new_bw_mod_attr,
new_bw_mod_attr_name,
*operands,
),
)
propagate_meta_info(new_bw_hop_gm, new_bw_node, bw_node)
# Since the partitioner is run after the graph passes, we have lost
# the eager information and cannot faithfully extract the eager
# inputs for the new partitioned backward graph. For the forward
# graph, it was fine because the input signature remains same.
new_bw_node.meta.pop("eager_input_vals", None)
bw_node.replace_all_uses_with(new_bw_node)
joint_gm.graph.erase_node(bw_node)
joint_gm.graph.eliminate_dead_code()
joint_gm.graph.lint()
joint_gm.recompile()
return joint_gm
def maybe_log_graph(
gm,
graph_name,
aot_config,
structured_log_prefix_fn,
out_structured_logs: Optional[list[str]] = None,
):
if not aot_config.enable_log:
return
aot_graphs_log.debug(
"%s",
lazy_format_graph_code(
f"{graph_name}",
gm,
aot_config.aot_id,
include_stride=True,
include_device=True,
colored=True,
),
)
def gm_str_fn() -> str:
return gm.print_readable(
print_output=False,
include_stride=True,
include_device=True,
expanded_def=True,
)
if out_structured_logs is not None:
out_structured_logs.append(f"{structured_log_prefix_fn()}:{gm_str_fn()}")
else:
trace_structured(
f"{structured_log_prefix_fn()}",
payload_fn=lambda: gm_str_fn(),
)
def create_wrap_fn(fn, args):
from torch.fx.experimental.proxy_tensor import maybe_enable_thunkify
from .functional_utils import from_fun, has_data_mutation, to_fun
def assert_no_mutation(t):
assert not has_data_mutation(t), (
"Saved tensors hooks with inputs mutations are not allowed"
)
@simple_wraps(fn)
def _wrapper(*args):
with maybe_enable_thunkify():
disable_above = torch._C._ExcludeDispatchKeyGuard(
torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
)
with disable_above:
f_args = pytree.tree_map(to_fun, args)
f_outs = fn(*f_args)
pytree.tree_map(assert_no_mutation, f_args)
return pytree.tree_map(from_fun, f_outs)
return _wrapper, args
def prepare_hook_gm(aot_config, fn, args):
from torch._functorch._aot_autograd.graph_capture import _create_graph
fn, args = create_wrap_fn(fn, args)
gm = _create_graph(fn, args, aot_config=aot_config)
return gm
# Inline Autograd saved_tensors_hooks into epilogue of forward graph
# and prologue of backward graph.
# This changes forward graph outputs and inputs.
# Pack hook can return tensors, sym scalars, constants.
# All tensors to save for backward will be grouped together at front.
# Sym scalars grouped on another end. Constants are inlined in the graph.
def maybe_inline_graph_saved_tensors_hooks(
fw_module, # torch.fx.GraphModule
bw_module, # torch.fx.GraphModule
num_inner_fwd_outputs,
inner_meta,
aot_config,
static_input_indices,
):
if torch._dynamo.compiled_autograd.in_compiled_autograd_region:
return
get_hooks = torch._functorch._aot_autograd.utils.top_saved_tensors_hooks
are_inline_hooks = (
torch._functorch._aot_autograd.utils.saved_tensors_hooks_are_inlineable
)
hooks = get_hooks()
if not are_inline_hooks(hooks):
return
pack_hook_gm, unpack_hook_gm = hooks
structured_logs: list[str] = []
maybe_log_graph(
fw_module,
"Forward graph pre saved_tensors_hooks inlining",
aot_config,
lambda: "aot_forward_graph_pre_saved_tensors_hooks",
structured_logs,
)
maybe_log_graph(
bw_module,
"Backward graph pre saved_tensors_hooks inlining",
aot_config,
lambda: "aot_backward_graph_pre_saved_tensors_hooks",
structured_logs,
)
fw_g = fw_module.graph
bw_g = bw_module.graph
fw_g_names = {node.name for node in fw_g.nodes}
bw_g_names = {node.name for node in bw_g.nodes}
def _gen_unused_name(candidate: str):
c = candidate
i = 0
while c in fw_g_names or c in bw_g_names:
c = f"{candidate}_{i}"
i = i + 1
return c
bw_g_inputs = bw_g.find_nodes(op="placeholder")
fw_out_n = fw_g.output_node()
fw_outs = fw_out_n.args[0] # type: ignore[var-annotated]
fw_outs_inner_set = set(fw_outs[:num_inner_fwd_outputs])
fw_outs_saved_for_bw = fw_outs[num_inner_fwd_outputs:]
fw_outs_packed_tensors = [] # type: ignore[var-annotated]
fw_outs_packed_syms = [] # type: ignore[var-annotated]
# The main use case for saved_tensors_hooks is activation quantization,
# for memory usage optimization.
# Desired behavior is to quantize saved activations to free the original saved tensor.
# Saved nodes may include forward inputs, outputs, parameters.
# They may be held by something else and will not be deallocated after quantization.
# Donated buffers are intermediates in the graph invisible for the user,
# this guarantees that they can be deallocated.
# Using this as a default behavior to select saved nodes to apply hooks.
# There is also a config to apply hooks for all saved nodes without any filtering.
# The plan is to propagate meta about the source of the saved node to the user hook function.
mode = torch._functorch.config.saved_tensors_hooks_filtering_mode
allow_set = None
exclude_set = None
if mode == "donated":
# collect_bw_donated_buffer_idxs requires inner_meta to have num_symints_saved_for_bw
inner_meta.num_symints_saved_for_bw = len(
[n for n in fw_outs_saved_for_bw if is_sym_node(n)]
)
bw_donated_idxs = collect_bw_donated_buffer_idxs(
fw_module,
bw_module,
inner_meta,
)
fw_donated_idxs = [
i - inner_meta.num_symints_saved_for_bw for i in bw_donated_idxs
]
allow_set = {fw_outs_saved_for_bw[i].name for i in fw_donated_idxs}
elif mode == "no_static":
fw_g_inputs = fw_g.find_nodes(op="placeholder")
exclude_set = {fw_g_inputs[i].name for i in static_input_indices}
if (allow_set is not None) and (not allow_set):
# This means we have empty whitelist,
# No donated (intermediate) saved.
# Do not do anything in this case
return
if aot_config.enable_log:
structured_logs.append(f"fw_outs_saved_for_bw:{fw_outs_saved_for_bw}")
structured_logs.append(f"mode:{mode}")
structured_logs.append(f"allow_set:{allow_set}")
structured_logs.append(f"exclude_set:{exclude_set}")
for saved in fw_outs_saved_for_bw:
if ((allow_set is not None) and (saved.name not in allow_set)) or (
(exclude_set is not None) and (saved.name in exclude_set)
):
if isinstance(saved.meta["val"], torch.Tensor):
fw_outs_packed_tensors.append(saved)
continue
val = saved.meta["val"]
if not isinstance(val, torch.Tensor):
continue
def _get_extra_info() -> dict[str, Any]:
return {"_fw_graph": fw_g, "_bw_graph": bw_g, "_node": saved}
with _saved_tensor_hook_context(_get_extra_info()):
pack_out_val = pack_hook_gm(val)
requires_sc_handling = any(
is_traceable_wrapper_subclass(x) for x in pytree.tree_leaves(pack_out_val)
)
if requires_sc_handling:
raise NotImplementedError(
"Tensor subclasses in GraphModule saved tensors hooks are not supported"
"You can workaround it by manually returning subclass's inner tensors"
" in the pack hook, and reconstructing the subclass in the unpack hook"
)
with _saved_tensor_hook_context(_get_extra_info()):
pack_gm = prepare_hook_gm(aot_config, pack_hook_gm, (val,))
pack_g = pack_gm.graph
maybe_log_graph(
pack_gm,
f"saved_tensors_pack_hook {saved.name}",
aot_config,
lambda: f"aot_saved_tensors_hooks_pack {saved.name}",
structured_logs,
)
pack_out_val = pack_gm(val)
# Install pack hook graph as eiplogue of fw_module.
# Saved tensor output becomes input of pack hook graph.
# Replace saved tensor output with pack hook graph output.
# Outputs symbolic scalars, tensors are accumulated separately.
# Then in forward outputs and backward inputs installed in order
# sym_scalars, packed_saved_tensors.
# Keeping all tensors together allows to preserve
# the same identification at runtime,
# updating only number of saved sym_scalars and tensors.
pack_g_inputs = pack_g.find_nodes(op="placeholder")
assert len(pack_g_inputs) == 1
env = {pack_g_inputs[0]: saved}
fw_pack_out_args = None
with fw_g.inserting_before(fw_out_n):
for node in pack_g.nodes:
if node.op == "placeholder":
continue
new_n = fw_g.node_copy(node, lambda n: env[n])
fw_g_names.add(new_n.name)
env[node] = new_n
# Output node is temporarily copied to have remapped arguments.
# Removed in the end.
if node.op == "output":
fw_pack_out_args = new_n.args[0]
fw_g.erase_node(new_n)
env.clear()
assert fw_pack_out_args
fw_outs_bw_ins_node_names = []
for out_idx, _n in enumerate(pytree.tree_leaves(fw_pack_out_args)):
if not isinstance(_n, torch.fx.Node):
fw_outs_bw_ins_node_names.append("")
continue
# This happens when hook is noop and it is either user input or user output.
# Do not do anything with this node.
if _n.op == "placeholder" or _n in fw_outs_inner_set:
# This means the hook returned input primals unchanged
# Do not rename in this case.
n = _n
new_node_name = _n.name
fw_outs_bw_ins_node_names.append(new_node_name)
else:
# We can not specify desired name in node_copy.
# Copying node manually to set specific name,
# to have matching fw_outs, bw_inputs names.
new_node_name = _gen_unused_name(f"{saved.name}_hook_{out_idx}")
with fw_g.inserting_before(_n):
n = fw_g.create_node(
_n.op,
_n.target,
_n.args,
_n.kwargs,
name=new_node_name,
)
assert n.name == new_node_name
fw_outs_bw_ins_node_names.append(new_node_name)
n.meta = copy.copy(_n.meta)
_n.replace_all_uses_with(n)
fw_g.erase_node(_n)
if isinstance(n.meta["val"], torch.Tensor):
fw_outs_packed_tensors.append(n)
elif is_sym_node(n):
fw_outs_packed_syms.append(n)
# Install unpack hook graph as a prologue of backward graph
# Saved tensors inputs are replaced with packed tensors and packed sym scalars.
# The saved tensors inputs usages in the graph are replaced with unpack hook graph outputs.
with _saved_tensor_hook_context(_get_extra_info()):
unpack_gm = prepare_hook_gm(aot_config, unpack_hook_gm, (pack_out_val,))
unpack_g = unpack_gm.graph
maybe_log_graph(
unpack_gm,
f"saved_tensors_unpack_hook {saved.name}",
aot_config,
lambda: f"aot_saved_tensors_hooks_unpack {saved.name}",
structured_logs,
)
def find_saved_in_bw_inputs(bw_inputs):
for n in bw_inputs:
if n.name == saved.name:
return n
bw_g_input = find_saved_in_bw_inputs(bw_g_inputs)
assert bw_g_input
original_bw_g_input_users = list(bw_g_input.users.keys())
bw_g_input_used_directly = False
# Replace backward graph saved tensor input with copy of pack graph outputs
# All non-Tensor, non-symscalars outputs are constanted.
unpack_g_inputs = unpack_g.find_nodes(op="placeholder")
env = {}
for out_idx, (unp_in_n, out_n, val) in enumerate(
zip(
unpack_g_inputs,
pytree.tree_leaves(fw_pack_out_args),
pytree.tree_leaves(pack_out_val),
)
):
is_sym = isinstance(val, py_sym_types)
if isinstance(val, torch.Tensor) or is_sym:
# We want forward_outputs names to match backward_inputs,
# Potentially backward may already have "{saved.name}_hook_{idx}",
# In this case fx.Graph will add suffix.
new_node_name = fw_outs_bw_ins_node_names[out_idx]
if bw_g_input.name == new_node_name:
env[unp_in_n] = bw_g_input
bw_g_input_used_directly = True
else:
# Backward calling convention: ctx_symints,ctx_saved_tensors
# Inserting packed sym scalars before first saved tensor input.
# Inserting packed tensors before last saved tensor input.
# Saved tensor inputs between them will be removed.
with (
bw_g.inserting_before(bw_g_inputs[0])
if is_sym
else bw_g.inserting_before(bw_g_input)
):
new_n = bw_g.placeholder(new_node_name)
assert new_n.name == new_node_name
new_n.meta = copy.copy(out_n.meta)
env[unp_in_n] = new_n
else:
# Inline values of non-Tensor, non-SymScalars
env[unp_in_n] = val
# Inserting unpack hook after placeholders.
bw_unpack_out_n = None
with bw_g.inserting_before(bw_g_inputs[-1].next):
for node in unpack_g.nodes:
if node.op == "placeholder":
continue
new_n = bw_g.node_copy(node, lambda n: env[n])
bw_g_names.add(new_n.name)
env[node] = new_n
# Temporary insert output, to have remapped by node_copy args.
# Removed in the end.
if node.op == "output":
bw_unpack_out_n = new_n
assert bw_unpack_out_n
_leaves = pytree.tree_leaves(bw_unpack_out_n.args)
assert len(_leaves) == 1
unpack_saved_tensor_n = _leaves[0]
if not bw_g_input_used_directly:
bw_g_input.replace_all_uses_with(unpack_saved_tensor_n)
bw_g.erase_node(bw_g_input)
else:
# Keep usages of bw_g_input in inserted unpacked hook graph.
# Replace other usages of bw_g_input with unpack_saved_tensor_n.
for use_node in original_bw_g_input_users:
use_node._replace_input_with(bw_g_input, unpack_saved_tensor_n)
bw_g.erase_node(bw_unpack_out_n)
# Changing forward graph outputs,
# Inserting packed_tensors and packed_syms on the place of saved tensors.
# Packed sym_scalars are together with saved symints
symint_outs_saved_for_bw = [n for n in fw_outs_saved_for_bw if is_sym_node(n)]
fw_new_outs = pytree.tree_leaves(
(
fw_outs[:num_inner_fwd_outputs],
fw_outs_packed_tensors,
fw_outs_packed_syms,
symint_outs_saved_for_bw,
)
)
fw_out_n.args = (tuple(fw_new_outs),)
# Assert that saved tensors and symints in forward outputs are aligned with backward inputs
_fw_n = num_inner_fwd_outputs
_fw_num_t = len(fw_outs_packed_tensors)
_fw_num_s = len(fw_outs_packed_syms) + len(symint_outs_saved_for_bw)
fw_outs_saved_tensors = fw_new_outs[_fw_n : _fw_n + _fw_num_t]
fw_outs_saved_syms = fw_new_outs[_fw_n + _fw_num_t :]
bw_new_ins = list(bw_g.find_nodes(op="placeholder"))
bw_ins_saved_syms = bw_new_ins[:_fw_num_s]
bw_ins_saved_tensors = bw_new_ins[_fw_num_s : _fw_num_s + _fw_num_t]
fw_t_names = [n.name for n in fw_outs_saved_tensors]
bw_t_names = [n.name for n in bw_ins_saved_tensors]
fw_s_names = [n.name for n in fw_outs_saved_syms]
bw_s_names = [n.name for n in bw_ins_saved_syms]
def _log_structured_logs():
if not aot_config.enable_log:
return
trace_structured(
"artifact",
metadata_fn=lambda: {
"name": "aot_saved_tensors_hooks_graphs",
"encoding": "string",
},
payload_fn=lambda: "\n".join(structured_logs),
)
if aot_config.enable_log:
structured_logs.append(
f"fw_outs[:num_inner_fwd_outputs]:{fw_outs[:num_inner_fwd_outputs]}"
)
structured_logs.append(f"fw_outs_packed_tensors:{fw_outs_packed_tensors}")
structured_logs.append(f"fw_t_names:{fw_t_names}")
structured_logs.append(f"bw_t_names:{bw_t_names}")
structured_logs.append(f"fw_s_names:{fw_s_names}")
structured_logs.append(f"bw_s_names:{bw_s_names}")
structured_logs.append(f"\nfw_g_pre_assert:{fw_g}")
structured_logs.append(f"\nbw_g_pre_assert:{bw_g}")
maybe_log_graph(
fw_module,
"Forward graph after transform pre-assert",
aot_config,
lambda: "aot_forward_graph_pre_assert_saved_tensors_hooks",
structured_logs,
)
maybe_log_graph(
bw_module,
"Backward graph after transform pre-assert",
aot_config,
lambda: "aot_backward_graph_pre_assert_saved_tensors_hooks",
structured_logs,
)
_log_structured_logs()
assert fw_t_names == bw_t_names
assert fw_s_names == bw_s_names
fw_g.lint()
bw_g.lint()
fw_module.recompile()
bw_module.recompile()
def _log_joint_graph(
fx_g: torch.fx.GraphModule,
aot_config: AOTConfig,
) -> Optional[str]:
"""
Log the joint graph to the structured logger.
Return a str representation of the graph.
"""
joint_graph_str = None
if aot_config.enable_log:
aot_joint_log.info(
"%s",
lazy_format_graph_code(
"Joint graph",
fx_g,
aot_config.aot_id,
include_stride=True,
include_device=True,
colored=True,
),
)
joint_graph_str = fx_g.print_readable(
print_output=False,
include_stride=True,
include_device=True,
expanded_def=True,
)
trace_structured(
"aot_joint_graph",
payload_fn=lambda: joint_graph_str,
)
return joint_graph_str
def _log_fw_bw_graphs(
fw_module: torch.fx.GraphModule,
bw_module: torch.fx.GraphModule,
maybe_subclass_meta: Optional[SubclassMeta],
fw_metadata: ViewAndMutationMeta,
aot_config: AOTConfig,
) -> tuple[Optional[str], Optional[str]]:
"""
Log the fw and bw graphs to the structured logger.
Return str representations of the graphs.
"""
fw_module_str = None
bw_module_str = None
if aot_config.enable_log:
trace_structured(
"artifact",
metadata_fn=lambda: {
"name": "torch._functorch.config",
"encoding": "string",
},
payload_fn=lambda: torch._functorch.config.get_serializable_config_copy(),
)
aot_graphs_log.info(
"aot_config id: %s, fw_metadata=%s, inner_meta=%s",
str(aot_config.aot_id),
str(fw_metadata),
str(_get_inner_meta(maybe_subclass_meta, fw_metadata)),
)
aot_graphs_log.info(
"%s",
lazy_format_graph_code(
"Forward graph",
fw_module,
aot_config.aot_id,
include_stride=True,
include_device=True,
colored=True,
),
)
aot_graphs_log.info(
"%s",
lazy_format_graph_code(
"Backward graph",
bw_module,
aot_config.aot_id,
include_stride=True,
include_device=True,
colored=True,
),
)
fw_module_str = fw_module.print_readable(
print_output=False,
include_stride=True,
include_device=True,
expanded_def=True,
)
bw_module_str = bw_module.print_readable(
print_output=False,
include_stride=True,
include_device=True,
expanded_def=True,
)
trace_structured(
"artifact",
metadata_fn=lambda: {
"name": "aot_forward_graph_fw_metadata",
"encoding": "string",
},
payload_fn=lambda: dataclass_repr(fw_metadata),
)
if maybe_subclass_meta is not None:
trace_structured(
"artifact",
metadata_fn=lambda: {
"name": "aot_forward_graph_fw_subclass_metadata",
"encoding": "string",
},
payload_fn=lambda: dataclass_repr(maybe_subclass_meta),
)
trace_structured(
"aot_forward_graph",
payload_fn=lambda: fw_module_str,
)
trace_structured(
"aot_backward_graph",
payload_fn=lambda: bw_module_str,
)
return fw_module_str, bw_module_str
def _aot_stage2a_partition(
fx_g: torch.fx.GraphModule,
joint_inputs: Union[list[Any], tuple[list[Any], list[Any]]],
maybe_subclass_meta: Optional[SubclassMeta],
fw_metadata: ViewAndMutationMeta,
aot_config: AOTConfig,
) -> tuple[torch.fx.GraphModule, torch.fx.GraphModule, int, int, list[int], list[Any]]:
"""
Partition the joint graph into a forward graph and a backward graph. Returns:
- the forward and backward graphs
- the number of forward outputs and the number of symints saved for backward
- indices of inputs to detach
- adjusted inputs to forward
"""
disable_amp = torch._C._is_any_autocast_enabled()
inner_meta = _get_inner_meta(maybe_subclass_meta, fw_metadata)
with torch.no_grad():
context = torch._C._DisableAutocast if disable_amp else nullcontext
with context(), track_graph_compiling(aot_config, "joint"):
# See Note: [Partitioner handling for Subclasses, Part 1]
# See Note: [Recomputing subclass mutation handling]
mutated_inp_runtime_indices = (
compute_inner_mutated_inp_indices_from_subclass_meta(
fw_metadata, inner_meta
)
)
num_tokens = len(fw_metadata.tokens)
num_mutated_inp_runtime_indices = len(mutated_inp_runtime_indices)
num_inner_fwd_outputs = (
num_mutated_inp_runtime_indices
+ inner_meta.num_outputs
+ inner_meta.num_intermediate_bases
+ inner_meta.num_outputs_rng_offset
+ num_tokens # See Note [Side-Effectful Tokens in AOTAutograd]
)
fx_g = run_joint_graph_passes_on_hops(fx_g, joint_inputs, aot_config)
# apply joint_gm callback here
if callable(torch._functorch.config.joint_custom_pass):
# pyrefly: ignore [bad-assignment]
fx_g = torch._functorch.config.joint_custom_pass(fx_g, joint_inputs)
static_lifetime_input_indices = fw_metadata.static_input_indices
fw_module, bw_module = aot_config.partition_fn(
fx_g,
joint_inputs,
num_fwd_outputs=num_inner_fwd_outputs,
static_lifetime_input_indices=static_lifetime_input_indices,
)
rng_states = [
n
for n in fw_module.graph.find_nodes(op="placeholder")
if "fwd_rng_state" in n.name
]
fw_metadata.num_graphsafe_rng_states = len(rng_states)
if rng_states:
fw_metadata.graphsafe_rng_state_index = (
rng_states[0].meta["val"].device.index
)
# See Note [Side-Effectful Tokens in AOTAutograd]
if config.unlift_effect_tokens and (
num_tokens > 0 or fw_metadata.num_backward_tokens > 0
):
unlift_tokens(fw_module, fw_metadata, aot_config, bw_module)
num_inner_fwd_outputs -= num_tokens
joint_inputs = (
joint_inputs[0][num_tokens:],
joint_inputs[1],
)
maybe_inline_graph_saved_tensors_hooks(
fw_module,
bw_module,
num_inner_fwd_outputs,
inner_meta,
aot_config,
fw_metadata.static_input_indices,
)
static_lifetime_input_indices = fw_metadata.static_input_indices
fw_outs = next(iter(fw_module.graph.find_nodes(op="output"))).args[0]
# we only need to bookkeep the symints that are saved for bw, not any symints
# the user forward might have returned in its own output
fw_outs_saved_for_bw = fw_outs[num_inner_fwd_outputs:]
num_fw_outs_saved_for_bw = len(fw_outs_saved_for_bw)
symint_outs_saved_for_bw = []
for idx, node in enumerate(fw_outs_saved_for_bw):
if is_sym_node(node):
symint_outs_saved_for_bw.append(node)
elif (
isinstance(node, torch.fx.Node)
and "val" in getattr(node, "meta", {})
and isinstance(node.meta["val"], FakeTensor)
):
# record dynamic tensor activations
dynamic_dims: set[int] = {
dim
for dim, size in enumerate(node.meta["val"].shape)
if not isinstance(size, int)
}
if dynamic_dims:
fw_metadata.dynamic_saved_tensors_idxs[idx] = dynamic_dims
num_symints_saved_for_bw = len(symint_outs_saved_for_bw)
fw_metadata.num_symints_saved_for_bw = num_symints_saved_for_bw
inner_meta.num_symints_saved_for_bw = num_symints_saved_for_bw
if torch._functorch.config.donated_buffer:
fw_metadata.bw_donated_idxs = collect_bw_donated_buffer_idxs(
fw_module,
bw_module,
inner_meta,
)
inner_meta.bw_donated_idxs = fw_metadata.bw_donated_idxs
# Note [Detaching inputs that never need gradients]
# See https://github.com/pytorch/pytorch/issues/97745
# Suppose we have a function like this that we want to compile:
#
# def f(x, y):
# return torch.mul(x, y.detach())
#
# What gradients should we compute for x and y?
# By default, AOTAutograd will compute a gradient for **every** input that requires gradients,
# and so we'll compute:
# x_grad_input = y
# y_grad_input = None
# Does this preserve the semantics of eager mode?
# Unfortunately, no.
# Doing the above will cause autograd to **continue** to backprop the autograd tape
# that was generated from constructing y.
#
# This is **different** from what would have happened in eager mode.
# In eager mode, if we backprop through the output of this function, autograd will only traverse
# the bit of the autograd tape corresponding to "x".
# In particular, if a user had previously backpropped through y's autograd tape,
# And then they try to backprop through the output of the above function,
# then we'll hit the dreaded "Trying to backward through the graph a second time" error.
#
# You might think: If autograd sees that a gradient is None, shouldn't it stop early,
# instead of continuing the backprop through the ancestors of that node in the graph?
#
# Autograd has two passes:
# (1) a first pass that traverses the autograd graph and figures out which nodes need to be executed
# (2) a second pass that actually goes ahead and executes each node when it becomes ready,
# propagating gradients
# By the time we're executing a node and we see that it produces a None, the set of nodes to execute
# is already locked-in.
#
# The fix: instead, we can recognize statically that the graph we're compiling will never contribute
# gradients to y, and prevent autograd from trying to traverse y's autograd tape at all.
# We can do this by manually detach'ing y before sending it through the `CompiledFunction`.
#
# Note that this solution is not bulletproof.
# It's possible to construct a case where eager may or may not have have tried to autograd through y,
# depending on the actual grad_outputs that were passed in during the backward.
# There is no easy fix for this: the simplest fix would be to run with `retain_graph=True`,
# allowing autograd to reuse the graph.
#
# An example of this case is:
# def f(x):
# return x.detach() * 2, x * 3
# If we were to only backprop through outs[0], in eager, we would stop
# If we backward only on the first output, we shouldn't send a grad through x.
# But the custom autograd function doesn't know that: it will materialize zero grads for x * 3
# and we will end up with a zero grad at x.
# If we later backprop through the second output, this will also require backprop'ing through x.
# Meaning we'll need to use `retain_graph=True` to be able to backprop through x the second time.
_indices_of_inps_to_detach: list[int] = []
# reversed() since we expect output at end of graph
bw_output = next(reversed(bw_module.graph.find_nodes(op="output")))
bw_outs: Sequence[torch.fx.Node] = bw_output.args[0] # type: ignore[assignment]
# TODO: we should apply the below "detach inputs if their gradients are statically known to be None"
# optimization even if we have subclass inputs/outputs (we do not handle this today).
# Computing which our our inputs get None gradients is a bit more complicated,
# if any of our inputs are subclasses. Why?
# (a) we need to make sure that we call .detach() on the input subclasses, since autograd sees subclasses.
# (b) The grad_outputs that we AOT computed in our backward graph are the desugared tensor tensors,
# so we need to figure out which subclass fw inputs they map to.
if maybe_subclass_meta is None:
num_backward_tokens: int = inner_meta.num_backward_tokens
assert (
len(bw_outs)
== len(fw_metadata.input_info)
+ inner_meta.num_outputs_rng_offset
+ num_backward_tokens
)
bw_outs_no_rng_no_tokens = bw_outs
if (inner_meta.num_outputs_rng_offset + num_backward_tokens) > 0:
bw_outs_no_rng_no_tokens = bw_outs[
: -(inner_meta.num_outputs_rng_offset + num_backward_tokens)
]
assert len(bw_outs_no_rng_no_tokens) == len(fw_metadata.input_info)
for i, (bw_out) in enumerate(bw_outs_no_rng_no_tokens):
# If our input experiences a metadata mutation inside the graph (e.g. set_()),
# we *must* not detach, otherwise it will be the detach'd input that gets the metadata mutation
metadata_mutation_in_graph = (
fw_metadata.input_info[i].mutation_type
== MutationType.MUTATED_IN_GRAPH
and fw_metadata.input_info[i].mutates_storage_metadata
)
is_non_leaf = (
fw_metadata.input_info[i].requires_grad
and not fw_metadata.input_info[i].is_leaf
)
if bw_out is None and not metadata_mutation_in_graph and is_non_leaf:
_indices_of_inps_to_detach.append(i)
return (
fw_module,
bw_module,
num_fw_outs_saved_for_bw,
num_symints_saved_for_bw,
_indices_of_inps_to_detach,
joint_inputs[0],
)
def _aot_stage2b_fw_compile(
fw_module: torch.fx.GraphModule,
adjusted_flat_args: list[Any],
maybe_subclass_meta: Optional[SubclassMeta],
fw_metadata: ViewAndMutationMeta,
num_fw_outs_saved_for_bw: int,
aot_config: AOTConfig,
) -> tuple[Optional[list[Optional[tuple[int, ...]]]], Callable]:
return _aot_stage2b_compile_forward_or_inference(
fw_module,
adjusted_flat_args,
maybe_subclass_meta,
fw_metadata,
aot_config,
is_inference=False,
num_fw_outs_saved_for_bw=num_fw_outs_saved_for_bw,
)
def _aot_stage2b_bw_compile(
bw_module: torch.fx.GraphModule,
maybe_subclass_meta: Optional[SubclassMeta],
fw_metadata: ViewAndMutationMeta,
fwd_output_strides: Optional[list[Optional[tuple[int, ...]]]],
num_symints_saved_for_bw: int,
aot_config: AOTConfig,
) -> tuple[AutogradLazyBackwardCompileInfo, Optional[Callable]]:
"""
Compile the backward graph. Returns:
- the placeholder list for the backward graph
- the compiled backward function
"""
with torch.no_grad():
# NB: It's important to compile backwards ahead of time, as this may
# add extra guards which we need to apply to the Dynamo cache at
# forwards
with track_graph_compiling(aot_config, "backward"), torch._C._DisableAutocast():
placeholder_list = fx_placeholder_vals(bw_module)
forward_saved_for_backwards_strides = None
if fwd_output_strides is not None:
inner_meta = _get_inner_meta(maybe_subclass_meta, fw_metadata)
forward_saved_for_backwards_strides = fwd_output_strides[
inner_meta.tensors_saved_for_backwards_slice
]
# saved activations can have different stride to eager if
# the compiler does layout optimization. We should restride the
# tensor passed in for compiling the backward graph using the
# saved tensor's stride.
for i in range(len(placeholder_list)):
ph_arg = placeholder_list[i]
if not isinstance(ph_arg, torch.Tensor):
continue
if forward_saved_for_backwards_strides is None:
continue
real_stride = None
# Per all_args calling convention
j = i - num_symints_saved_for_bw
if 0 <= j < len(forward_saved_for_backwards_strides):
real_stride = forward_saved_for_backwards_strides[j]
if real_stride is None:
continue
# Comparing ph_arg.stride() with real_stride directly may
# cause dynamic dimensions in ph_arg being specialized to static
# value. Using suppress_guards and guard_or_true to avoid that.
stride_different = False
fake_mode = detect_fake_mode()
suppress_ctx = (
fake_mode.shape_env.suppress_guards()
if fake_mode is not None and fake_mode.shape_env is not None
else nullcontext()
)
# Inductor can choose different strides for activations than
# what backward graph has. if we can't statically tell that
# strides are the same, we assume they are not.
with suppress_ctx:
for k in range(len(ph_arg.stride())):
# real_stride can't be symbolic.
# pyrefly: ignore [index-error]
if guard_or_true(ph_arg.stride()[k] != int(real_stride[k])):
stride_different = True
break
if stride_different:
# Note that here we use the stride of the real tensor to
# restride a FakeTensor. This does not cause trouble
# for dynamic shape since this code path only get
# executed if layout optimization is enabled. And we
# disable layout optimization for dynamic shape right
# now.
#
# A solution that decide stride order based on real
# tensor's stride and then apply that stride order to
# the FakeTensor does not work smoothly since some
# tensor's layout is not 'dense'. E.g. mixnet_l has a
# tensor with size [8, 64, 112, 112] and strides
# (2408448, 1, 21504, 192). The solution mentioned will
# decide a stride of (802816, 1, 7168, 64) for this
# tensor which is wrong.
ph_size = ph_arg.size()
# pyrefly: ignore [bad-argument-type]
placeholder_list[i] = ph_arg.as_strided(ph_size, real_stride)
compiled_bw_func = None
if (
num_symints_saved_for_bw > 0
or aot_config.force_non_lazy_backward_lowering
):
try:
# See Note: [Backward graph lazy lowering]
with torch._subclasses.fake_tensor.unset_fake_temporarily():
# If bw_module contains lifted constants, they will be real tensors stored as
# GraphModule. Deepcopying tensors under fake mode is not supported and will
# raise when attempting to set storage.
bw_module_copy = copy.deepcopy(bw_module)
compiled_bw_func = aot_config.bw_compiler(
bw_module_copy, placeholder_list
)
del bw_module_copy
except Exception as e:
if aot_config.force_non_lazy_backward_lowering:
raise
exc = e
trace_structured(
"artifact",
metadata_fn=lambda: {
"name": "eager_compile_backwards_failure",
"encoding": "string",
},
payload_fn=lambda: "\n".join(
traceback.format_exception(
type(exc), exc, exc.__traceback__
)
),
)
log.warning(
"failed to eagerly compile backwards for dynamic, suppressing in case backwards not needed",
exc_info=True,
)
# Compiled autograd will run the bw_module in the backward pass,
# so recompilation need happen anyway if the backward pass is ever
# called.
#
# The reason we do the GraphModule recompilation here is because
# the lazy recompilation will cause issue in the backward pass
# with compiled autograd.
#
# Do the _LazyGraphModule.force_recompile here rather than when
# bw_module is first generated by the partitioner because the bw_module.recompile
# may be called in some code path later and cause the _LazyGraphModule.forward
# becomes the lazy version again. One example is when dynamic shape is enabled
# upfront, the bw_compiler will be called above which can cause extra
# graph module recompilation on bw_module.
if torch._dynamo.compiled_autograd.in_compiled_autograd_region:
from torch.fx._lazy_graph_module import _LazyGraphModule
_LazyGraphModule.force_recompile(bw_module)
saved_context = TracingContext.try_get()
saved_compile_context = CompileContext.try_get()
lazy_backward_info = AutogradLazyBackwardCompileInfo(
bw_module,
placeholder_list,
saved_context,
saved_compile_context,
)
return lazy_backward_info, compiled_bw_func
def aot_stage2_autograd(
aot_state: AOTState,
aot_graph_capture: AOTGraphCapture,
) -> DispatchReturn:
"""
Autograd logic. Generates a joint graph, partitions it, manipulates the input with various wrappers,
and returns a wrapped torch.autograd.Function with a forward and backward.
"""
fx_g = aot_graph_capture.graph_module
maybe_subclass_meta = aot_graph_capture.maybe_subclass_meta
fw_metadata = aot_state.fw_metadata
aot_config = aot_state.aot_config
CompileEventLogger.try_add_pt2_compile("backend_compile", dispatch_mode="autograd")
joint_graph_str = _log_joint_graph(fx_g, aot_config)
_apply_tensorify_python_scalars(fx_g)
(
fw_module,
bw_module,
num_fw_outs_saved_for_bw,
num_symints_saved_for_bw,
_indices_of_inps_to_detach,
adjusted_flat_args,
) = _aot_stage2a_partition(
fx_g,
aot_graph_capture.updated_flat_args,
maybe_subclass_meta,
fw_metadata,
aot_config,
)
fw_module_str, bw_module_str = _log_fw_bw_graphs(
fw_module, bw_module, maybe_subclass_meta, fw_metadata, aot_config
)
fwd_output_strides, compiled_fw_func = _aot_stage2b_fw_compile(
fw_module,
adjusted_flat_args,
maybe_subclass_meta,
fw_metadata,
num_fw_outs_saved_for_bw,
aot_config,
)
lazy_backward_info, compiled_bw_func = _aot_stage2b_bw_compile(
bw_module,
maybe_subclass_meta,
fw_metadata,
fwd_output_strides,
num_symints_saved_for_bw,
aot_config,
)
try_save_cache_entry, entry = _cache_autograd_info(
aot_config,
aot_state.flat_args,
compiled_fw_func,
compiled_bw_func,
fw_module_str,
bw_module_str,
joint_graph_str,
aot_graph_capture.wrappers,
maybe_subclass_meta,
fw_metadata,
num_fw_outs_saved_for_bw,
_indices_of_inps_to_detach,
num_symints_saved_for_bw,
bw_module,
)
return _aot_stage2c_make_autograd_function(
aot_config,
aot_state.flat_args,
fw_metadata,
maybe_subclass_meta,
aot_graph_capture.wrappers,
compiled_fw_func,
compiled_bw_func,
lazy_backward_info,
try_save_cache_entry,
entry,
_indices_of_inps_to_detach,
num_symints_saved_for_bw,
)
def _aot_stage2c_make_autograd_function(
aot_config,
flat_args,
fw_metadata,
maybe_subclass_meta,
wrappers,
compiled_fw_func,
compiled_bw_func,
lazy_backward_info,
try_save_cache_entry,
entry,
_indices_of_inps_to_detach,
num_symints_saved_for_bw,
):
backward_state_indices = [
idx for idx, x in enumerate(flat_args) if isinstance(x, BackwardState)
]
assert len(backward_state_indices) <= 1
disable_amp = torch._C._is_any_autocast_enabled()
compiled_fn = AOTDispatchAutograd.post_compile(
compiled_fw_func,
compiled_bw_func,
maybe_subclass_meta,
num_symints_saved_for_bw,
backward_state_indices,
disable_amp,
_indices_of_inps_to_detach,
lazy_backward_info,
aot_config,
fw_metadata=fw_metadata,
try_save_cache_entry=try_save_cache_entry,
)
if entry is not None:
compiled_fn = SerializableCompiledFunction(compiled_fn, lambda: entry)
if config.debug_assert:
flat_requires_grad: list[Optional[bool]] = [
a.requires_grad if isinstance(a, Tensor) else None for a in flat_args
]
compiled_fn = DebugAssertWrapper(
flat_requires_grad=flat_requires_grad
).post_compile(compiled_fn, aot_config, runtime_metadata=fw_metadata)
compiled_fn = post_compile(
wrappers,
compiled_fn,
aot_config,
runtime_metadata=fw_metadata,
)
return compiled_fn
def _cache_autograd_info(
aot_config,
flat_args,
compiled_fw_func,
compiled_bw_func,
fw_module_str,
bw_module_str,
joint_graph_str,
wrappers,
maybe_subclass_meta,
fw_metadata,
num_fw_outs_saved_for_bw,
_indices_of_inps_to_detach,
num_symints_saved_for_bw,
bw_module,
):
backward_state_indices = [
idx for idx, x in enumerate(flat_args) if isinstance(x, BackwardState)
]
assert len(backward_state_indices) <= 1
make_runtime_safe(fw_metadata, maybe_subclass_meta)
try_save_cache_entry: Optional[Callable] = None
entry: Optional[GenericAOTAutogradResult] = None
if aot_config.cache_info is not None:
forward_time_taken_ns = time.time_ns() - aot_config.cache_info.start_time_ns
# NB: aot_config here is technically not needed as an argument: we could just
# close over aot_config.cache_info, since aot_config never changes.
# But closing over random variables is confusing IMO, so I'm leaving it.
def try_save_cache_entry( # noqa: F811
compiled_bw_func: Callable,
bw_module: torch.fx.GraphModule,
_fw_metadata: ViewAndMutationMeta,
aot_config: AOTConfig,
) -> Optional[GenericAOTAutogradResult]:
cache_info = aot_config.cache_info
def should_save_cache():
if should_bundle_autograd_cache():
return True
else:
return hasattr(compiled_fw_func, "_fx_graph_cache_key") and hasattr(
compiled_bw_func, "_fx_graph_cache_key"
)
if cache_info is not None and should_save_cache():
assert forward_time_taken_ns is not None
# TODO: technically, AOTAutograd does a *little* bit of post processing work
# in the backward that isn't measured here. But it's small enough that it's not worth
# the complexity of threading a bunch of times through the code, so we
# use the compiled_bw_func's inductor compile time instead.
# It's possible this changes in the future, in which case we should
# update backward_time_taken_ns to be more inclusive
backward_time_taken_ns = getattr(compiled_bw_func, "_time_taken_ns", 0)
aot_forward_graph_str: Optional[str] = fw_module_str
aot_backward_graph_str: Optional[str] = bw_module_str
aot_joint_graph_str: Optional[str] = joint_graph_str
guards_expr = AOTAutogradCache.generate_guards_expression(cache_info)
entry = AOTAutogradCache.make_entry(
compiled_fw_func, # type: ignore[arg-type]
compiled_bw_func, # type: ignore[arg-type]
aot_joint_graph_str,
aot_forward_graph_str,
aot_backward_graph_str,
_fw_metadata,
wrappers,
maybe_subclass_meta,
num_fw_outs_saved_for_bw,
_indices_of_inps_to_detach,
forward_time_taken_ns,
backward_time_taken_ns,
sanitized_aot_config=sanitize_aot_config(aot_config),
guards_expr=guards_expr,
backward_state_indices=backward_state_indices,
num_symints_saved_for_bw=num_symints_saved_for_bw,
serialized_bw_module=serialize_graph_module(bw_module),
)
AOTAutogradCache.save(
cache_info.cache_key,
entry,
remote=should_use_remote_autograd_cache(),
)
return entry
return None
if compiled_bw_func is not None:
# If we already compiled the backward, we save its cache entry now
entry = try_save_cache_entry(
compiled_bw_func, bw_module, fw_metadata, aot_config
)
try_save_cache_entry = None
return try_save_cache_entry, entry
def _aot_stage2b_compile_forward_or_inference(
fw_module: torch.fx.GraphModule,
adjusted_flat_args: list[Any],
maybe_subclass_meta: Optional[SubclassMeta],
fw_metadata: ViewAndMutationMeta,
aot_config: AOTConfig,
*,
is_inference: bool,
num_fw_outs_saved_for_bw: Optional[int] = None,
) -> tuple[Optional[list[Optional[tuple[int, ...]]]], Callable]:
"""
Compile the forward or inference graph. Returns:
- the output strides of the forward graph
- the compiled forward/inference function
Args:
fw_module: The forward graph module to compile
adjusted_flat_args: Flattened arguments after adjustments
maybe_subclass_meta: Metadata for tensor subclasses
fw_metadata: View and mutation metadata
aot_config: AOT configuration
is_inference: If True, compile for inference; if False, compile for forward (autograd)
num_fw_outs_saved_for_bw: Number of forward outputs saved for backward (required if not is_inference)
Before compiling, we run pre_compile for the following wrappers:
- FakifiedOutWrapper
- FunctionalizedRngRuntimeWrapper
After compiling, we run post_compile for the following wrappers:
- EffectTokensWrapper
- AOTDispatchSubclassWrapper
- FunctionalizedRngRuntimeWrapper
- FakifiedOutWrapper
"""
# Validation
if not is_inference and num_fw_outs_saved_for_bw is None:
raise ValueError(
"num_fw_outs_saved_for_bw must be provided when is_inference=False"
)
# Determine grad context, autocast context, tracking mode, compiler
if is_inference:
grad_ctx: Any = nullcontext
autocast_ctx: Any = (
torch._C._DisableAutocast
if torch._C._is_any_autocast_enabled()
else nullcontext
)
tracking_mode: str = "inference"
compiler: Any = aot_config.inference_compiler
else:
grad_ctx = torch.no_grad
autocast_ctx = torch._C._DisableAutocast
tracking_mode = "forward"
compiler = aot_config.fw_compiler
with grad_ctx(), autocast_ctx(), track_graph_compiling(aot_config, tracking_mode):
# Setup wrappers
fakified_out_wrapper = FakifiedOutWrapper()
fakified_out_wrapper.pre_compile(
fw_module, adjusted_flat_args, aot_config, fw_metadata=fw_metadata
)
# Initialize RNG wrapper based on mode
functionalized_rng_wrapper = FunctionalizedRngRuntimeWrapper(
return_new_outs=is_inference
)
# Add RNG states for forward mode only
if not is_inference and fw_metadata.num_graphsafe_rng_states > 0:
index = fw_metadata.graphsafe_rng_state_index
assert index is not None
rng_states = [
get_cuda_generator_meta_val(index)
for _ in range(fw_metadata.num_graphsafe_rng_states)
]
adjusted_flat_args.extend(rng_states) # type: ignore[arg-type]
functionalized_rng_wrapper.pre_compile(
fw_module, adjusted_flat_args, aot_config, fw_metadata=fw_metadata
)
# Set tracing context
if tracing_context := torch._guards.TracingContext.try_get():
tracing_context.fw_metadata = _get_inner_meta(
maybe_subclass_meta, fw_metadata
)
with TracingContext.report_output_strides() as fwd_output_strides:
compiled_fw_func = compiler(fw_module, adjusted_flat_args)
# Make boxed if needed
if not getattr(compiled_fw_func, "_boxed_call", False):
compiled_fw_func = make_boxed_func(compiled_fw_func)
# Set forward output strides if needed
if fakified_out_wrapper.needs_post_compile:
fakified_out_wrapper.set_fwd_output_strides(fwd_output_strides)
# Apply post-compile wrappers
compiled_fw_func = EffectTokensWrapper().post_compile(
compiled_fw_func,
aot_config,
runtime_metadata=fw_metadata,
)
compiled_fw_func = AOTDispatchSubclassWrapper(
fw_only=None,
trace_joint=False,
maybe_subclass_meta=maybe_subclass_meta,
num_fw_outs_saved_for_bw=num_fw_outs_saved_for_bw,
).post_compile(
compiled_fw_func,
aot_config,
runtime_metadata=fw_metadata,
)
compiled_fw_func = functionalized_rng_wrapper.post_compile(
compiled_fw_func, aot_config, runtime_metadata=fw_metadata
)
compiled_fw_func = fakified_out_wrapper.post_compile(
compiled_fw_func,
aot_config,
runtime_metadata=fw_metadata,
)
return fwd_output_strides, compiled_fw_func
| InvokeSubgraphHopGraphs |
python | numpy__numpy | numpy/lib/tests/test_nanfunctions.py | {
"start": 19832,
"end": 21842
} | class ____(SharedNanFunctionsTestsMixin):
nanfuncs = [np.nansum, np.nanprod]
stdfuncs = [np.sum, np.prod]
@pytest.mark.parametrize("axis", [None, 0, 1])
@pytest.mark.parametrize("dtype", np.typecodes["AllFloat"])
@pytest.mark.parametrize("array", [
np.array(np.nan),
np.full((3, 3), np.nan),
], ids=["0d", "2d"])
def test_allnans(self, axis, dtype, array):
if axis is not None and array.ndim == 0:
pytest.skip("`axis != None` not supported for 0d arrays")
array = array.astype(dtype)
for func, identity in zip(self.nanfuncs, [0, 1]):
out = func(array, axis=axis)
assert np.all(out == identity)
assert out.dtype == array.dtype
def test_empty(self):
for f, tgt_value in zip([np.nansum, np.nanprod], [0, 1]):
mat = np.zeros((0, 3))
tgt = [tgt_value] * 3
res = f(mat, axis=0)
assert_equal(res, tgt)
tgt = []
res = f(mat, axis=1)
assert_equal(res, tgt)
tgt = tgt_value
res = f(mat, axis=None)
assert_equal(res, tgt)
@pytest.mark.parametrize("dtype", np.typecodes["AllFloat"])
def test_initial(self, dtype):
ar = np.arange(9).astype(dtype)
ar[:5] = np.nan
for f in self.nanfuncs:
reference = 28 if f is np.nansum else 3360
ret = f(ar, initial=2)
assert ret.dtype == dtype
assert ret == reference
@pytest.mark.parametrize("dtype", np.typecodes["AllFloat"])
def test_where(self, dtype):
ar = np.arange(9).reshape(3, 3).astype(dtype)
ar[0, :] = np.nan
where = np.ones_like(ar, dtype=np.bool)
where[:, 0] = False
for f in self.nanfuncs:
reference = 26 if f is np.nansum else 2240
ret = f(ar, where=where, initial=2)
assert ret.dtype == dtype
assert ret == reference
| TestNanFunctions_SumProd |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 579454,
"end": 579819
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("assignable", "client_mutation_id")
assignable = sgqlc.types.Field(Assignable, graphql_name="assignable")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
| RemoveAssigneesFromAssignablePayload |
python | streamlit__streamlit | lib/streamlit/errors.py | {
"start": 9698,
"end": 10856
} | class ____(LocalizableStreamlitException):
"""Exception raised when there are more default selections specified than the max allowable selections."""
def __init__(
self, current_selections_count: int, max_selections_count: int
) -> None:
super().__init__(
"Multiselect has {current_selections_count} {current_selections_noun} "
"selected but `max_selections` is set to {max_selections_count}. "
"This happened because you either gave too many options to `default` "
"or you manipulated the widget's state through `st.session_state`. "
"Note that the latter can happen before the line indicated in the traceback. "
"Please select at most {max_selections_count} {options_noun}.",
current_selections_count=current_selections_count,
current_selections_noun="option"
if current_selections_count == 1
else "options",
max_selections_count=max_selections_count,
options_noun="option" if max_selections_count == 1 else "options",
)
# st.number_input
| StreamlitSelectionCountExceedsMaxError |
python | ray-project__ray | rllib/env/external_env.py | {
"start": 8606,
"end": 12465
} | class ____:
"""Tracked state for each active episode."""
def __init__(
self,
episode_id: str,
results_avail_condition: threading.Condition,
training_enabled: bool,
multiagent: bool = False,
):
self.episode_id = episode_id
self.results_avail_condition = results_avail_condition
self.training_enabled = training_enabled
self.multiagent = multiagent
self.data_queue = queue.Queue()
self.action_queue = queue.Queue()
if multiagent:
self.new_observation_dict = None
self.new_action_dict = None
self.cur_reward_dict = {}
self.cur_terminated_dict = {"__all__": False}
self.cur_truncated_dict = {"__all__": False}
self.cur_info_dict = {}
else:
self.new_observation = None
self.new_action = None
self.cur_reward = 0.0
self.cur_terminated = False
self.cur_truncated = False
self.cur_info = {}
def get_data(self):
if self.data_queue.empty():
return None
return self.data_queue.get_nowait()
def log_action(self, observation, action):
if self.multiagent:
self.new_observation_dict = observation
self.new_action_dict = action
else:
self.new_observation = observation
self.new_action = action
self._send()
self.action_queue.get(True, timeout=60.0)
def wait_for_action(self, observation):
if self.multiagent:
self.new_observation_dict = observation
else:
self.new_observation = observation
self._send()
return self.action_queue.get(True, timeout=300.0)
def done(self, observation):
if self.multiagent:
self.new_observation_dict = observation
self.cur_terminated_dict = {"__all__": True}
# TODO(sven): External env API does not currently support truncated,
# but we should deprecate external Env anyways in favor of a client-only
# approach.
self.cur_truncated_dict = {"__all__": False}
else:
self.new_observation = observation
self.cur_terminated = True
self.cur_truncated = False
self._send()
def _send(self):
if self.multiagent:
if not self.training_enabled:
for agent_id in self.cur_info_dict:
self.cur_info_dict[agent_id]["training_enabled"] = False
item = {
"obs": self.new_observation_dict,
"reward": self.cur_reward_dict,
"terminated": self.cur_terminated_dict,
"truncated": self.cur_truncated_dict,
"info": self.cur_info_dict,
}
if self.new_action_dict is not None:
item["off_policy_action"] = self.new_action_dict
self.new_observation_dict = None
self.new_action_dict = None
self.cur_reward_dict = {}
else:
item = {
"obs": self.new_observation,
"reward": self.cur_reward,
"terminated": self.cur_terminated,
"truncated": self.cur_truncated,
"info": self.cur_info,
}
if self.new_action is not None:
item["off_policy_action"] = self.new_action
self.new_observation = None
self.new_action = None
self.cur_reward = 0.0
if not self.training_enabled:
item["info"]["training_enabled"] = False
with self.results_avail_condition:
self.data_queue.put_nowait(item)
self.results_avail_condition.notify()
@OldAPIStack
| _ExternalEnvEpisode |
python | Lightning-AI__lightning | src/lightning/fabric/utilities/distributed.py | {
"start": 14273,
"end": 16023
} | class ____(DistributedSampler):
"""Wrapper over ``Sampler`` for distributed training.
Allows you to use any sampler in distributed mode. It will be automatically used by Lightning in distributed mode if
sampler replacement is enabled.
Note:
The purpose of this wrapper is to take care of sharding the sampler indices. It is up to the underlying
sampler to handle randomness and shuffling. The ``shuffle`` and ``seed`` arguments on this wrapper won't
have any effect.
"""
def __init__(self, sampler: Union[Sampler, Iterable], *args: Any, **kwargs: Any) -> None:
super().__init__(_DatasetSamplerWrapper(sampler), *args, **kwargs)
@override
def __iter__(self) -> Iterator:
self.dataset.reset()
return (self.dataset[index] for index in super().__iter__())
def _suggested_max_num_threads(num_processes: int = 1) -> int:
if num_processes < 1:
raise ValueError(f"`num_processes` should be >= 1, got {num_processes}.")
return max(1, _num_cpus_available() // num_processes)
def _set_num_threads_if_needed(num_processes: int = 1) -> None:
if "OMP_NUM_THREADS" not in os.environ:
num_threads = _suggested_max_num_threads(num_processes)
torch.set_num_threads(num_threads)
os.environ["OMP_NUM_THREADS"] = str(num_threads)
def _distributed_is_initialized() -> bool:
# `is_initialized` is only defined conditionally
# https://github.com/pytorch/pytorch/blob/v2.1.0/torch/distributed/__init__.py#L25
# this might happen to MacOS builds from source (default) or any build from source that sets `USE_DISTRIBUTED=0`
return torch.distributed.is_available() and torch.distributed.is_initialized()
| DistributedSamplerWrapper |
python | mkdocs__mkdocs | mkdocs/config/config_options.py | {
"start": 25853,
"end": 27218
} | class ____(Dir):
"""
SiteDir Config Option.
Validates the site_dir and docs_dir directories do not contain each other.
"""
def post_validation(self, config: Config, key_name: str):
super().post_validation(config, key_name)
docs_dir = config['docs_dir']
site_dir = config['site_dir']
# Validate that the docs_dir and site_dir don't contain the
# other as this will lead to copying back and forth on each
# and eventually make a deep nested mess.
if (docs_dir + os.sep).startswith(site_dir.rstrip(os.sep) + os.sep):
raise ValidationError(
f"The 'docs_dir' should not be within the 'site_dir' as this "
f"can mean the source files are overwritten by the output or "
f"it will be deleted if --clean is passed to mkdocs build. "
f"(site_dir: '{site_dir}', docs_dir: '{docs_dir}')"
)
elif (site_dir + os.sep).startswith(docs_dir.rstrip(os.sep) + os.sep):
raise ValidationError(
f"The 'site_dir' should not be within the 'docs_dir' as this "
f"leads to the build directory being copied into itself and "
f"duplicate nested files in the 'site_dir'. "
f"(site_dir: '{site_dir}', docs_dir: '{docs_dir}')"
)
| SiteDir |
python | gevent__gevent | src/gevent/tests/test__socket_dns.py | {
"start": 33362,
"end": 33435
} | class ____(TestCase):
pass
add(TestBadName, 'xxxxxxxxxxxx')
| TestBadName |
python | scikit-learn__scikit-learn | sklearn/multioutput.py | {
"start": 15021,
"end": 21695
} | class ____(ClassifierMixin, _MultiOutputEstimator):
"""Multi target classification.
This strategy consists of fitting one classifier per target. This is a
simple strategy for extending classifiers that do not natively support
multi-target classification.
Parameters
----------
estimator : estimator object
An estimator object implementing :term:`fit` and :term:`predict`.
A :term:`predict_proba` method will be exposed only if `estimator` implements
it.
n_jobs : int or None, optional (default=None)
The number of jobs to run in parallel.
:meth:`fit`, :meth:`predict` and :meth:`partial_fit` (if supported
by the passed estimator) will be parallelized for each target.
When individual estimators are fast to train or predict,
using ``n_jobs > 1`` can result in slower performance due
to the parallelism overhead.
``None`` means `1` unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all available processes / threads.
See :term:`Glossary <n_jobs>` for more details.
.. versionchanged:: 0.20
`n_jobs` default changed from `1` to `None`.
Attributes
----------
classes_ : ndarray of shape (n_classes,)
Class labels.
estimators_ : list of ``n_output`` estimators
Estimators used for predictions.
n_features_in_ : int
Number of features seen during :term:`fit`. Only defined if the
underlying `estimator` exposes such an attribute when fit.
.. versionadded:: 0.24
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Only defined if the
underlying estimators expose such an attribute when fit.
.. versionadded:: 1.0
See Also
--------
ClassifierChain : A multi-label model that arranges binary classifiers
into a chain.
MultiOutputRegressor : Fits one regressor per target variable.
Examples
--------
>>> import numpy as np
>>> from sklearn.datasets import make_multilabel_classification
>>> from sklearn.multioutput import MultiOutputClassifier
>>> from sklearn.linear_model import LogisticRegression
>>> X, y = make_multilabel_classification(n_classes=3, random_state=0)
>>> clf = MultiOutputClassifier(LogisticRegression()).fit(X, y)
>>> clf.predict(X[-2:])
array([[1, 1, 1],
[1, 0, 1]])
"""
def __init__(self, estimator, *, n_jobs=None):
super().__init__(estimator, n_jobs=n_jobs)
def fit(self, X, Y, sample_weight=None, **fit_params):
"""Fit the model to data matrix X and targets Y.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The input data.
Y : array-like of shape (n_samples, n_classes)
The target values.
sample_weight : array-like of shape (n_samples,), default=None
Sample weights. If `None`, then samples are equally weighted.
Only supported if the underlying classifier supports sample
weights.
**fit_params : dict of string -> object
Parameters passed to the ``estimator.fit`` method of each step.
.. versionadded:: 0.23
Returns
-------
self : object
Returns a fitted instance.
"""
super().fit(X, Y, sample_weight=sample_weight, **fit_params)
self.classes_ = [estimator.classes_ for estimator in self.estimators_]
return self
def _check_predict_proba(self):
if hasattr(self, "estimators_"):
# raise an AttributeError if `predict_proba` does not exist for
# each estimator
[getattr(est, "predict_proba") for est in self.estimators_]
return True
# raise an AttributeError if `predict_proba` does not exist for the
# unfitted estimator
getattr(self.estimator, "predict_proba")
return True
@available_if(_check_predict_proba)
def predict_proba(self, X):
"""Return prediction probabilities for each class of each output.
This method will raise a ``ValueError`` if any of the
estimators do not have ``predict_proba``.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The input data.
Returns
-------
p : array of shape (n_samples, n_classes), or a list of n_outputs \
such arrays if n_outputs > 1.
The class probabilities of the input samples. The order of the
classes corresponds to that in the attribute :term:`classes_`.
.. versionchanged:: 0.19
This function now returns a list of arrays where the length of
the list is ``n_outputs``, and each array is (``n_samples``,
``n_classes``) for that particular output.
"""
check_is_fitted(self)
results = [estimator.predict_proba(X) for estimator in self.estimators_]
return results
def score(self, X, y):
"""Return the mean accuracy on the given test data and labels.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Test samples.
y : array-like of shape (n_samples, n_outputs)
True values for X.
Returns
-------
scores : float
Mean accuracy of predicted target versus true target.
"""
check_is_fitted(self)
n_outputs_ = len(self.estimators_)
if y.ndim == 1:
raise ValueError(
"y must have at least two dimensions for "
"multi target classification but has only one"
)
if y.shape[1] != n_outputs_:
raise ValueError(
"The number of outputs of Y for fit {0} and"
" score {1} should be same".format(n_outputs_, y.shape[1])
)
y_pred = self.predict(X)
return np.mean(np.all(y == y_pred, axis=1))
def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
# FIXME
tags._skip_test = True
return tags
def _available_if_base_estimator_has(attr):
"""Return a function to check if `base_estimator` or `estimators_` has `attr`.
Helper for Chain implementations.
"""
def _check(self):
return hasattr(self._get_estimator(), attr) or all(
hasattr(est, attr) for est in self.estimators_
)
return available_if(_check)
| MultiOutputClassifier |
python | ijl__orjson | test/test_subclass.py | {
"start": 2422,
"end": 3126
} | class ____:
def test_subclass_str(self):
with pytest.raises(orjson.JSONEncodeError):
orjson.dumps(SubStr("zxc"), option=orjson.OPT_PASSTHROUGH_SUBCLASS)
def test_subclass_int(self):
with pytest.raises(orjson.JSONEncodeError):
orjson.dumps(SubInt(1), option=orjson.OPT_PASSTHROUGH_SUBCLASS)
def test_subclass_dict(self):
with pytest.raises(orjson.JSONEncodeError):
orjson.dumps(SubDict({"a": "b"}), option=orjson.OPT_PASSTHROUGH_SUBCLASS)
def test_subclass_list(self):
with pytest.raises(orjson.JSONEncodeError):
orjson.dumps(SubList(["a", "b"]), option=orjson.OPT_PASSTHROUGH_SUBCLASS)
| TestSubclassPassthrough |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/endpoints-frameworks-v2/echo/main.py | {
"start": 883,
"end": 960
} | class ____(messages.Message):
message = messages.StringField(1)
| EchoRequest |
python | Netflix__metaflow | metaflow/plugins/env_escape/client_modules.py | {
"start": 4304,
"end": 10580
} | class ____(object):
"""
A custom import hook that proxies module imports to a different Python environment.
This class implements the MetaPathFinder and Loader protocols (PEP 451) to enable
"environment escape" - allowing the current Python process to import and use modules
from a different Python interpreter with potentially different versions or packages.
When a module is imported through this importer:
1. A client spawns a server process in the target Python environment
2. The module is loaded in the remote environment
3. A _WrappedModule proxy is returned that forwards all operations (function calls,
attribute access, etc.) to the remote environment via RPC
4. Data is serialized/deserialized using pickle for cross-environment communication
Args:
python_executable: Path to the Python interpreter for the remote environment
pythonpath: Python path to use in the remote environment
max_pickle_version: Maximum pickle protocol version supported by remote interpreter
config_dir: Directory containing configuration for the environment escape
module_prefixes: List of module name prefixes to handle
"""
def __init__(
self,
python_executable,
pythonpath,
max_pickle_version,
config_dir,
module_prefixes,
):
self._module_prefixes = module_prefixes
self._python_executable = python_executable
self._pythonpath = pythonpath
self._config_dir = config_dir
self._client = None
self._max_pickle_version = max_pickle_version
self._handled_modules = None
self._aliases = {}
def find_spec(self, fullname, path=None, target=None):
if self._handled_modules is not None:
if get_canonical_name(fullname, self._aliases) in self._handled_modules:
return importlib.util.spec_from_loader(fullname, self)
return None
if any([fullname.startswith(prefix) for prefix in self._module_prefixes]):
# We potentially handle this
return importlib.util.spec_from_loader(fullname, self)
return None
def create_module(self, spec):
# Return the pre-created wrapped module for this spec
self._initialize_client()
fullname = spec.name
canonical_fullname = get_canonical_name(fullname, self._aliases)
# Modules are created canonically but we need to handle any of the aliases.
wrapped_module = self._handled_modules.get(canonical_fullname)
if wrapped_module is None:
raise ImportError(f"No module named '{fullname}'")
return wrapped_module
def exec_module(self, module):
# No initialization needed since the wrapped module returned by
# create_module() is fully initialized
pass
def _initialize_client(self):
if self._client is not None:
return
# We initialize a client and query the modules we handle
# The max_pickle_version is the pickle version that the server (so
# the underlying interpreter we call into) supports; we determine
# what version the current environment support and take the minimum
# of those two
max_pickle_version = min(self._max_pickle_version, pickle.HIGHEST_PROTOCOL)
self._client = Client(
self._module_prefixes,
self._python_executable,
self._pythonpath,
max_pickle_version,
self._config_dir,
)
atexit.register(_clean_client, self._client)
# Get information about overrides and what the server knows about
exports = self._client.get_exports()
prefixes = set()
export_classes = exports.get("classes", [])
export_functions = exports.get("functions", [])
export_values = exports.get("values", [])
export_exceptions = exports.get("exceptions", [])
self._aliases = exports.get("aliases", {})
for name in itertools.chain(
export_classes,
export_functions,
export_values,
(e[0] for e in export_exceptions),
):
splits = name.rsplit(".", 1)
prefixes.add(splits[0])
# We will make sure that we create modules even for "empty" prefixes
# because packages are always loaded hierarchically so if we have
# something in `a.b.c` but nothing directly in `a`, we still need to
# create a module named `a`. There is probably a better way of doing this
all_prefixes = list(prefixes)
for prefix in all_prefixes:
parts = prefix.split(".")
cur = parts[0]
for i in range(1, len(parts)):
prefixes.add(cur)
cur = ".".join([cur, parts[i]])
# We now know all the modules that we can handle. We update
# handled_module and return the module if we have it or raise ImportError
self._handled_modules = {}
for prefix in prefixes:
self._handled_modules[prefix] = _WrappedModule(
self, prefix, exports, self._client
)
def create_modules(python_executable, pythonpath, max_pickle_version, path, prefixes):
# This is an extra verification to make sure we are not trying to use the
# environment escape for something that is in the system
for prefix in prefixes:
try:
importlib.import_module(prefix)
except ImportError:
pass
else:
# pass
raise RuntimeError(
"Trying to override %s when module exists in system" % prefix
)
# The first version forces the use of the environment escape even if the module
# exists in the system. This is useful for testing to make sure that the
# environment escape is used. The second version is more production friendly and
# will only use the environment escape if the module cannot be found
# sys.meta_path.insert(0, ModuleImporter(python_path, path, prefixes))
sys.meta_path.append(
ModuleImporter(
python_executable, pythonpath, max_pickle_version, path, prefixes
)
)
| ModuleImporter |
python | walkccc__LeetCode | solutions/2094. Finding 3-Digit Even Numbers/2094.py | {
"start": 0,
"end": 454
} | class ____:
def findEvenNumbers(self, digits: list[int]) -> list[int]:
ans = []
count = collections.Counter(digits)
# Try to construct `abc`.
for a in range(1, 10):
for b in range(0, 10):
for c in range(0, 9, 2):
if count[a] > 0 and count[b] > (
b == a) and count[c] > (
c == a) + (
c == b):
ans.append(a * 100 + b * 10 + c)
return ans
| Solution |
python | pytorch__pytorch | test/dynamo/test_export.py | {
"start": 116364,
"end": 116746
} | class ____(torch.nn.Module):
def forward(self, pred, x):
arg0: "Sym(Eq(s26, {size}))"; arg1: "f32[s77, s27]";
arg0, arg1, = fx_pytree.tree_flatten_spec(([pred, x], {{}}), self._in_spec)
l_x_ = arg1
sin: "f32[s77, s27]" = l_x_.sin(); l_x_ = None
return pytree.tree_unflatten([sin], self._out_spec)
"""
false_graph = """\
| GraphModule |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/hashability2.py | {
"start": 668,
"end": 716
} | class ____(E, D): ...
s5 = {G()}
d5 = {G(): 100}
| G |
python | django__django | tests/contenttypes_tests/models.py | {
"start": 2088,
"end": 2461
} | class ____(models.Model):
"""An ordered tag on an item."""
title = models.CharField(max_length=200)
content_type = models.ForeignKey(ContentType, models.CASCADE, null=True)
object_id = models.PositiveIntegerField(null=True)
parent = GenericForeignKey()
children = GenericRelation("Post")
class Meta:
order_with_respect_to = "parent"
| Post |
python | django__django | tests/utils_tests/test_autoreload.py | {
"start": 24457,
"end": 29134
} | class ____:
@mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed")
@mock.patch(
"django.utils.autoreload.iter_all_python_module_files", return_value=frozenset()
)
def test_glob(self, mocked_modules, notify_mock):
non_py_file = self.ensure_file(self.tempdir / "non_py_file")
self.reloader.watch_dir(self.tempdir, "*.py")
with self.tick_twice():
self.increment_mtime(non_py_file)
self.increment_mtime(self.existing_file)
self.assertEqual(notify_mock.call_count, 1)
self.assertCountEqual(notify_mock.call_args[0], [self.existing_file])
@mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed")
@mock.patch(
"django.utils.autoreload.iter_all_python_module_files", return_value=frozenset()
)
def test_multiple_globs(self, mocked_modules, notify_mock):
self.ensure_file(self.tempdir / "x.test")
self.reloader.watch_dir(self.tempdir, "*.py")
self.reloader.watch_dir(self.tempdir, "*.test")
with self.tick_twice():
self.increment_mtime(self.existing_file)
self.assertEqual(notify_mock.call_count, 1)
self.assertCountEqual(notify_mock.call_args[0], [self.existing_file])
@mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed")
@mock.patch(
"django.utils.autoreload.iter_all_python_module_files", return_value=frozenset()
)
def test_overlapping_globs(self, mocked_modules, notify_mock):
self.reloader.watch_dir(self.tempdir, "*.py")
self.reloader.watch_dir(self.tempdir, "*.p*")
with self.tick_twice():
self.increment_mtime(self.existing_file)
self.assertEqual(notify_mock.call_count, 1)
self.assertCountEqual(notify_mock.call_args[0], [self.existing_file])
@mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed")
@mock.patch(
"django.utils.autoreload.iter_all_python_module_files", return_value=frozenset()
)
def test_glob_recursive(self, mocked_modules, notify_mock):
non_py_file = self.ensure_file(self.tempdir / "dir" / "non_py_file")
py_file = self.ensure_file(self.tempdir / "dir" / "file.py")
self.reloader.watch_dir(self.tempdir, "**/*.py")
with self.tick_twice():
self.increment_mtime(non_py_file)
self.increment_mtime(py_file)
self.assertEqual(notify_mock.call_count, 1)
self.assertCountEqual(notify_mock.call_args[0], [py_file])
@mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed")
@mock.patch(
"django.utils.autoreload.iter_all_python_module_files", return_value=frozenset()
)
def test_multiple_recursive_globs(self, mocked_modules, notify_mock):
non_py_file = self.ensure_file(self.tempdir / "dir" / "test.txt")
py_file = self.ensure_file(self.tempdir / "dir" / "file.py")
self.reloader.watch_dir(self.tempdir, "**/*.txt")
self.reloader.watch_dir(self.tempdir, "**/*.py")
with self.tick_twice():
self.increment_mtime(non_py_file)
self.increment_mtime(py_file)
self.assertEqual(notify_mock.call_count, 2)
self.assertCountEqual(
notify_mock.call_args_list, [mock.call(py_file), mock.call(non_py_file)]
)
@mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed")
@mock.patch(
"django.utils.autoreload.iter_all_python_module_files", return_value=frozenset()
)
def test_nested_glob_recursive(self, mocked_modules, notify_mock):
inner_py_file = self.ensure_file(self.tempdir / "dir" / "file.py")
self.reloader.watch_dir(self.tempdir, "**/*.py")
self.reloader.watch_dir(inner_py_file.parent, "**/*.py")
with self.tick_twice():
self.increment_mtime(inner_py_file)
self.assertEqual(notify_mock.call_count, 1)
self.assertCountEqual(notify_mock.call_args[0], [inner_py_file])
@mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed")
@mock.patch(
"django.utils.autoreload.iter_all_python_module_files", return_value=frozenset()
)
def test_overlapping_glob_recursive(self, mocked_modules, notify_mock):
py_file = self.ensure_file(self.tempdir / "dir" / "file.py")
self.reloader.watch_dir(self.tempdir, "**/*.p*")
self.reloader.watch_dir(self.tempdir, "**/*.py*")
with self.tick_twice():
self.increment_mtime(py_file)
self.assertEqual(notify_mock.call_count, 1)
self.assertCountEqual(notify_mock.call_args[0], [py_file])
| IntegrationTests |
python | dagster-io__dagster | python_modules/libraries/dagster-looker/dagster_looker/api/components/looker_component.py | {
"start": 1547,
"end": 2212
} | class ____(Model, Resolvable):
"""Arguments for filtering which Looker content to load."""
dashboard_folders: Optional[list[list[str]]] = Field(
default=None,
description=(
"A list of folder paths to load dashboards from. Each folder path is a list of "
"folder names, starting from the root folder. If not provided, all dashboards "
"will be loaded."
),
)
only_fetch_explores_used_in_dashboards: bool = Field(
default=False,
description="If True, only load explores that are used in dashboards. If False, load all explores.",
)
@beta
@public
@dataclass
| LookerFilterArgs |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/operators/data_factory.py | {
"start": 1615,
"end": 3092
} | class ____(LoggingMixin, BaseOperatorLink):
"""Construct a link to monitor a pipeline run in Azure Data Factory."""
name = "Monitor Pipeline Run"
def get_link(
self,
operator: BaseOperator,
*,
ti_key: TaskInstanceKey,
) -> str:
run_id = XCom.get_value(key="run_id", ti_key=ti_key)
conn_id = operator.azure_data_factory_conn_id # type: ignore
conn = BaseHook.get_connection(conn_id)
extras = conn.extra_dejson
subscription_id = get_field(extras, "subscriptionId") or get_field(
extras, "extra__azure__subscriptionId"
)
if not subscription_id:
raise KeyError(f"Param subscriptionId not found in conn_id '{conn_id}'")
# Both Resource Group Name and Factory Name can either be declared in the Azure Data Factory
# connection or passed directly to the operator.
resource_group_name = operator.resource_group_name or get_field( # type: ignore
extras, "resource_group_name"
)
factory_name = operator.factory_name or get_field(extras, "factory_name") # type: ignore
url = (
f"https://adf.azure.com/en-us/monitoring/pipelineruns/{run_id}"
f"?factory=/subscriptions/{subscription_id}/"
f"resourceGroups/{resource_group_name}/providers/Microsoft.DataFactory/"
f"factories/{factory_name}"
)
return url
| AzureDataFactoryPipelineRunLink |
python | apache__airflow | providers/apache/hdfs/tests/unit/apache/hdfs/sensors/test_web_hdfs.py | {
"start": 1222,
"end": 2329
} | class ____:
@mock.patch("airflow.providers.apache.hdfs.hooks.webhdfs.WebHDFSHook")
def test_poke(self, mock_hook):
sensor = WebHdfsSensor(
task_id="test_task",
webhdfs_conn_id=TEST_HDFS_CONN,
filepath=TEST_HDFS_PATH,
)
exists = sensor.poke(dict())
assert exists
mock_hook.return_value.check_for_path.assert_called_once_with(hdfs_path=TEST_HDFS_PATH)
mock_hook.assert_called_once_with(TEST_HDFS_CONN)
@mock.patch("airflow.providers.apache.hdfs.hooks.webhdfs.WebHDFSHook")
def test_poke_should_return_false_for_non_existing_table(self, mock_hook):
mock_hook.return_value.check_for_path.return_value = False
sensor = WebHdfsSensor(
task_id="test_task",
webhdfs_conn_id=TEST_HDFS_CONN,
filepath=TEST_HDFS_PATH,
)
exists = sensor.poke(dict())
assert not exists
mock_hook.return_value.check_for_path.assert_called_once_with(hdfs_path=TEST_HDFS_PATH)
mock_hook.assert_called_once_with(TEST_HDFS_CONN)
| TestWebHdfsSensor |
python | instagram__MonkeyType | monkeytype/typing.py | {
"start": 16385,
"end": 18594
} | class ____(TypeRewriter):
"""
Relace a union of classes by the most specific
common base of its members (while avoiding multiple
inheritance), i.e.,
Union[Derived1, Derived2] -> Base
"""
def _compute_bases(self, klass):
"""
Return list of bases of a given class,
going from general (i.e., closer to object)
to specific (i.e., closer to class).
The list ends with the class itself, its
first element is the most general base of
the class up to (but excluding) any
base class having multiple inheritance
or the object class itself.
"""
bases = []
curr_klass = klass
while curr_klass is not object:
bases.append(curr_klass)
curr_bases = curr_klass.__bases__
if len(curr_bases) != 1:
break
curr_klass = curr_bases[0]
return bases[::-1]
def _merge_common_bases(self, first_bases, second_bases):
"""
Return list of bases common to both* classes,
going from general (i.e., closer to object)
to specific (i.e., closer to both classes).
"""
merged_bases = []
# Only process up to shorter of the lists
for first_base, second_base in zip(first_bases, second_bases):
if first_base is second_base:
merged_bases.append(second_base)
else:
break
return merged_bases
def rewrite_Union(self, union):
"""
Rewrite the union if possible, if no meaningful rewrite is possible,
return the original union.
"""
klasses = union.__args__
all_bases = []
for klass in klasses:
klass_bases = self._compute_bases(klass)
all_bases.append(klass_bases)
common_bases = functools.reduce(self._merge_common_bases, all_bases)
if common_bases:
return common_bases[-1]
return union
DEFAULT_REWRITER = ChainedRewriter(
(
RemoveEmptyContainers(),
RewriteConfigDict(),
RewriteLargeUnion(),
RewriteGenerator(),
)
)
| RewriteMostSpecificCommonBase |
python | optuna__optuna | optuna/_gp/acqf.py | {
"start": 8390,
"end": 11389
} | class ____(BaseAcquisitionFunc):
def __init__(
self,
gpr_list: list[GPRegressor],
search_space: SearchSpace,
Y_train: torch.Tensor,
n_qmc_samples: int,
qmc_seed: int | None,
stabilizing_noise: float = 1e-12,
) -> None:
def _get_non_dominated_box_bounds() -> tuple[torch.Tensor, torch.Tensor]:
# NOTE(nabenabe): Y is to be maximized, loss_vals is to be minimized.
loss_vals = -Y_train.numpy()
pareto_sols = loss_vals[_is_pareto_front(loss_vals, assume_unique_lexsorted=False)]
ref_point = np.max(loss_vals, axis=0)
ref_point = np.nextafter(np.maximum(1.1 * ref_point, 0.9 * ref_point), np.inf)
lbs, ubs = get_non_dominated_box_bounds(pareto_sols, ref_point)
# NOTE(nabenabe): Flip back the sign to make them compatible with maximization.
return torch.from_numpy(-ubs), torch.from_numpy(-lbs)
self._stabilizing_noise = stabilizing_noise
self._gpr_list = gpr_list
self._fixed_samples = _sample_from_normal_sobol(
dim=Y_train.shape[-1], n_samples=n_qmc_samples, seed=qmc_seed
)
self._non_dominated_box_lower_bounds, non_dominated_box_upper_bounds = (
_get_non_dominated_box_bounds()
)
self._non_dominated_box_intervals = (
non_dominated_box_upper_bounds - self._non_dominated_box_lower_bounds
).clamp_min_(_EPS)
# Since all the objectives are equally important, we simply use the mean of
# inverse of squared mean lengthscales over all the objectives.
# inverse_squared_lengthscales is used in optim_mixed.py.
# cf. https://github.com/optuna/optuna/blob/v4.3.0/optuna/_gp/optim_mixed.py#L200-L209
super().__init__(np.mean([gpr.length_scales for gpr in gpr_list], axis=0), search_space)
def eval_acqf(self, x: torch.Tensor) -> torch.Tensor:
Y_post = []
for i, gpr in enumerate(self._gpr_list):
mean, var = gpr.posterior(x)
stdev = torch.sqrt(var + self._stabilizing_noise)
# NOTE(nabenabe): By using fixed samples from the Sobol sequence, EHVI becomes
# deterministic, making it possible to optimize the acqf by l-BFGS.
# Sobol is better than the standard Monte-Carlo w.r.t. the approximation stability.
# cf. Appendix D of https://arxiv.org/pdf/2006.05078
Y_post.append(mean[..., None] + stdev[..., None] * self._fixed_samples[..., i])
# NOTE(nabenabe): Use the following once multi-task GP is supported.
# L = torch.linalg.cholesky(cov)
# Y_post = means[..., None, :] + torch.einsum("...MM,SM->...SM", L, fixed_samples)
return logehvi(
Y_post=torch.stack(Y_post, dim=-1),
non_dominated_box_lower_bounds=self._non_dominated_box_lower_bounds,
non_dominated_box_intervals=self._non_dominated_box_intervals,
)
| LogEHVI |
python | pydantic__pydantic | pydantic-core/python/pydantic_core/core_schema.py | {
"start": 51489,
"end": 52083
} | class ____(TypedDict, total=False):
type: Required[Literal['uuid']]
version: Literal[1, 3, 4, 5, 7]
strict: bool
ref: str
metadata: dict[str, Any]
serialization: SerSchema
def uuid_schema(
*,
version: Literal[1, 3, 4, 5, 6, 7, 8] | None = None,
strict: bool | None = None,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
serialization: SerSchema | None = None,
) -> UuidSchema:
return _dict_not_none(
type='uuid', version=version, strict=strict, ref=ref, metadata=metadata, serialization=serialization
)
| UuidSchema |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.