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
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDict18.py
{ "start": 2222, "end": 2258 }
class ____(TypedDict): y: int
TD11
python
openai__openai-python
src/openai/types/beta/assistant_stream_event.py
{ "start": 1982, "end": 2205 }
class ____(BaseModel): data: Run """ Represents an execution run on a [thread](https://platform.openai.com/docs/api-reference/threads). """ event: Literal["thread.run.in_progress"]
ThreadRunInProgress
python
sqlalchemy__sqlalchemy
test/ext/test_mutable.py
{ "start": 13192, "end": 20912 }
class ____(_MutableListTestFixture): run_define_tables = "each" def setup_mappers(cls): foo = cls.tables.foo cls.mapper_registry.map_imperatively(Foo, foo) def test_coerce_none(self): sess = fixture_session() f1 = Foo(data=None) sess.add(f1) sess.commit() eq_(f1.data, None) def test_coerce_raise(self): assert_raises_message( ValueError, "Attribute 'data' does not accept objects of type", Foo, data={1, 2, 3}, ) def test_in_place_mutation_int(self): sess = fixture_session() f1 = Foo(data=[1, 2]) sess.add(f1) sess.commit() f1.data[0] = 3 sess.commit() eq_(f1.data, [3, 2]) def test_in_place_mutation_str(self): sess = fixture_session() f1 = Foo(data=["one", "two"]) sess.add(f1) sess.commit() f1.data[0] = "three" sess.commit() eq_(f1.data, ["three", "two"]) # test 12802 f1.data[1] = ["four", "two"] sess.commit() eq_(f1.data, ["three", ["four", "two"]]) def test_in_place_slice_mutation_int(self): sess = fixture_session() f1 = Foo(data=[1, 2, 3, 4]) sess.add(f1) sess.commit() f1.data[1:3] = 5, 6 sess.commit() eq_(f1.data, [1, 5, 6, 4]) # test 12802 f1.data[1:3] = [9, 8, 7] sess.commit() eq_(f1.data, [1, 9, 8, 7, 4]) def test_in_place_slice_mutation_str(self): sess = fixture_session() f1 = Foo(data=["one", "two", "three", "four"]) sess.add(f1) sess.commit() f1.data[1:3] = "five", "six" sess.commit() eq_(f1.data, ["one", "five", "six", "four"]) def test_del_slice(self): sess = fixture_session() f1 = Foo(data=[1, 2, 3, 4]) sess.add(f1) sess.commit() del f1.data[1:3] sess.commit() eq_(f1.data, [1, 4]) def test_clear(self): if not hasattr(list, "clear"): # py2 list doesn't have 'clear' return sess = fixture_session() f1 = Foo(data=[1, 2]) sess.add(f1) sess.commit() f1.data.clear() sess.commit() eq_(f1.data, []) def test_pop(self): sess = fixture_session() f1 = Foo(data=[1, 2, 3]) sess.add(f1) sess.commit() eq_(f1.data.pop(), 3) eq_(f1.data.pop(0), 1) sess.commit() assert_raises(IndexError, f1.data.pop, 5) eq_(f1.data, [2]) def test_append(self): sess = fixture_session() f1 = Foo(data=[1, 2]) sess.add(f1) sess.commit() f1.data.append(5) sess.commit() eq_(f1.data, [1, 2, 5]) def test_extend(self): sess = fixture_session() f1 = Foo(data=[1, 2]) sess.add(f1) sess.commit() f1.data.extend([5]) sess.commit() eq_(f1.data, [1, 2, 5]) def test_operator_extend(self): sess = fixture_session() f1 = Foo(data=[1, 2]) sess.add(f1) sess.commit() f1.data += [5] sess.commit() eq_(f1.data, [1, 2, 5]) def test_insert(self): sess = fixture_session() f1 = Foo(data=[1, 2]) sess.add(f1) sess.commit() f1.data.insert(1, 5) sess.commit() eq_(f1.data, [1, 5, 2]) def test_insert2(self): # test #12802 sess = fixture_session() f1 = Foo(data=[1, 2]) sess.add(f1) sess.commit() f1.data.insert(1, [4, 2]) sess.commit() eq_(f1.data, [1, [4, 2], 2]) def test_remove(self): sess = fixture_session() f1 = Foo(data=[1, 2, 3]) sess.add(f1) sess.commit() f1.data.remove(2) sess.commit() eq_(f1.data, [1, 3]) def test_sort(self): sess = fixture_session() f1 = Foo(data=[1, 3, 2]) sess.add(f1) sess.commit() f1.data.sort() sess.commit() eq_(f1.data, [1, 2, 3]) def test_sort_w_key(self): sess = fixture_session() f1 = Foo(data=[1, 3, 2]) sess.add(f1) sess.commit() f1.data.sort(key=lambda elem: -1 * elem) sess.commit() eq_(f1.data, [3, 2, 1]) def test_sort_w_reverse_kwarg(self): sess = fixture_session() f1 = Foo(data=[1, 3, 2]) sess.add(f1) sess.commit() f1.data.sort(reverse=True) sess.commit() eq_(f1.data, [3, 2, 1]) def test_reverse(self): sess = fixture_session() f1 = Foo(data=[1, 3, 2]) sess.add(f1) sess.commit() f1.data.reverse() sess.commit() eq_(f1.data, [2, 3, 1]) def test_pickle_parent(self): sess = fixture_session() f1 = Foo(data=[1, 2]) sess.add(f1) sess.commit() f1.data sess.close() for loads, dumps in picklers(): sess = fixture_session() f2 = loads(dumps(f1)) sess.add(f2) f2.data[0] = 3 assert f2 in sess.dirty def test_unrelated_flush(self): sess = fixture_session() f1 = Foo(data=[1, 2], unrelated_data="unrelated") sess.add(f1) sess.flush() f1.unrelated_data = "unrelated 2" sess.flush() f1.data[0] = 3 sess.commit() eq_(f1.data[0], 3) def test_copy(self): f1 = Foo(data=[1, 2]) f1.data = copy.copy(f1.data) eq_(f1.data, [1, 2]) def test_deepcopy(self): f1 = Foo(data=[1, 2]) f1.data = copy.deepcopy(f1.data) eq_(f1.data, [1, 2]) def test_legacy_pickle_loads(self): # due to an inconsistency between pickle and copy, we have to change # MutableList to implement a __reduce_ex__ method. Which means we # have to make sure all the old pickle formats are still # deserializable since these can be used for persistence. these pickles # were all generated using a MutableList that has only __getstate__ and # __setstate__. # f1 = Foo(data=[1, 2]) # pickles = [ # dumps(f1.data) # for loads, dumps in picklers() # ] # print(repr(pickles)) # return pickles = [ b"\x80\x04\x95<\x00\x00\x00\x00\x00\x00\x00\x8c\x16" b"sqlalchemy.ext.mutable\x94\x8c\x0bMutableList\x94\x93\x94)" b"\x81\x94(K\x01K\x02e]\x94(K\x01K\x02eb.", b"ccopy_reg\n_reconstructor\np0\n(csqlalchemy.ext.mutable\n" b"MutableList\np1\nc__builtin__\nlist\np2\n(lp3\nI1\naI2\n" b"atp4\nRp5\n(lp6\nI1\naI2\nab.", b"ccopy_reg\n_reconstructor\nq\x00(csqlalchemy.ext.mutable\n" b"MutableList\nq\x01c__builtin__\nlist\nq\x02]q\x03(K\x01K" b"\x02etq\x04Rq\x05]q\x06(K\x01K\x02eb.", b"\x80\x02csqlalchemy.ext.mutable\nMutableList\nq\x00)\x81q" b"\x01(K\x01K\x02e]q\x02(K\x01K\x02eb.", b"\x80\x03csqlalchemy.ext.mutable\nMutableList\nq\x00)\x81q" b"\x01(K\x01K\x02e]q\x02(K\x01K\x02eb.", b"\x80\x04\x95<\x00\x00\x00\x00\x00\x00\x00\x8c\x16" b"sqlalchemy.ext.mutable\x94\x8c\x0bMutableList\x94\x93\x94)" b"\x81\x94(K\x01K\x02e]\x94(K\x01K\x02eb.", ] for pickle_ in pickles: obj = pickle.loads(pickle_) eq_(obj, [1, 2]) assert isinstance(obj, MutableList)
_MutableListTestBase
python
apache__airflow
task-sdk/tests/task_sdk/io/test_path.py
{ "start": 3169, "end": 5623 }
class ____: FAKE = "ffs:///fake" MNT = "ffs:///mnt/warehouse" FOO = "ffs:///mnt/warehouse/foo" BAR = FOO @pytest.fixture(autouse=True) def restore_cache(self): cache = _STORE_CACHE.copy() yield _STORE_CACHE.clear() _STORE_CACHE.update(cache) @pytest.fixture def fake_files(self): obj = _FakeRemoteFileSystem() obj.touch(self.FOO) try: yield finally: _FakeRemoteFileSystem.store.clear() _FakeRemoteFileSystem.pseudo_dirs[:] = [""] def test_alias(self): store = attach("file", alias="local") assert isinstance(store.fs, LocalFileSystem) assert {"local": store} == _STORE_CACHE def test_objectstoragepath_init_conn_id_in_uri(self): attach(protocol="fake", conn_id="fake", fs=_FakeRemoteFileSystem(conn_id="fake")) p = ObjectStoragePath("fake://fake@bucket/path") p.touch() fsspec_info = p.fs.info(p.path) assert p.stat() == {**fsspec_info, "conn_id": "fake", "protocol": "fake"} @pytest.mark.parametrize( ("fn", "args", "fn2", "path", "expected_args", "expected_kwargs"), [ ("checksum", {}, "checksum", FOO, _FakeRemoteFileSystem._strip_protocol(BAR), {}), ("size", {}, "size", FOO, _FakeRemoteFileSystem._strip_protocol(BAR), {}), ( "sign", {"expiration": 200, "extra": "xtra"}, "sign", FOO, _FakeRemoteFileSystem._strip_protocol(BAR), {"expiration": 200, "extra": "xtra"}, ), ("ukey", {}, "ukey", FOO, _FakeRemoteFileSystem._strip_protocol(BAR), {}), ( "read_block", {"offset": 0, "length": 1}, "read_block", FOO, _FakeRemoteFileSystem._strip_protocol(BAR), {"delimiter": None, "length": 1, "offset": 0}, ), ], ) def test_standard_extended_api(self, fake_files, fn, args, fn2, path, expected_args, expected_kwargs): fs = _FakeRemoteFileSystem() attach(protocol="ffs", conn_id="fake", fs=fs) with mock.patch.object(fs, fn2) as method: o = ObjectStoragePath(path, conn_id="fake") getattr(o, fn)(**args) method.assert_called_once_with(expected_args, **expected_kwargs)
TestAttach
python
django-mptt__django-mptt
tests/myapp/models.py
{ "start": 1754, "end": 2007 }
class ____(models.Model): genre = TreeForeignKey(Genre, on_delete=models.CASCADE) genres_m2m = models.ManyToManyField(Genre, related_name="games_m2m") name = models.CharField(max_length=50) def __str__(self): return self.name
Game
python
pypa__warehouse
tests/unit/packaging/test_services.py
{ "start": 15017, "end": 22524 }
class ____: def test_verify_service(self): assert verifyClass(IFileStorage, S3FileStorage) def test_basic_init(self): bucket = pretend.stub() storage = S3FileStorage(bucket) assert storage.bucket is bucket def test_create_service(self): session = boto3.session.Session( aws_access_key_id="foo", aws_secret_access_key="bar" ) request = pretend.stub( find_service=pretend.call_recorder(lambda name: session), registry=pretend.stub(settings={"files.bucket": "froblob"}), ) storage = S3FileStorage.create_service(None, request) assert request.find_service.calls == [pretend.call(name="aws.session")] assert storage.bucket.name == "froblob" def test_gets_file(self): s3key = pretend.stub(get=lambda: {"Body": io.BytesIO(b"my contents")}) bucket = pretend.stub(Object=pretend.call_recorder(lambda path: s3key)) storage = S3FileStorage(bucket) file_object = storage.get("file.txt") assert file_object.read() == b"my contents" assert bucket.Object.calls == [pretend.call("file.txt")] def test_gets_metadata(self): s3key = pretend.stub(metadata={"foo": "bar", "wu": "tang"}) bucket = pretend.stub(Object=pretend.call_recorder(lambda path: s3key)) storage = S3FileStorage(bucket) metadata = storage.get_metadata("file.txt") assert metadata == {"foo": "bar", "wu": "tang"} assert bucket.Object.calls == [pretend.call("file.txt")] def test_gets_checksum(self): s3key = pretend.stub(e_tag="deadbeef") bucket = pretend.stub(Object=pretend.call_recorder(lambda path: s3key)) storage = S3FileStorage(bucket) checksum = storage.get_checksum("file.txt") assert checksum == "deadbeef" assert bucket.Object.calls == [pretend.call("file.txt")] def test_raises_when_key_non_existent(self): def raiser(): raise botocore.exceptions.ClientError( {"Error": {"Code": "NoSuchKey", "Message": "No Key!"}}, "some operation" ) s3key = pretend.stub(get=raiser) bucket = pretend.stub(Object=pretend.call_recorder(lambda path: s3key)) storage = S3FileStorage(bucket) with pytest.raises(FileNotFoundError): storage.get("file.txt") assert bucket.Object.calls == [pretend.call("file.txt")] def test_get_metadata_raises_when_key_non_existent(self): def raiser(*a, **kw): raise botocore.exceptions.ClientError( {"Error": {"Code": "NoSuchKey", "Message": "No Key!"}}, "some operation" ) bucket = pretend.stub(Object=raiser) storage = S3FileStorage(bucket) with pytest.raises(FileNotFoundError): storage.get_metadata("file.txt") def test_get_checksum_raises_when_key_non_existent(self): def raiser(*a, **kw): raise botocore.exceptions.ClientError( {"ResponseMetadata": {"HTTPStatusCode": 404}}, "some operation" ) bucket = pretend.stub(Object=raiser) storage = S3FileStorage(bucket) with pytest.raises(FileNotFoundError): storage.get_checksum("file.txt") def test_passes_up_error_when_not_no_such_key(self): def raiser(): raise botocore.exceptions.ClientError( {"Error": {"Code": "SomeOtherError", "Message": "Who Knows!"}}, "some operation", ) s3key = pretend.stub(get=raiser) bucket = pretend.stub(Object=pretend.call_recorder(lambda path: s3key)) storage = S3FileStorage(bucket) with pytest.raises(botocore.exceptions.ClientError): storage.get("file.txt") def test_get_metadata_passes_up_error_when_not_no_such_key(self): def raiser(*a, **kw): raise botocore.exceptions.ClientError( {"Error": {"Code": "SomeOtherError", "Message": "Who Knows!"}}, "some operation", ) bucket = pretend.stub(Object=raiser) storage = S3FileStorage(bucket) with pytest.raises(botocore.exceptions.ClientError): storage.get_metadata("file.txt") def test_get_checksum_passes_up_error_when_not_no_such_key(self): def raiser(*a, **kw): raise botocore.exceptions.ClientError( {"ResponseMetadata": {"HTTPStatusCode": 666}}, "some operation", ) bucket = pretend.stub(Object=raiser) storage = S3FileStorage(bucket) with pytest.raises(botocore.exceptions.ClientError): storage.get_checksum("file.txt") def test_stores_file(self, tmpdir): filename = str(tmpdir.join("testfile.txt")) with open(filename, "wb") as fp: fp.write(b"Test File!") bucket = pretend.stub( upload_file=pretend.call_recorder(lambda filename, key, ExtraArgs: None) ) storage = S3FileStorage(bucket) storage.store("foo/bar.txt", filename) assert bucket.upload_file.calls == [ pretend.call(filename, "foo/bar.txt", ExtraArgs={}) ] def test_stores_two_files(self, tmpdir): filename1 = str(tmpdir.join("testfile1.txt")) with open(filename1, "wb") as fp: fp.write(b"First Test File!") filename2 = str(tmpdir.join("testfile2.txt")) with open(filename2, "wb") as fp: fp.write(b"Second Test File!") bucket = pretend.stub( upload_file=pretend.call_recorder(lambda filename, key, ExtraArgs: None) ) storage = S3FileStorage(bucket) storage.store("foo/first.txt", filename1) storage.store("foo/second.txt", filename2) assert bucket.upload_file.calls == [ pretend.call(filename1, "foo/first.txt", ExtraArgs={}), pretend.call(filename2, "foo/second.txt", ExtraArgs={}), ] def test_stores_metadata(self, tmpdir): filename = str(tmpdir.join("testfile.txt")) with open(filename, "wb") as fp: fp.write(b"Test File!") bucket = pretend.stub( upload_file=pretend.call_recorder(lambda filename, key, ExtraArgs: None) ) storage = S3FileStorage(bucket) storage.store("foo/bar.txt", filename, meta={"foo": "bar"}) assert bucket.upload_file.calls == [ pretend.call( filename, "foo/bar.txt", ExtraArgs={"Metadata": {"foo": "bar"}} ) ] def test_hashed_path_with_prefix(self): s3key = pretend.stub(get=lambda: {"Body": io.BytesIO(b"my contents")}) bucket = pretend.stub(Object=pretend.call_recorder(lambda path: s3key)) storage = S3FileStorage(bucket, prefix="packages/") file_object = storage.get("ab/file.txt") assert file_object.read() == b"my contents" assert bucket.Object.calls == [pretend.call("packages/ab/file.txt")] def test_hashed_path_without_prefix(self): s3key = pretend.stub(get=lambda: {"Body": io.BytesIO(b"my contents")}) bucket = pretend.stub(Object=pretend.call_recorder(lambda path: s3key)) storage = S3FileStorage(bucket) file_object = storage.get("ab/file.txt") assert file_object.read() == b"my contents" assert bucket.Object.calls == [pretend.call("ab/file.txt")]
TestS3FileStorage
python
graphql-python__graphene
graphene/types/tests/test_subscribe_async.py
{ "start": 87, "end": 202 }
class ____(ObjectType): hello = String() def resolve_hello(root, info): return "Hello, world!"
Query
python
ray-project__ray
rllib/examples/envs/classes/multi_agent/footsies/utils.py
{ "start": 805, "end": 2078 }
class ____: def __init__(self, matchups: list[Matchup]): self.matchups = matchups self.probs = [matchup.prob for matchup in matchups] self.current_matchups = collections.defaultdict(dict) def agent_to_module_mapping_fn( self, agent_id: str, episode: EpisodeType, **kwargs ) -> str: """Mapping function that retrieves policy_id from the sampled matchup""" id_ = episode.id_ if self.current_matchups.get(id_) is None: # step 1: sample a matchup according to the specified probabilities sampled_matchup = np.random.choice(a=self.matchups, p=self.probs) # step 2: Randomize who is player 1 and player 2 policies = [sampled_matchup.p1, sampled_matchup.p2] p1, p2 = np.random.choice(policies, size=2, replace=False) # step 3: Set as the current matchup for the episode in question (id_) self.current_matchups[id_]["p1"] = p1 self.current_matchups[id_]["p2"] = p2 policy_id = self.current_matchups[id_].pop(agent_id) # remove (an empty dict) for the current episode with id_ if not self.current_matchups[id_]: del self.current_matchups[id_] return policy_id
Matchmaker
python
ansible__ansible
test/units/inventory/test_data.py
{ "start": 2207, "end": 2419 }
class ____(Exception): """Raised when an object is trusted which should not be.""" def __init__(self, obj: t.Any) -> None: super().__init__(f'TrustedAsTemplate is tagged on {obj}.')
TrustFoundError
python
dask__dask
dask/dataframe/dask_expr/_backends.py
{ "start": 860, "end": 2055 }
class ____(DataFrameBackendEntrypoint): """Pandas-Backend Entrypoint Class for Dask-Expressions Note that all DataFrame-creation functions are defined and registered 'in-place'. """ @classmethod def to_backend(cls, data, **kwargs): from dask.dataframe.dask_expr._collection import new_collection return new_collection(ToPandasBackend(data, kwargs)) dataframe_creation_dispatch.register_backend("pandas", PandasBackendEntrypoint()) @get_collection_type.register(pd.Series) def get_collection_type_series(_): from dask.dataframe.dask_expr._collection import Series return Series @get_collection_type.register(pd.DataFrame) def get_collection_type_dataframe(_): from dask.dataframe.dask_expr._collection import DataFrame return DataFrame @get_collection_type.register(pd.Index) def get_collection_type_index(_): from dask.dataframe.dask_expr._collection import Index return Index ###################################### # cuDF: Pandas Dataframes on the GPU # ###################################### @get_collection_type.register_lazy("cudf") def _register_cudf(): import dask_cudf # noqa: F401
PandasBackendEntrypoint
python
apache__airflow
airflow-core/tests/unit/api_fastapi/auth/managers/simple/test_simple_auth_manager.py
{ "start": 1224, "end": 9651 }
class ____: def test_get_users(self, auth_manager): with conf_vars( { ("core", "simple_auth_manager_users"): "test1:viewer,test2:viewer", } ): users = auth_manager.get_users() assert users == [{"role": "viewer", "username": "test1"}, {"role": "viewer", "username": "test2"}] @pytest.mark.parametrize( ("file_content", "expected"), [ ("{}", {}), ("", {}), ('{"test1": "test1"}', {"test1": "test1"}), ('{"test1": "test1", "test2": "test2"}', {"test1": "test1", "test2": "test2"}), ], ) def test_get_passwords(self, auth_manager, file_content, expected): with conf_vars( { ("core", "simple_auth_manager_users"): "test1:viewer,test2:viewer", } ): with open(auth_manager.get_generated_password_file(), "w") as file: file.write(file_content) passwords = auth_manager.get_passwords() assert passwords == expected def test_init_with_default_user(self, auth_manager): auth_manager.init() with open(auth_manager.get_generated_password_file()) as file: passwords_str = file.read().strip() user_passwords_from_file = json.loads(passwords_str) assert len(user_passwords_from_file) == 1 def test_init_with_users(self, auth_manager): with conf_vars( { ("core", "simple_auth_manager_users"): "test1:viewer,test2:viewer", } ): auth_manager.init() with open(auth_manager.get_generated_password_file()) as file: passwords_str = file.read().strip() user_passwords_from_file = json.loads(passwords_str) assert len(user_passwords_from_file) == 2 @pytest.mark.parametrize( ("file_content", "expected"), [ ({"test1": "test1"}, {"test1": "test1"}), ({"test2": "test2", "test3": "test3"}, {"test1": mock.ANY, "test2": "test2", "test3": "test3"}), ], ) def test_init_with_users_with_password(self, auth_manager, file_content, expected): with conf_vars( { ("core", "simple_auth_manager_users"): "test1:viewer", } ): with open(auth_manager.get_generated_password_file(), "w") as file: file.write(json.dumps(file_content) + "\n") auth_manager.init() with open(auth_manager.get_generated_password_file()) as file: passwords_str = file.read().strip() user_passwords_from_file = json.loads(passwords_str) assert user_passwords_from_file == expected def test_init_with_all_admins(self, auth_manager): with conf_vars({("core", "simple_auth_manager_all_admins"): "true"}): auth_manager.init() assert not os.path.exists(auth_manager.get_generated_password_file()) def test_get_url_login(self, auth_manager): result = auth_manager.get_url_login() assert result == AUTH_MANAGER_FASTAPI_APP_PREFIX + "/login" def test_get_url_login_with_all_admins(self, auth_manager): with conf_vars({("core", "simple_auth_manager_all_admins"): "true"}): result = auth_manager.get_url_login() assert result == AUTH_MANAGER_FASTAPI_APP_PREFIX + "/token/login" def test_deserialize_user(self, auth_manager): result = auth_manager.deserialize_user({"sub": "test", "role": "admin"}) assert result.username == "test" assert result.role == "admin" def test_serialize_user(self, auth_manager): user = SimpleAuthManagerUser(username="test", role="admin") result = auth_manager.serialize_user(user) assert result == {"sub": "test", "role": "admin"} @pytest.mark.parametrize( "api", [ "is_authorized_configuration", "is_authorized_connection", "is_authorized_dag", "is_authorized_asset", "is_authorized_asset_alias", "is_authorized_backfill", "is_authorized_pool", "is_authorized_variable", ], ) @pytest.mark.parametrize( ("role", "method", "result"), [ ("ADMIN", "GET", True), ("ADMIN", "DELETE", True), ("VIEWER", "POST", False), ("VIEWER", "PUT", False), ("VIEWER", "DELETE", False), ], ) def test_is_authorized_methods(self, auth_manager, api, role, method, result): assert ( getattr(auth_manager, api)(method=method, user=SimpleAuthManagerUser(username="test", role=role)) is result ) @pytest.mark.parametrize( ("api", "kwargs"), [ ("is_authorized_view", {"access_view": AccessView.CLUSTER_ACTIVITY}), ( "is_authorized_custom_view", { "method": "GET", "resource_name": "test", }, ), ], ) @pytest.mark.parametrize( ("role", "result"), [ ("ADMIN", True), ("VIEWER", True), ("USER", True), ("OP", True), ], ) def test_is_authorized_view_methods(self, auth_manager, api, kwargs, role, result): assert ( getattr(auth_manager, api)(**kwargs, user=SimpleAuthManagerUser(username="test", role=role)) is result ) @pytest.mark.parametrize( "api", [ "is_authorized_configuration", "is_authorized_connection", "is_authorized_asset", "is_authorized_asset_alias", "is_authorized_backfill", "is_authorized_pool", "is_authorized_variable", ], ) @pytest.mark.parametrize( ("role", "method", "result"), [ ("ADMIN", "GET", True), ("OP", "DELETE", True), ("USER", "DELETE", False), ("VIEWER", "PUT", False), ], ) def test_is_authorized_methods_op_role_required(self, auth_manager, api, role, method, result): assert ( getattr(auth_manager, api)(method=method, user=SimpleAuthManagerUser(username="test", role=role)) is result ) @pytest.mark.parametrize( "api", ["is_authorized_dag"], ) @pytest.mark.parametrize( ("role", "method", "result"), [ ("ADMIN", "GET", True), ("OP", "DELETE", True), ("USER", "GET", True), ("USER", "DELETE", True), ("VIEWER", "PUT", False), ], ) def test_is_authorized_methods_user_role_required(self, auth_manager, api, role, method, result): assert ( getattr(auth_manager, api)(method=method, user=SimpleAuthManagerUser(username="test", role=role)) is result ) @pytest.mark.parametrize( "api", [ "is_authorized_dag", "is_authorized_asset", "is_authorized_asset_alias", "is_authorized_backfill", "is_authorized_pool", ], ) @pytest.mark.parametrize( ("role", "method", "result"), [ ("ADMIN", "GET", True), ("VIEWER", "GET", True), ("OP", "GET", True), ("USER", "GET", True), ("VIEWER", "POST", False), ], ) def test_is_authorized_methods_viewer_role_required_for_get( self, auth_manager, api, role, method, result ): assert ( getattr(auth_manager, api)(method=method, user=SimpleAuthManagerUser(username="test", role=role)) is result ) def test_is_authorized_team(self, auth_manager): result = auth_manager.is_authorized_team( method="GET", user=SimpleAuthManagerUser(username="test", role=None) ) assert result is True def test_filter_authorized_menu_items(self, auth_manager): items = [MenuItem.ASSETS] results = auth_manager.filter_authorized_menu_items( items, user=SimpleAuthManagerUser(username="test", role=None) ) assert results == items
TestSimpleAuthManager
python
pytorch__pytorch
test/torch_np/numpy_tests/linalg/test_linalg.py
{ "start": 23438, "end": 25328 }
class ____(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): # cond(x, p) for p in (None, 2, -2) def do(self, a, b, tags): c = asarray(a) # a might be a matrix if "size-0" in tags: assert_raises(LinAlgError, linalg.cond, c) return # +-2 norms s = linalg.svd(c, compute_uv=False) assert_almost_equal( linalg.cond(a), s[..., 0] / s[..., -1], single_decimal=5, double_decimal=11 ) assert_almost_equal( linalg.cond(a, 2), s[..., 0] / s[..., -1], single_decimal=5, double_decimal=11, ) assert_almost_equal( linalg.cond(a, -2), s[..., -1] / s[..., 0], single_decimal=5, double_decimal=11, ) # Other norms cinv = np.linalg.inv(c) assert_almost_equal( linalg.cond(a, 1), abs(c).sum(-2).max(-1) * abs(cinv).sum(-2).max(-1), single_decimal=5, double_decimal=11, ) assert_almost_equal( linalg.cond(a, -1), abs(c).sum(-2).min(-1) * abs(cinv).sum(-2).min(-1), single_decimal=5, double_decimal=11, ) assert_almost_equal( linalg.cond(a, np.inf), abs(c).sum(-1).max(-1) * abs(cinv).sum(-1).max(-1), single_decimal=5, double_decimal=11, ) assert_almost_equal( linalg.cond(a, -np.inf), abs(c).sum(-1).min(-1) * abs(cinv).sum(-1).min(-1), single_decimal=5, double_decimal=11, ) assert_almost_equal( linalg.cond(a, "fro"), np.sqrt((abs(c) ** 2).sum(-1).sum(-1) * (abs(cinv) ** 2).sum(-1).sum(-1)), single_decimal=5, double_decimal=11, )
CondCases
python
huggingface__transformers
src/transformers/generation/utils.py
{ "start": 10796, "end": 14042 }
class ____(ModelOutput): """ Outputs of decoder-only generation models, when using beam methods. Args: sequences (`torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`): The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter if all batches finished early due to the `eos_token_id`. sequences_scores (`torch.FloatTensor` of shape `(batch_size*num_return_sequences)`, *optional*, returned when `output_scores=True`): Final beam scores of the generated `sequences`. scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`): Beam transition scores for each vocabulary token at each generation step. Beam transition scores consisting of log probabilities of tokens conditioned on log softmax of previously generated tokens in this beam. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token), with each tensor of shape `(batch_size*num_beams, config.vocab_size)`. logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`): Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax) at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token), with each tensor of shape `(batch_size*num_beams, config.vocab_size)`. beam_indices (`torch.LongTensor`, *optional*, returned when `output_scores=True`): Beam indices of generated token id at each generation step. `torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`. attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`): Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of `torch.FloatTensor` of shape `(batch_size*num_beams, num_heads, generated_length, sequence_length)`. hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`): Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of `torch.FloatTensor` of shape `(batch_size*num_beams*num_return_sequences, generated_length, hidden_size)`. past_key_values (`Cache`, *optional*, returned when `use_cache=True`): Returns the model cache, used to speed up decoding. Different models have a different cache format, check the model's documentation. Usually, a [`~cache_utils.Cache`] instance. """ sequences: torch.LongTensor sequences_scores: torch.FloatTensor | None = None scores: tuple[torch.FloatTensor] | None = None logits: tuple[torch.FloatTensor] | None = None beam_indices: torch.LongTensor | None = None attentions: tuple[tuple[torch.FloatTensor]] | None = None hidden_states: tuple[tuple[torch.FloatTensor]] | None = None past_key_values: Cache | None = None @dataclass
GenerateBeamDecoderOnlyOutput
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 41021, "end": 41484 }
class ____(Blockwise): _parameters = ["frame", "index", "deep"] _defaults = {"index": True, "deep": False} @staticmethod def operation(*args, **kwargs): if is_series_like(args[0]): return args[0]._constructor([total_mem_usage(*args, **kwargs)]) return args[0]._constructor_sliced([total_mem_usage(*args, **kwargs)]) def _divisions(self): return (None,) * (self.frame.npartitions + 1)
MemoryUsagePerPartition
python
huggingface__transformers
src/transformers/models/qwen2_moe/modular_qwen2_moe.py
{ "start": 6968, "end": 10241 }
class ____(MixtralModel): def __init__(self, config: Qwen2MoeConfig): super().__init__(config) self.layers = nn.ModuleList( [Qwen2MoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.norm = Qwen2MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.rotary_emb = Qwen2MoeRotaryEmbedding(config=config) @check_model_inputs() @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> MoeModelOutputWithPast: if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) if use_cache and past_key_values is None: past_key_values = DynamicCache(config=self.config) if cache_position is None: past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 cache_position = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device ) if position_ids is None: position_ids = cache_position.unsqueeze(0) # It may already have been prepared by e.g. `generate` if not isinstance(causal_mask_mapping := attention_mask, dict): # Prepare mask arguments mask_kwargs = { "config": self.config, "input_embeds": inputs_embeds, "attention_mask": attention_mask, "cache_position": cache_position, "past_key_values": past_key_values, "position_ids": position_ids, } # Create the masks causal_mask_mapping = { "full_attention": create_causal_mask(**mask_kwargs), "sliding_attention": create_sliding_window_causal_mask(**mask_kwargs), } hidden_states = inputs_embeds position_embeddings = self.rotary_emb(hidden_states, position_ids) for i, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]): hidden_states = decoder_layer( hidden_states, attention_mask=causal_mask_mapping[self.config.layer_types[i]], position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, ) hidden_states = self.norm(hidden_states) return MoeModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=past_key_values if use_cache else None, )
Qwen2MoeModel
python
getlogbook__logbook
src/logbook/base.py
{ "start": 5547, "end": 8108 }
class ____(StackedObject): """An object that can be bound to a context. It is managed by the :class:`ContextStackManager`""" #: subclasses have to instantiate a :class:`ContextStackManager` #: object on this attribute which is then shared for all the #: subclasses of it. stack_manager = None @deprecated("Use push_context instead") def push_greenlet(self): """Pushes the context object to the greenlet stack. .. deprecated:: 1.9 Use :meth:`push_context` instead. """ self.stack_manager.push_context(self) @deprecated("Use pop_context instead") def pop_greenlet(self): """Pops the context object from the stack. .. deprecated:: 1.9 Use :meth:`pop_context` instead. """ popped = self.stack_manager.pop_context() assert popped is self, "popped unexpected object" def push_context(self): """Pushes the context object to the context stack.""" self.stack_manager.push_context(self) def pop_context(self): """Pops the context object from the stack.""" popped = self.stack_manager.pop_context() assert popped is self, "popped unexpected object" @deprecated("Use push_context instead") def push_thread(self): """Pushes the context object to the thread stack. .. deprecated:: 1.9 Use :meth:`push_context` instead. """ self.stack_manager.push_context(self) @deprecated("Use pop_context instead") def pop_thread(self): """Pops the context object from the stack. .. deprecated:: 1.9 Use :meth:`pop_context` instead. """ popped = self.stack_manager.pop_context() assert popped is self, "popped unexpected object" def push_application(self): """Pushes the context object to the application stack.""" self.stack_manager.push_application(self) def pop_application(self): """Pops the context object from the stack.""" popped = self.stack_manager.pop_application() assert popped is self, "popped unexpected object" @deprecated("`with obj.greenletbound()` is deprecated, use `with obj:` instead") def greenletbound(self): return self @deprecated("`with obj.contextbound()` is deprecated, use `with obj:` instead") def contextbound(self): return self @deprecated("`with obj.threadbound()` is deprecated, use `with obj:` instead") def threadbound(self): return self
ContextObject
python
ray-project__ray
python/ray/data/_internal/planner/exchange/split_repartition_task_scheduler.py
{ "start": 690, "end": 6640 }
class ____(ExchangeTaskScheduler): """ The split (non-shuffle) repartition scheduler. First, we calculate global splits needed to produce `output_num_blocks` blocks. After the split blocks are generated accordingly, reduce tasks are scheduled to combine split blocks together. """ def execute( self, refs: List[RefBundle], output_num_blocks: int, ctx: TaskContext, map_ray_remote_args: Optional[Dict[str, Any]] = None, reduce_ray_remote_args: Optional[Dict[str, Any]] = None, ) -> AllToAllTransformFnResult: input_num_rows = 0 input_owned_by_consumer = True for ref_bundle in refs: block_num_rows = ref_bundle.num_rows() if block_num_rows is None: raise ValueError( "Cannot split partition on blocks with unknown number of rows." ) input_num_rows += block_num_rows if not ref_bundle.owns_blocks: input_owned_by_consumer = False # Compute the (output_num_blocks) indices needed for an equal split of the # input blocks. When output_num_blocks=1, the total number of # input rows is used as the end index during the split calculation, # so that we can combine all input blocks into a single output block. indices = [] if output_num_blocks == 1: indices = [input_num_rows] else: cur_idx = 0 for _ in range(output_num_blocks - 1): cur_idx += input_num_rows / output_num_blocks indices.append(int(cur_idx)) assert len(indices) <= output_num_blocks, (indices, output_num_blocks) if map_ray_remote_args is None: map_ray_remote_args = {} if reduce_ray_remote_args is None: reduce_ray_remote_args = {} if "scheduling_strategy" not in reduce_ray_remote_args: reduce_ray_remote_args = reduce_ray_remote_args.copy() reduce_ray_remote_args["scheduling_strategy"] = "SPREAD" blocks_with_metadata: List[Tuple[ObjectRef[Block], BlockMetadata]] = [] for ref_bundle in refs: blocks_with_metadata.extend(ref_bundle.blocks) split_return = _split_at_indices( blocks_with_metadata, indices, input_owned_by_consumer ) split_block_refs, split_metadata = [], [] for b, m in zip(*split_return): split_block_refs.append(b) split_metadata.extend(m) sub_progress_bar_dict = ctx.sub_progress_bar_dict bar_name = ShuffleTaskSpec.SPLIT_REPARTITION_SUB_PROGRESS_BAR_NAME assert bar_name in sub_progress_bar_dict, sub_progress_bar_dict reduce_bar = sub_progress_bar_dict[bar_name] reduce_task = cached_remote_fn(self._exchange_spec.reduce) reduce_return = [ reduce_task.options(**reduce_ray_remote_args, num_returns=2).remote( *self._exchange_spec._reduce_args, *split_block_refs[j], ) for j in range(output_num_blocks) # Only process splits which contain blocks. if len(split_block_refs[j]) > 0 ] reduce_block_refs, reduce_metadata_schema = [], [] if reduce_return: reduce_block_refs, reduce_metadata_schema = unzip(reduce_return) reduce_metadata_schema: List[ "BlockMetadataWithSchema" ] = reduce_bar.fetch_until_complete(list(reduce_metadata_schema)) reduce_block_refs = list(reduce_block_refs) # Handle empty blocks. if len(reduce_block_refs) < output_num_blocks: import pyarrow as pa from ray.data._internal.arrow_block import ArrowBlockBuilder from ray.data._internal.pandas_block import ( PandasBlockBuilder, PandasBlockSchema, ) num_empty_blocks = output_num_blocks - len(reduce_block_refs) if len(reduce_metadata_schema) > 0: first_block_schema = reduce_metadata_schema[0].schema if isinstance(first_block_schema, pa.Schema): builder = ArrowBlockBuilder() elif isinstance(first_block_schema, PandasBlockSchema): builder = PandasBlockBuilder() else: raise ValueError( "Cannot split partition on blocks with unknown block schema:" f" {first_block_schema}." ) else: # If the result is empty, default to Arrow format for the empty blocks. builder = ArrowBlockBuilder() empty_block = builder.build() empty_meta_with_schema = BlockMetadataWithSchema.from_block( empty_block ) # No stats for empty block. empty_block_refs, empty_metadata = zip( *[ (ray.put(empty_block), empty_meta_with_schema) for _ in range(num_empty_blocks) ] ) reduce_block_refs.extend(empty_block_refs) reduce_metadata_schema.extend(empty_metadata) output = [] assert len(reduce_block_refs) == len(reduce_metadata_schema), ( len(reduce_block_refs), len(reduce_metadata_schema), ) for block, meta_with_schema in zip(reduce_block_refs, reduce_metadata_schema): output.append( RefBundle( [(block, meta_with_schema.metadata)], owns_blocks=input_owned_by_consumer, schema=meta_with_schema.schema, ) ) stats = { "split": split_metadata, "reduce": reduce_metadata_schema, } return (output, stats)
SplitRepartitionTaskScheduler
python
django__django
django/db/migrations/serializer.py
{ "start": 1030, "end": 1265 }
class ____: def __init__(self, value): self.value = value def serialize(self): raise NotImplementedError( "Subclasses of BaseSerializer must implement the serialize() method." )
BaseSerializer
python
pydata__xarray
xarray/indexes/nd_point_index.py
{ "start": 539, "end": 2089 }
class ____(abc.ABC): """Lightweight adapter abstract class for plugging in 3rd-party structures like :py:class:`scipy.spatial.KDTree` or :py:class:`sklearn.neighbors.KDTree` into :py:class:`~xarray.indexes.NDPointIndex`. """ @abc.abstractmethod def __init__(self, points: np.ndarray, *, options: Mapping[str, Any]): """ Parameters ---------- points : ndarray of shape (n_points, n_coordinates) Two-dimensional array of points/samples (rows) and their corresponding coordinate labels (columns) to index. """ ... @abc.abstractmethod def query(self, points: np.ndarray) -> tuple[np.ndarray, np.ndarray]: """Query points. Parameters ---------- points: ndarray of shape (n_points, n_coordinates) Two-dimensional array of points/samples (rows) and their corresponding coordinate labels (columns) to query. Returns ------- distances : ndarray of shape (n_points) Distances to the nearest neighbors. indices : ndarray of shape (n_points) Indices of the nearest neighbors in the array of the indexed points. """ ... def equals(self, other: Self) -> bool: """Check equality with another TreeAdapter of the same kind. Parameters ---------- other : The other TreeAdapter object to compare with this object. """ raise NotImplementedError
TreeAdapter
python
ray-project__ray
python/ray/data/block.py
{ "start": 8705, "end": 21692 }
class ____: """Provides accessor methods for a specific block. Ideally, we wouldn't need a separate accessor classes for blocks. However, this is needed if we want to support storing ``pyarrow.Table`` directly as a top-level Ray object, without a wrapping class (issue #17186). """ def num_rows(self) -> int: """Return the number of rows contained in this block.""" raise NotImplementedError def iter_rows(self, public_row_format: bool) -> Iterator[T]: """Iterate over the rows of this block. Args: public_row_format: Whether to cast rows into the public Dict row format (this incurs extra copy conversions). """ raise NotImplementedError def slice(self, start: int, end: int, copy: bool = False) -> Block: """Return a slice of this block. Args: start: The starting index of the slice (inclusive). end: The ending index of the slice (exclusive). copy: Whether to perform a data copy for the slice. Returns: The sliced block result. """ raise NotImplementedError def take(self, indices: List[int]) -> Block: """Return a new block containing the provided row indices. Args: indices: The row indices to return. Returns: A new block containing the provided row indices. """ raise NotImplementedError def drop(self, columns: List[str]) -> Block: """Return a new block with the list of provided columns dropped""" raise NotImplementedError def select(self, columns: List[Optional[str]]) -> Block: """Return a new block containing the provided columns.""" raise NotImplementedError def rename_columns(self, columns_rename: Dict[str, str]) -> Block: """Return the block reflecting the renamed columns.""" raise NotImplementedError def upsert_column(self, column_name: str, column_data: BlockColumn) -> Block: """ Upserts a column into the block. If the column already exists, it will be replaced. Args: column_name: The name of the column to upsert. column_data: The data to upsert into the column. (Arrow Array/ChunkedArray for Arrow blocks, Series or array-like for Pandas blocks) Returns: The updated block. """ raise NotImplementedError() def random_shuffle(self, random_seed: Optional[int]) -> Block: """Randomly shuffle this block.""" raise NotImplementedError def to_pandas(self) -> "pandas.DataFrame": """Convert this block into a Pandas dataframe.""" raise NotImplementedError def to_numpy( self, columns: Optional[Union[str, List[str]]] = None ) -> Union[np.ndarray, Dict[str, np.ndarray]]: """Convert this block (or columns of block) into a NumPy ndarray. Args: columns: Name of columns to convert, or None if converting all columns. """ raise NotImplementedError def to_arrow(self) -> "pyarrow.Table": """Convert this block into an Arrow table.""" raise NotImplementedError def to_block(self) -> Block: """Return the base block that this accessor wraps.""" raise NotImplementedError def to_default(self) -> Block: """Return the default data format for this accessor.""" return self.to_block() def to_batch_format(self, batch_format: Optional[str]) -> DataBatch: """Convert this block into the provided batch format. Args: batch_format: The batch format to convert this block to. Returns: This block formatted as the provided batch format. """ if batch_format is None: return self.to_block() elif batch_format == "default" or batch_format == "native": return self.to_default() elif batch_format == "pandas": return self.to_pandas() elif batch_format == "pyarrow": return self.to_arrow() elif batch_format == "numpy": return self.to_numpy() else: raise ValueError( f"The batch format must be one of {VALID_BATCH_FORMATS}, got: " f"{batch_format}" ) def size_bytes(self) -> int: """Return the approximate size in bytes of this block.""" raise NotImplementedError def schema(self) -> Union[type, "pyarrow.lib.Schema"]: """Return the Python type or pyarrow schema of this block.""" raise NotImplementedError def get_metadata( self, input_files: Optional[List[str]] = None, exec_stats: Optional[BlockExecStats] = None, ) -> BlockMetadata: """Create a metadata object from this block.""" return BlockMetadata( num_rows=self.num_rows(), size_bytes=self.size_bytes(), input_files=input_files, exec_stats=exec_stats, ) def zip(self, other: "Block") -> "Block": """Zip this block with another block of the same type and size.""" raise NotImplementedError @staticmethod def builder() -> "BlockBuilder": """Create a builder for this block type.""" raise NotImplementedError @classmethod def batch_to_block( cls, batch: DataBatch, block_type: Optional[BlockType] = None, ) -> Block: """Create a block from user-facing data formats.""" if isinstance(batch, np.ndarray): raise ValueError( f"Error validating {_truncated_repr(batch)}: " "Standalone numpy arrays are not " "allowed in Ray 2.5. Return a dict of field -> array, " "e.g., `{'data': array}` instead of `array`." ) elif isinstance(batch, collections.abc.Mapping): if block_type is None or block_type == BlockType.ARROW: from ray.air.util.tensor_extensions.arrow import ArrowConversionError try: return cls.batch_to_arrow_block(batch) except ArrowConversionError as e: if log_once("_fallback_to_pandas_block_warning"): logger.warning( f"Failed to convert batch to Arrow due to: {e}; " f"falling back to Pandas block" ) if block_type is None: return cls.batch_to_pandas_block(batch) else: raise e else: assert block_type == BlockType.PANDAS return cls.batch_to_pandas_block(batch) return batch @classmethod def batch_to_arrow_block(cls, batch: Dict[str, Any]) -> Block: """Create an Arrow block from user-facing data formats.""" from ray.data._internal.arrow_block import ArrowBlockBuilder return ArrowBlockBuilder._table_from_pydict(batch) @classmethod def batch_to_pandas_block(cls, batch: Dict[str, Any]) -> Block: """Create a Pandas block from user-facing data formats.""" from ray.data._internal.pandas_block import PandasBlockBuilder return PandasBlockBuilder._table_from_pydict(batch) @staticmethod def for_block(block: Block) -> "BlockAccessor[T]": """Create a block accessor for the given block.""" _check_pyarrow_version() import pandas import pyarrow if isinstance(block, (pyarrow.Table, pyarrow.RecordBatch)): from ray.data._internal.arrow_block import ArrowBlockAccessor return ArrowBlockAccessor(block) elif isinstance(block, pandas.DataFrame): from ray.data._internal.pandas_block import PandasBlockAccessor return PandasBlockAccessor(block) elif isinstance(block, bytes): from ray.data._internal.arrow_block import ArrowBlockAccessor return ArrowBlockAccessor.from_bytes(block) elif isinstance(block, list): raise ValueError( f"Error validating {_truncated_repr(block)}: " "Standalone Python objects are not " "allowed in Ray 2.5. To use Python objects in a dataset, " "wrap them in a dict of numpy arrays, e.g., " "return `{'item': batch}` instead of just `batch`." ) else: raise TypeError("Not a block type: {} ({})".format(block, type(block))) def sample(self, n_samples: int, sort_key: "SortKey") -> "Block": """Return a random sample of items from this block.""" raise NotImplementedError def count(self, on: str, ignore_nulls: bool = False) -> Optional[U]: """Returns a count of the distinct values in the provided column""" raise NotImplementedError def sum(self, on: str, ignore_nulls: bool) -> Optional[U]: """Returns a sum of the values in the provided column""" raise NotImplementedError def min(self, on: str, ignore_nulls: bool) -> Optional[U]: """Returns a min of the values in the provided column""" raise NotImplementedError def max(self, on: str, ignore_nulls: bool) -> Optional[U]: """Returns a max of the values in the provided column""" raise NotImplementedError def mean(self, on: str, ignore_nulls: bool) -> Optional[U]: """Returns a mean of the values in the provided column""" raise NotImplementedError def sum_of_squared_diffs_from_mean( self, on: str, ignore_nulls: bool, mean: Optional[U] = None, ) -> Optional[U]: """Returns a sum of diffs (from mean) squared for the provided column""" raise NotImplementedError def sort(self, sort_key: "SortKey") -> "Block": """Returns new block sorted according to provided `sort_key`""" raise NotImplementedError def sort_and_partition( self, boundaries: List[T], sort_key: "SortKey" ) -> List["Block"]: """Return a list of sorted partitions of this block.""" raise NotImplementedError def _aggregate(self, key: "SortKey", aggs: Tuple["AggregateFn"]) -> Block: """Combine rows with the same key into an accumulator.""" raise NotImplementedError @staticmethod def merge_sorted_blocks( blocks: List["Block"], sort_key: "SortKey" ) -> Tuple[Block, BlockMetadataWithSchema]: """Return a sorted block by merging a list of sorted blocks.""" raise NotImplementedError @staticmethod def _combine_aggregated_blocks( blocks: List[Block], sort_key: "SortKey", aggs: Tuple["AggregateFn"], finalize: bool = True, ) -> Tuple[Block, BlockMetadataWithSchema]: """Aggregate partially combined and sorted blocks.""" raise NotImplementedError def _find_partitions_sorted( self, boundaries: List[Tuple[Any]], sort_key: "SortKey", ) -> List[Block]: """NOTE: PLEASE READ CAREFULLY Returns dataset partitioned using list of boundaries This method requires that - Block being sorted (according to `sort_key`) - Boundaries is a sorted list of tuples """ raise NotImplementedError def block_type(self) -> BlockType: """Return the block type of this block.""" raise NotImplementedError def _get_group_boundaries_sorted(self, keys: List[str]) -> np.ndarray: """ NOTE: THIS METHOD ASSUMES THAT PROVIDED BLOCK IS ALREADY SORTED Compute boundaries of the groups within a block based on provided key (a column or a list of columns) NOTE: In each column, NaNs/None are considered to be the same group. Args: block: sorted block for which grouping of rows will be determined based on provided key keys: list of columns determining the key for every row based on which the block will be grouped Returns: A list of starting indices of each group and an end index of the last group, i.e., there are ``num_groups + 1`` entries and the first and last entries are 0 and ``len(array)`` respectively. """ if self.num_rows() == 0: return np.array([], dtype=np.int32) elif not keys: # If no keys are specified, whole block is considered a single group return np.array([0, self.num_rows()]) # Convert key columns to Numpy (to perform vectorized # ops on them) projected_block = self.to_numpy(keys) return _get_group_boundaries_sorted_numpy(list(projected_block.values())) @DeveloperAPI(stability="beta")
BlockAccessor
python
dagster-io__dagster
python_modules/libraries/dagster-aws/dagster_aws_tests/s3_tests/test_compute_log_manager.py
{ "start": 9978, "end": 12312 }
class ____(TestComputeLogManager): __test__ = True @pytest.fixture(name="compute_log_manager") def compute_log_manager(self, mock_s3_bucket): with tempfile.TemporaryDirectory() as temp_dir: yield S3ComputeLogManager( bucket=mock_s3_bucket.name, prefix="my_prefix", local_dir=temp_dir ) # for streaming tests @pytest.fixture(name="write_manager") def write_manager(self, mock_s3_bucket): # should be a different local directory as the read manager with tempfile.TemporaryDirectory() as temp_dir: yield S3ComputeLogManager( bucket=mock_s3_bucket.name, prefix="my_prefix", local_dir=temp_dir, upload_interval=1, ) @pytest.fixture(name="read_manager") def read_manager(self, mock_s3_bucket): # should be a different local directory as the write manager with tempfile.TemporaryDirectory() as temp_dir: yield S3ComputeLogManager( bucket=mock_s3_bucket.name, prefix="my_prefix", local_dir=temp_dir ) def test_external_compute_log_manager(mock_s3_bucket): @op def my_op(): print("hello out") # noqa: T201 print("hello error", file=sys.stderr) # noqa: T201 @job def my_job(): my_op() with instance_for_test( overrides={ "compute_logs": { "module": "dagster_aws.s3.compute_log_manager", "class": "S3ComputeLogManager", "config": { "bucket": mock_s3_bucket.name, "show_url_only": True, }, }, }, ) as instance: result = my_job.execute_in_process(instance=instance) assert result.success assert result.run_id captured_log_entries = instance.all_logs( result.run_id, of_type=DagsterEventType.LOGS_CAPTURED ) assert len(captured_log_entries) == 1 entry = captured_log_entries[0] assert entry.dagster_event.logs_captured_data.external_stdout_url # pyright: ignore[reportOptionalMemberAccess] assert entry.dagster_event.logs_captured_data.external_stderr_url # pyright: ignore[reportOptionalMemberAccess]
TestS3ComputeLogManager
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_arxiv_id.py
{ "start": 1687, "end": 3951 }
class ____(ColumnMapExpectation): """Expect column values to be valid arXiv identifiers.""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "well_formed_arxiv_id": [ "hep-th/9108001", "math/9910001v1", "1706.03762", "0706.1234v1", ], "malformed_arxiv_id": [ "", "2202.100001", "7001.12345", "This is not a valid arXiv id", ], }, "tests": [ { "title": "basic_positive_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "well_formed_arxiv_id"}, "out": {"success": True}, }, { "title": "basic_negative_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "malformed_arxiv_id"}, "out": {"success": False}, }, ], } ] # This is the id string of the Metric used by this Expectation. # For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above. map_metric = "column_values.valid_arxiv_id" # This is a list of parameter names that can affect whether the Expectation evaluates to True or False success_keys = ("mostly",) # This dictionary contains default values for any parameters that should have default values default_kwarg_values = {} # This object contains metadata for display in the public Gallery library_metadata = { "maturity": "experimental", "tags": ["experimental", "hackathon", "typed-entities"], "contributors": [ "@voidforall", ], "requirements": ["arxiv"], } if __name__ == "__main__": ExpectColumnValuesToBeValidArxivId().print_diagnostic_checklist()
ExpectColumnValuesToBeValidArxivId
python
great-expectations__great_expectations
great_expectations/expectations/metrics/column_aggregate_metrics/column_partition.py
{ "start": 889, "end": 9592 }
class ____(ColumnAggregateMetricProvider): metric_name = "column.partition" value_keys = ("bins", "n_bins", "allow_relative_error") default_kwarg_values = { "bins": "uniform", "n_bins": 10, "allow_relative_error": False, } @metric_value(engine=PandasExecutionEngine) def _pandas( cls, execution_engine: PandasExecutionEngine, metric_domain_kwargs: dict, metric_value_kwargs: dict, metrics: Dict[str, Any], runtime_configuration: dict, ): bins = metric_value_kwargs.get("bins", cls.default_kwarg_values["bins"]) n_bins = metric_value_kwargs.get("n_bins", cls.default_kwarg_values["n_bins"]) return _get_column_partition_using_metrics(bins=bins, n_bins=n_bins, _metrics=metrics) @metric_value(engine=SqlAlchemyExecutionEngine) def _sqlalchemy( cls, execution_engine: PandasExecutionEngine, metric_domain_kwargs: dict, metric_value_kwargs: dict, metrics: Dict[str, Any], runtime_configuration: dict, ): bins = metric_value_kwargs.get("bins", cls.default_kwarg_values["bins"]) n_bins = metric_value_kwargs.get("n_bins", cls.default_kwarg_values["n_bins"]) return _get_column_partition_using_metrics(bins=bins, n_bins=n_bins, _metrics=metrics) @metric_value(engine=SparkDFExecutionEngine) def _spark( cls, execution_engine: PandasExecutionEngine, metric_domain_kwargs: dict, metric_value_kwargs: dict, metrics: Dict[str, Any], runtime_configuration: dict, ): bins = metric_value_kwargs.get("bins", cls.default_kwarg_values["bins"]) n_bins = metric_value_kwargs.get("n_bins", cls.default_kwarg_values["n_bins"]) return _get_column_partition_using_metrics(bins=bins, n_bins=n_bins, _metrics=metrics) @classmethod @override def _get_evaluation_dependencies( cls, metric: MetricConfiguration, configuration: Optional[ExpectationConfiguration] = None, execution_engine: Optional[ExecutionEngine] = None, runtime_configuration: Optional[dict] = None, ): bins = metric.metric_value_kwargs.get("bins", cls.default_kwarg_values["bins"]) n_bins = metric.metric_value_kwargs.get("n_bins", cls.default_kwarg_values["n_bins"]) allow_relative_error = metric.metric_value_kwargs["allow_relative_error"] dependencies: dict = super()._get_evaluation_dependencies( metric=metric, configuration=configuration, execution_engine=execution_engine, runtime_configuration=runtime_configuration, ) if bins == "uniform": dependencies["column.min"] = MetricConfiguration( metric_name="column.min", metric_domain_kwargs=metric.metric_domain_kwargs, ) dependencies["column.max"] = MetricConfiguration( metric_name="column.max", metric_domain_kwargs=metric.metric_domain_kwargs, ) elif bins in ["ntile", "quantile", "percentile"]: dependencies["column.quantile_values"] = MetricConfiguration( metric_name="column.quantile_values", metric_domain_kwargs=metric.metric_domain_kwargs, metric_value_kwargs={ "quantiles": np.linspace(start=0, stop=1, num=n_bins + 1).tolist(), "allow_relative_error": allow_relative_error, }, ) elif bins == "auto": dependencies["column_values.nonnull.count"] = MetricConfiguration( metric_name="column_values.nonnull.count", metric_domain_kwargs=metric.metric_domain_kwargs, ) dependencies["column.quantile_values"] = MetricConfiguration( metric_name="column.quantile_values", metric_domain_kwargs=metric.metric_domain_kwargs, metric_value_kwargs={ "quantiles": (0.0, 0.25, 0.75, 1.0), "allow_relative_error": allow_relative_error, }, ) else: raise ValueError("Invalid parameter for bins argument") # noqa: TRY003 # FIXME CoP return dependencies def _get_column_partition_using_metrics( bins: Literal["uniform", "ntile", "quantile", "percentile", "auto"], n_bins: int, _metrics: dict, ) -> list | npt.NDArray: result_bins: list | npt.NDArray if bins == "uniform": min_ = _metrics["column.min"] max_ = _metrics["column.max"] original_ndarray_is_datetime_type: bool conversion_ndarray_to_datetime_type_performed: bool min_max_values: npt.NDArray | list ( original_ndarray_is_datetime_type, conversion_ndarray_to_datetime_type_performed, min_max_values, ) = convert_ndarray_to_datetime_dtype_best_effort( data=[min_, max_], # type: ignore[arg-type] # expects NDArray parse_strings_as_datetimes=True, ) ndarray_is_datetime_type: bool = ( original_ndarray_is_datetime_type or conversion_ndarray_to_datetime_type_performed ) min_ = min_max_values[0] max_ = min_max_values[1] result_bins = _determine_bins_using_proper_units( # type: ignore[assignment] # TODO: ensure not None ndarray_is_datetime_type=ndarray_is_datetime_type, n_bins=n_bins, min_=min_, max_=max_, ) elif bins in ["ntile", "quantile", "percentile"]: result_bins = _metrics["column.quantile_values"] elif bins == "auto": # Use the method from numpy histogram_bin_edges nonnull_count = _metrics["column_values.nonnull.count"] sturges = np.log2(1.0 * nonnull_count + 1.0) min_, _25, _75, max_ = _metrics["column.quantile_values"] box_plot_values: npt.NDArray ( original_ndarray_is_datetime_type, conversion_ndarray_to_datetime_type_performed, box_plot_values, ) = convert_ndarray_to_datetime_dtype_best_effort( data=[min_, _25, _75, max_], # type: ignore[arg-type] # expects NDArray parse_strings_as_datetimes=True, ) ndarray_is_datetime_type = ( original_ndarray_is_datetime_type or conversion_ndarray_to_datetime_type_performed ) min_ = box_plot_values[0] _25 = box_plot_values[1] _75 = box_plot_values[2] max_ = box_plot_values[3] if ndarray_is_datetime_type: iqr = _75.timestamp() - _25.timestamp() min_as_float_ = min_.timestamp() max_as_float_ = max_.timestamp() else: iqr = _75 - _25 min_as_float_ = min_ max_as_float_ = max_ if ( iqr < 1.0e-10 # noqa: PLR2004 # FIXME CoP ): # Consider IQR 0 and do not use variance-based estimator n_bins = int(np.ceil(sturges)) else: # noqa: PLR5501 # FIXME CoP if nonnull_count == 0: n_bins = 0 else: fd = (2 * float(iqr)) / (nonnull_count ** (1.0 / 3.0)) n_bins = max( int(np.ceil(sturges)), int(np.ceil(float(max_as_float_ - min_as_float_) / fd)), ) result_bins = _determine_bins_using_proper_units( # type: ignore[assignment] # need overloads to ensure not None ndarray_is_datetime_type=ndarray_is_datetime_type, n_bins=n_bins, min_=min_, max_=max_, ) else: raise ValueError("Invalid parameter for bins argument") # noqa: TRY003 # FIXME CoP return result_bins def _determine_bins_using_proper_units( ndarray_is_datetime_type: bool, n_bins: int, min_: Any, max_: Any ) -> list | npt.NDArray | None: if ndarray_is_datetime_type: if n_bins == 0: bins = [min_] else: delta_t = (max_ - min_) / n_bins bins = [] for idx in range(n_bins + 1): bins.append(min_ + idx * delta_t) else: # PRECISION NOTE: some implementations of quantiles could produce # varying levels of precision (e.g. a NUMERIC column producing # Decimal from a SQLAlchemy source, so we cast to float for numpy) if min_ is None or max_ is None: return None bins = np.linspace(start=float(min_), stop=float(max_), num=n_bins + 1).tolist() return bins
ColumnPartition
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 879138, "end": 879493 }
class ____(sgqlc.types.Type, ProjectV2FieldCommon, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("configuration",) configuration = sgqlc.types.Field( sgqlc.types.non_null(ProjectV2IterationFieldConfiguration), graphql_name="configuration", )
ProjectV2IterationField
python
apache__airflow
providers/standard/src/airflow/providers/standard/sensors/time_delta.py
{ "start": 1615, "end": 5591 }
class ____(BaseSensorOperator): """ Waits for a timedelta. The delta will be evaluated against data_interval_end if present for the dag run, otherwise run_after will be used. :param delta: time to wait before succeeding. :param deferrable: Run sensor in deferrable mode. If set to True, task will defer itself to avoid taking up a worker slot while it is waiting. .. seealso:: For more information on how to use this sensor, take a look at the guide: :ref:`howto/operator:TimeDeltaSensor` """ def __init__( self, *, delta: timedelta, deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False), end_from_trigger: bool = False, **kwargs, ): super().__init__(**kwargs) self.delta = delta self.deferrable = deferrable self.end_from_trigger = end_from_trigger def _derive_base_time(self, context: Context) -> datetime: """ Get the "base time" against which the delta should be calculated. If data_interval_end is populated, use it; else use run_after. """ data_interval_end = context.get("data_interval_end") if data_interval_end: if not isinstance(data_interval_end, datetime): raise ValueError("`data_interval_end` returned non-datetime object") return data_interval_end if not data_interval_end and not AIRFLOW_V_3_0_PLUS: raise ValueError("`data_interval_end` not found in task context.") dag_run = context.get("dag_run") if not dag_run: raise ValueError("`dag_run` not found in task context") return dag_run.run_after def poke(self, context: Context) -> bool: base_time = self._derive_base_time(context=context) target_dttm = base_time + self.delta self.log.info("Checking if the delta has elapsed base_time=%s, delta=%s", base_time, self.delta) return timezone.utcnow() > target_dttm """ Asynchronous execution """ def execute(self, context: Context) -> Any: """ Depending on the deferrable flag, either execute the sensor in a blocking way or defer it. - Sync path → use BaseSensorOperator.execute() which loops over ``poke``. - Async path → defer to DateTimeTrigger and free the worker slot. """ if not self.deferrable: return super().execute(context=context) # Deferrable path base_time = self._derive_base_time(context=context) target_dttm: datetime = base_time + self.delta if timezone.utcnow() > target_dttm: # If the target datetime is in the past, return immediately return True try: if AIRFLOW_V_3_0_PLUS: trigger = DateTimeTrigger(moment=target_dttm, end_from_trigger=self.end_from_trigger) else: trigger = DateTimeTrigger(moment=target_dttm) except (TypeError, ValueError) as e: if self.soft_fail: raise AirflowSkipException("Skipping due to soft_fail is set to True.") from e raise # todo: remove backcompat when min airflow version greater than 2.11 timeout: int | float | timedelta if AIRFLOW_V_3_0_PLUS: timeout = self.timeout else: # <=2.11 requires timedelta timeout = timedelta(seconds=self.timeout) self.defer( trigger=trigger, method_name="execute_complete", timeout=timeout, ) def execute_complete(self, context: Context, event: Any = None) -> None: """Handle the event when the trigger fires and return immediately.""" return None # TODO: Remove in the next major release @deprecated( "Use `TimeDeltaSensor` with `deferrable=True` instead", category=AirflowProviderDeprecationWarning )
TimeDeltaSensor
python
Textualize__textual
src/textual/theme.py
{ "start": 8449, "end": 9339 }
class ____(Provider): """A provider for themes.""" @property def commands(self) -> list[tuple[str, Callable[[], None]]]: themes = self.app.available_themes def set_app_theme(name: str) -> None: self.app.theme = name return [ (theme.name, partial(set_app_theme, theme.name)) for theme in themes.values() if theme.name != "textual-ansi" ] async def discover(self) -> Hits: for command in self.commands: yield DiscoveryHit(*command) async def search(self, query: str) -> Hits: matcher = self.matcher(query) for name, callback in self.commands: if (match := matcher.match(name)) > 0: yield Hit( match, matcher.highlight(name), callback, )
ThemeProvider
python
fluentpython__example-code
09-pythonic-obj/vector2d_v3.py
{ "start": 1779, "end": 3249 }
class ____: typecode = 'd' def __init__(self, x, y): self.__x = float(x) self.__y = float(y) @property def x(self): return self.__x @property def y(self): return self.__y def __iter__(self): return (i for i in (self.x, self.y)) def __repr__(self): class_name = type(self).__name__ return '{}({!r}, {!r})'.format(class_name, *self) def __str__(self): return str(tuple(self)) def __bytes__(self): return (bytes([ord(self.typecode)]) + bytes(array(self.typecode, self))) def __eq__(self, other): return tuple(self) == tuple(other) def __hash__(self): return hash(self.x) ^ hash(self.y) def __abs__(self): return math.hypot(self.x, self.y) def __bool__(self): return bool(abs(self)) def angle(self): return math.atan2(self.y, self.x) def __format__(self, fmt_spec=''): if fmt_spec.endswith('p'): fmt_spec = fmt_spec[:-1] coords = (abs(self), self.angle()) outer_fmt = '<{}, {}>' else: coords = self outer_fmt = '({}, {})' components = (format(c, fmt_spec) for c in coords) return outer_fmt.format(*components) @classmethod def frombytes(cls, octets): typecode = chr(octets[0]) memv = memoryview(octets[1:]).cast(typecode) return cls(*memv)
Vector2d
python
tensorflow__tensorflow
tensorflow/lite/python/interpreter.py
{ "start": 6604, "end": 12011 }
class ____: """SignatureRunner class for running TFLite models using SignatureDef. This class should be instantiated through TFLite Interpreter only using get_signature_runner method on Interpreter. Example, signature = interpreter.get_signature_runner("my_signature") result = signature(input_1=my_input_1, input_2=my_input_2) print(result["my_output"]) print(result["my_second_output"]) All names used are this specific SignatureDef names. Notes: No other function on this object or on the interpreter provided should be called while this object call has not finished. """ def __init__(self, interpreter=None, signature_key=None): """Constructor. Args: interpreter: Interpreter object that is already initialized with the requested model. signature_key: SignatureDef key to be used. """ if not interpreter: raise ValueError('None interpreter provided.') if not signature_key: raise ValueError('None signature_key provided.') self._interpreter = interpreter self._interpreter_wrapper = interpreter._interpreter self._signature_key = signature_key signature_defs = interpreter._get_full_signature_list() if signature_key not in signature_defs: raise ValueError(f'Invalid signature_key provided: "{signature_key}".') self._signature_def = signature_defs[signature_key] self._outputs = self._signature_def['outputs'].items() self._inputs = self._signature_def['inputs'] self._subgraph_index = ( self._interpreter_wrapper.GetSubgraphIndexFromSignature( self._signature_key)) def __call__(self, **kwargs): """Runs the SignatureDef given the provided inputs in arguments. Args: **kwargs: key,value for inputs to the model. Key is the SignatureDef input name. Value is numpy array with the value. Returns: dictionary of the results from the model invoke. Key in the dictionary is SignatureDef output name. Value is the result Tensor. """ if len(kwargs) != len(self._inputs): raise ValueError( 'Invalid number of inputs provided for running a SignatureDef, ' 'expected %s vs provided %s' % (len(self._inputs), len(kwargs))) # Resize input tensors for input_name, value in kwargs.items(): if input_name not in self._inputs: raise ValueError('Invalid Input name (%s) for SignatureDef' % input_name) self._interpreter_wrapper.ResizeInputTensor( self._inputs[input_name], np.array(value.shape, dtype=np.int32), False, self._subgraph_index) # Allocate tensors. self._interpreter_wrapper.AllocateTensors(self._subgraph_index) # Set the input values. for input_name, value in kwargs.items(): self._interpreter_wrapper.SetTensor(self._inputs[input_name], value, self._subgraph_index) self._interpreter_wrapper.Invoke(self._subgraph_index) result = {} for output_name, output_index in self._outputs: result[output_name] = self._interpreter_wrapper.GetTensor( output_index, self._subgraph_index) return result def get_input_details(self): """Gets input tensor details. Returns: A dictionary from input name to tensor details where each item is a dictionary with details about an input tensor. Each dictionary contains the following fields that describe the tensor: + `name`: The tensor name. + `index`: The tensor index in the interpreter. + `shape`: The shape of the tensor. + `shape_signature`: Same as `shape` for models with known/fixed shapes. If any dimension sizes are unknown, they are indicated with `-1`. + `dtype`: The numpy data type (such as `np.int32` or `np.uint8`). + `quantization`: Deprecated, use `quantization_parameters`. This field only works for per-tensor quantization, whereas `quantization_parameters` works in all cases. + `quantization_parameters`: A dictionary of parameters used to quantize the tensor: ~ `scales`: List of scales (one if per-tensor quantization). ~ `zero_points`: List of zero_points (one if per-tensor quantization). ~ `quantized_dimension`: Specifies the dimension of per-axis quantization, in the case of multiple scales/zero_points. + `sparsity_parameters`: A dictionary of parameters used to encode a sparse tensor. This is empty if the tensor is dense. """ result = {} for input_name, tensor_index in self._inputs.items(): result[input_name] = self._interpreter._get_tensor_details( # pylint: disable=protected-access tensor_index, self._subgraph_index) return result def get_output_details(self): """Gets output tensor details. Returns: A dictionary from input name to tensor details where each item is a dictionary with details about an output tensor. The dictionary contains the same fields as described for `get_input_details()`. """ result = {} for output_name, tensor_index in self._outputs: result[output_name] = self._interpreter._get_tensor_details( # pylint: disable=protected-access tensor_index, self._subgraph_index) return result @_tf_export('lite.experimental.OpResolverType') @enum.unique
SignatureRunner
python
sympy__sympy
sympy/physics/mechanics/loads.py
{ "start": 819, "end": 2301 }
class ____(LoadBase): """Force acting upon a point. Explanation =========== A force is a vector that is bound to a line of action. This class stores both a point, which lies on the line of action, and the vector. A tuple can also be used, with the location as the first entry and the vector as second entry. Examples ======== A force of magnitude 2 along N.x acting on a point Po can be created as follows: >>> from sympy.physics.mechanics import Point, ReferenceFrame, Force >>> N = ReferenceFrame('N') >>> Po = Point('Po') >>> Force(Po, 2 * N.x) (Po, 2*N.x) If a body is supplied, then the center of mass of that body is used. >>> from sympy.physics.mechanics import Particle >>> P = Particle('P', point=Po) >>> Force(P, 2 * N.x) (Po, 2*N.x) """ def __new__(cls, point, force): if isinstance(point, BodyBase): point = point.masscenter if not isinstance(point, Point): raise TypeError('Force location should be a Point.') if not isinstance(force, Vector): raise TypeError('Force vector should be a Vector.') return super().__new__(cls, point, force) def __repr__(self): return (f'{self.__class__.__name__}(point={self.point}, ' f'force={self.force})') @property def point(self): return self.location @property def force(self): return self.vector
Force
python
coleifer__peewee
peewee.py
{ "start": 53217, "end": 53955 }
class ____(ColumnBase): def __init__(self, predicate, expression_tuples, default=None): self.predicate = predicate self.expression_tuples = expression_tuples self.default = default def __sql__(self, ctx): clauses = [SQL('CASE')] if self.predicate is not None: clauses.append(self.predicate) for expr, value in self.expression_tuples: clauses.extend((SQL('WHEN'), expr, SQL('THEN'), _InFunction(value))) if self.default is not None: clauses.extend((SQL('ELSE'), _InFunction(self.default))) clauses.append(SQL('END')) with ctx(in_function=False): return ctx.sql(NodeList(clauses))
Case
python
anthropics__anthropic-sdk-python
src/anthropic/resources/beta/files.py
{ "start": 1307, "end": 12668 }
class ____(SyncAPIResource): @cached_property def with_raw_response(self) -> FilesWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers """ return FilesWithRawResponse(self) @cached_property def with_streaming_response(self) -> FilesWithStreamingResponse: """ An alternative to `.with_raw_response` that doesn't eagerly read the response body. For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response """ return FilesWithStreamingResponse(self) def list( self, *, after_id: str | Omit = omit, before_id: str | Omit = omit, limit: int | Omit = omit, betas: List[AnthropicBetaParam] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> SyncPage[FileMetadata]: """List Files Args: after_id: ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object. before_id: ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object. limit: Number of items to return per page. Defaults to `20`. Ranges from `1` to `1000`. betas: Optional header to specify the beta version(s) you want to use. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ extra_headers = { **strip_not_given( { "anthropic-beta": ",".join(chain((str(e) for e in betas), ["files-api-2025-04-14"])) if is_given(betas) else not_given } ), **(extra_headers or {}), } extra_headers = {"anthropic-beta": "files-api-2025-04-14", **(extra_headers or {})} return self._get_api_list( "/v1/files?beta=true", page=SyncPage[FileMetadata], options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout, query=maybe_transform( { "after_id": after_id, "before_id": before_id, "limit": limit, }, file_list_params.FileListParams, ), ), model=FileMetadata, ) def delete( self, file_id: str, *, betas: List[AnthropicBetaParam] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> DeletedFile: """ Delete File Args: file_id: ID of the File. betas: Optional header to specify the beta version(s) you want to use. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not file_id: raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") extra_headers = { **strip_not_given( { "anthropic-beta": ",".join(chain((str(e) for e in betas), ["files-api-2025-04-14"])) if is_given(betas) else not_given } ), **(extra_headers or {}), } extra_headers = {"anthropic-beta": "files-api-2025-04-14", **(extra_headers or {})} return self._delete( f"/v1/files/{file_id}?beta=true", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=DeletedFile, ) def download( self, file_id: str, *, betas: List[AnthropicBetaParam] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> BinaryAPIResponse: """ Download File Args: file_id: ID of the File. betas: Optional header to specify the beta version(s) you want to use. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not file_id: raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") extra_headers = {"Accept": "application/binary", **(extra_headers or {})} extra_headers = { **strip_not_given( { "anthropic-beta": ",".join(chain((str(e) for e in betas), ["files-api-2025-04-14"])) if is_given(betas) else not_given } ), **(extra_headers or {}), } extra_headers = {"anthropic-beta": "files-api-2025-04-14", **(extra_headers or {})} return self._get( f"/v1/files/{file_id}/content?beta=true", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=BinaryAPIResponse, ) def retrieve_metadata( self, file_id: str, *, betas: List[AnthropicBetaParam] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> FileMetadata: """ Get File Metadata Args: file_id: ID of the File. betas: Optional header to specify the beta version(s) you want to use. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not file_id: raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") extra_headers = { **strip_not_given( { "anthropic-beta": ",".join(chain((str(e) for e in betas), ["files-api-2025-04-14"])) if is_given(betas) else not_given } ), **(extra_headers or {}), } extra_headers = {"anthropic-beta": "files-api-2025-04-14", **(extra_headers or {})} return self._get( f"/v1/files/{file_id}?beta=true", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=FileMetadata, ) def upload( self, *, file: FileTypes, betas: List[AnthropicBetaParam] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> FileMetadata: """ Upload File Args: file: The file to upload betas: Optional header to specify the beta version(s) you want to use. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ extra_headers = { **strip_not_given( { "anthropic-beta": ",".join(chain((str(e) for e in betas), ["files-api-2025-04-14"])) if is_given(betas) else not_given } ), **(extra_headers or {}), } extra_headers = {"anthropic-beta": "files-api-2025-04-14", **(extra_headers or {})} body = deepcopy_minimal({"file": file}) files = extract_files(cast(Mapping[str, object], body), paths=[["file"]]) # It should be noted that the actual Content-Type header that will be # sent to the server will contain a `boundary` parameter, e.g. # multipart/form-data; boundary=---abc-- extra_headers["Content-Type"] = "multipart/form-data" return self._post( "/v1/files?beta=true", body=maybe_transform(body, file_upload_params.FileUploadParams), files=files, options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=FileMetadata, )
Files
python
pypa__pip
src/pip/_vendor/rich/progress.py
{ "start": 21951, "end": 23682 }
class ____(ProgressColumn): """Renders a visual progress bar. Args: bar_width (Optional[int], optional): Width of bar or None for full width. Defaults to 40. style (StyleType, optional): Style for the bar background. Defaults to "bar.back". complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete". finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished". pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse". """ def __init__( self, bar_width: Optional[int] = 40, style: StyleType = "bar.back", complete_style: StyleType = "bar.complete", finished_style: StyleType = "bar.finished", pulse_style: StyleType = "bar.pulse", table_column: Optional[Column] = None, ) -> None: self.bar_width = bar_width self.style = style self.complete_style = complete_style self.finished_style = finished_style self.pulse_style = pulse_style super().__init__(table_column=table_column) def render(self, task: "Task") -> ProgressBar: """Gets a progress bar widget for a task.""" return ProgressBar( total=max(0, task.total) if task.total is not None else None, completed=max(0, task.completed), width=None if self.bar_width is None else max(1, self.bar_width), pulse=not task.started, animation_time=task.get_time(), style=self.style, complete_style=self.complete_style, finished_style=self.finished_style, pulse_style=self.pulse_style, )
BarColumn
python
Pylons__pyramid
tests/test_config/test_views.py
{ "start": 149035, "end": 149125 }
class ____(dict): def get_csrf_token(self): return self['csrf_token']
DummySession
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 23544, "end": 23955 }
class ____(sgqlc.types.Enum): """The possible viewed states of a file . Enumeration Choices: * `DISMISSED`: The file has new changes since last viewed. * `UNVIEWED`: The file has not been marked as viewed. * `VIEWED`: The file has been marked as viewed. """ __schema__ = github_schema __choices__ = ("DISMISSED", "UNVIEWED", "VIEWED") Float = sgqlc.types.Float
FileViewedState
python
doocs__leetcode
solution/2700-2799/2711.Difference of Number of Distinct Values on Diagonals/Solution.py
{ "start": 0, "end": 697 }
class ____: def differenceOfDistinctValues(self, grid: List[List[int]]) -> List[List[int]]: m, n = len(grid), len(grid[0]) ans = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): x, y = i, j s = set() while x and y: x, y = x - 1, y - 1 s.add(grid[x][y]) tl = len(s) x, y = i, j s = set() while x + 1 < m and y + 1 < n: x, y = x + 1, y + 1 s.add(grid[x][y]) br = len(s) ans[i][j] = abs(tl - br) return ans
Solution
python
PrefectHQ__prefect
tests/utilities/test_pydantic.py
{ "start": 5755, "end": 6324 }
class ____: def test_json_schema(self): class PatchModel(BaseModel): model_config = ConfigDict(arbitrary_types_allowed=True) patch: JsonPatch = Field(default_factory=lambda: JsonPatch([])) schema = PatchModel.model_json_schema() assert schema["properties"]["patch"] == { "title": "Patch", "type": "array", "format": "rfc6902", "items": { "type": "object", "additionalProperties": {"type": "string"}, }, }
TestJsonPatch
python
kamyu104__LeetCode-Solutions
Python/longest-increasing-subsequence.py
{ "start": 49, "end": 556 }
class ____(object): def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ LIS = [] def insert(target): left = bisect.bisect_left(LIS, target) # If not found, append the target. if left == len(LIS): LIS.append(target) else: LIS[left] = target for num in nums: insert(num) return len(LIS) # Time: O(nlogn) # Space: O(n)
Solution
python
numpy__numpy
numpy/_core/tests/test_simd.py
{ "start": 10928, "end": 11790 }
class ____(_Test_Utility): """ To only test single precision """ def test_conversions(self): """ Round to nearest even integer, assume CPU control register is set to rounding. Test intrinsics: npyv_round_s32_##SFX """ features = self._cpu_features() if not self.npyv.simd_f64 and re.match(r".*(NEON|ASIMD)", features): # very costly to emulate nearest even on Armv7 # instead we round halves to up. e.g. 0.5 -> 1, -0.5 -> -1 _round = lambda v: int(v + (0.5 if v >= 0 else -0.5)) else: _round = round vdata_a = self.load(self._data()) vdata_a = self.sub(vdata_a, self.setall(0.5)) data_round = [_round(x) for x in vdata_a] vround = self.round_s32(vdata_a) assert vround == data_round
_SIMD_FP32
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 480625, "end": 481415 }
class ____(sgqlc.types.relay.Connection): """The connection type for BypassForcePushAllowance.""" __schema__ = github_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of("BypassForcePushAllowanceEdge"), graphql_name="edges") """A list of edges.""" nodes = sgqlc.types.Field(sgqlc.types.list_of("BypassForcePushAllowance"), graphql_name="nodes") """A list of nodes.""" page_info = sgqlc.types.Field(sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo") """Information to aid in pagination.""" total_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="totalCount") """Identifies the total count of items in the connection."""
BypassForcePushAllowanceConnection
python
ray-project__ray
python/ray/_private/runtime_env/utils.py
{ "start": 120, "end": 3989 }
class ____(subprocess.CalledProcessError): """The subprocess.CalledProcessError with stripped stdout.""" LAST_N_LINES = 50 def __init__(self, *args, cmd_index=None, **kwargs): self.cmd_index = cmd_index super().__init__(*args, **kwargs) @staticmethod def _get_last_n_line(str_data: str, last_n_lines: int) -> str: if last_n_lines < 0: return str_data lines = str_data.strip().split("\n") return "\n".join(lines[-last_n_lines:]) def __str__(self): str_list = ( [] if self.cmd_index is None else [f"Run cmd[{self.cmd_index}] failed with the following details."] ) str_list.append(super().__str__()) out = { "stdout": self.stdout, "stderr": self.stderr, } for name, s in out.items(): if s: subtitle = f"Last {self.LAST_N_LINES} lines of {name}:" last_n_line_str = self._get_last_n_line(s, self.LAST_N_LINES).strip() str_list.append( f"{subtitle}\n{textwrap.indent(last_n_line_str, ' ' * 4)}" ) return "\n".join(str_list) async def check_output_cmd( cmd: List[str], *, logger: logging.Logger, cmd_index_gen: types.GeneratorType = itertools.count(1), **kwargs, ) -> str: """Run command with arguments and return its output. If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute. Args: cmd: The cmdline should be a sequence of program arguments or else a single string or path-like object. The program to execute is the first item in cmd. logger: The logger instance. cmd_index_gen: The cmd index generator, default is itertools.count(1). kwargs: All arguments are passed to the create_subprocess_exec. Returns: The stdout of cmd. Raises: CalledProcessError: If the return code of cmd is not 0. """ cmd_index = next(cmd_index_gen) logger.info("Run cmd[%s] %s", cmd_index, repr(cmd)) proc = None try: proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, **kwargs, ) # Use communicate instead of polling stdout: # * Avoid deadlocks due to streams pausing reading or writing and blocking the # child process. Please refer to: # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.stderr # * Avoid mixing multiple outputs of concurrent cmds. stdout, _ = await proc.communicate() except asyncio.exceptions.CancelledError as e: # since Python 3.9, when cancelled, the inner process needs to throw as it is # for asyncio to timeout properly https://bugs.python.org/issue40607 raise e except BaseException as e: raise RuntimeError(f"Run cmd[{cmd_index}] got exception.") from e else: stdout = stdout.decode("utf-8") if stdout: logger.info("Output of cmd[%s]: %s", cmd_index, stdout) else: logger.info("No output for cmd[%s]", cmd_index) if proc.returncode != 0: raise SubprocessCalledProcessError( proc.returncode, cmd, output=stdout, cmd_index=cmd_index ) return stdout finally: if proc is not None: # Kill process. try: proc.kill() except ProcessLookupError: pass # Wait process exit. await proc.wait()
SubprocessCalledProcessError
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_ordered_dict.py
{ "start": 39485, "end": 39871 }
class ____(mapping_tests.BasicTestMappingProtocol): @classmethod def setUpClass(cls): cls.type2test = py_coll.OrderedDict super().setUpClass() def test_popitem(self): d = self._empty_mapping() self.assertRaises(KeyError, d.popitem) @unittest.skipUnless(c_coll, 'requires the C version of the collections module')
PurePythonGeneralMappingTests
python
PrefectHQ__prefect
tests/client/test_prefect_client.py
{ "start": 2635, "end": 3874 }
class ____: def test_get_client_returns_client(self): assert isinstance(get_client(), PrefectClient) def test_get_client_does_not_cache_client(self): assert get_client() is not get_client() def test_get_client_cache_uses_profile_settings(self): client = get_client() with temporary_settings(updates={PREFECT_API_KEY: "FOO"}): new_client = get_client() assert isinstance(new_client, PrefectClient) assert new_client is not client @pytest.mark.usefixtures("enable_ephemeral_server") def test_get_client_starts_subprocess_server_when_enabled( self, monkeypatch: pytest.MonkeyPatch ): subprocess_server_mock = MagicMock() monkeypatch.setattr( prefect.server.api.server, "SubprocessASGIServer", subprocess_server_mock ) get_client() assert subprocess_server_mock.call_count == 1 assert subprocess_server_mock.return_value.start.call_count == 1 @pytest.mark.usefixtures("disable_hosted_api_server") def test_get_client_rasises_error_when_no_api_url_and_no_ephemeral_mode(self): with pytest.raises(ValueError, match="API URL"): get_client()
TestGetClient
python
doocs__leetcode
solution/2800-2899/2814.Minimum Time Takes to Reach Destination Without Drowning/Solution.py
{ "start": 0, "end": 1775 }
class ____: def minimumSeconds(self, land: List[List[str]]) -> int: m, n = len(land), len(land[0]) vis = [[False] * n for _ in range(m)] g = [[inf] * n for _ in range(m)] q = deque() si = sj = 0 for i, row in enumerate(land): for j, c in enumerate(row): match c: case "*": q.append((i, j)) case "S": si, sj = i, j dirs = (-1, 0, 1, 0, -1) t = 0 while q: for _ in range(len(q)): i, j = q.popleft() g[i][j] = t for a, b in pairwise(dirs): x, y = i + a, j + b if ( 0 <= x < m and 0 <= y < n and not vis[x][y] and land[x][y] in ".S" ): vis[x][y] = True q.append((x, y)) t += 1 t = 0 q = deque([(si, sj)]) vis = [[False] * n for _ in range(m)] vis[si][sj] = True while q: for _ in range(len(q)): i, j = q.popleft() if land[i][j] == "D": return t for a, b in pairwise(dirs): x, y = i + a, j + b if ( 0 <= x < m and 0 <= y < n and g[x][y] > t + 1 and not vis[x][y] and land[x][y] in ".D" ): vis[x][y] = True q.append((x, y)) t += 1 return -1
Solution
python
getsentry__sentry
src/sentry/integrations/discord/message_builder/base/component/select_menu.py
{ "start": 1333, "end": 2752 }
class ____(DiscordMessageComponent): """ A Discord select menu message component. We are only implementing the string select variation because the other types are not currently required. https://discord.com/developers/docs/interactions/message-components#select-menu-object """ def __init__( self, custom_id: str, options: Iterable[DiscordSelectMenuOption], placeholder: str | None = None, min_values: int = 1, max_values: int = 1, disabled: bool = False, ) -> None: super().__init__(type=3) self.custom_id = custom_id self.options = options self.placeholder = placeholder self.min_values = min_values self.max_values = max_values self.disabled = disabled def build(self) -> DiscordSelectMenuDict: select_menu = DiscordSelectMenuDict( type=self.type, custom_id=self.custom_id, options=[o.build() for o in self.options] ) if self.placeholder is not None: select_menu["placeholder"] = self.placeholder if self.min_values is not None: select_menu["min_values"] = self.min_values if self.max_values is not None: select_menu["max_values"] = self.max_values if self.disabled is not None: select_menu["disabled"] = self.disabled return select_menu
DiscordSelectMenu
python
numba__numba
numba/core/dispatcher.py
{ "start": 29121, "end": 38726 }
class ____(serialize.ReduceMixin, _MemoMixin, _DispatcherBase): """ Implementation of user-facing dispatcher objects (i.e. created using the @jit decorator). This is an abstract base class. Subclasses should define the targetdescr class attribute. """ _fold_args = True __numba__ = 'py_func' def __init__(self, py_func, locals=None, targetoptions=None, pipeline_class=compiler.Compiler): """ Parameters ---------- py_func: function object to be compiled locals: dict, optional Mapping of local variable names to Numba types. Used to override the types deduced by the type inference engine. targetoptions: dict, optional Target-specific config options. pipeline_class: type numba.compiler.CompilerBase The compiler pipeline type. """ if locals is None: locals = {} if targetoptions is None: targetoptions = {} self.typingctx = self.targetdescr.typing_context self.targetctx = self.targetdescr.target_context pysig = utils.pysignature(py_func) arg_count = len(pysig.parameters) can_fallback = not targetoptions.get('nopython', False) _DispatcherBase.__init__(self, arg_count, py_func, pysig, can_fallback, exact_match_required=False) functools.update_wrapper(self, py_func) self.targetoptions = targetoptions self.locals = locals self._cache = NullCache() compiler_class = _FunctionCompiler self._compiler = compiler_class(py_func, self.targetdescr, targetoptions, locals, pipeline_class) self._cache_hits = collections.Counter() self._cache_misses = collections.Counter() self._type = types.Dispatcher(self) self.typingctx.insert_global(self, self._type) def dump(self, tab=''): print(f'{tab}DUMP {type(self).__name__}[{self.py_func.__name__}' f', type code={self._type._code}]') for cres in self.overloads.values(): cres.dump(tab=tab + ' ') print(f'{tab}END DUMP {type(self).__name__}[{self.py_func.__name__}]') @property def _numba_type_(self): return types.Dispatcher(self) def enable_caching(self): self._cache = FunctionCache(self.py_func) def __get__(self, obj, objtype=None): '''Allow a JIT function to be bound as a method to an object''' if obj is None: # Unbound method return self else: # Bound method return pytypes.MethodType(self, obj) def _reduce_states(self): """ Reduce the instance for pickling. This will serialize the original function as well the compilation options and compiled signatures, but not the compiled code itself. NOTE: part of ReduceMixin protocol """ if self._can_compile: sigs = [] else: sigs = [cr.signature for cr in self.overloads.values()] return dict( uuid=str(self._uuid), py_func=self.py_func, locals=self.locals, targetoptions=self.targetoptions, can_compile=self._can_compile, sigs=sigs, ) @classmethod def _rebuild(cls, uuid, py_func, locals, targetoptions, can_compile, sigs): """ Rebuild an Dispatcher instance after it was __reduce__'d. NOTE: part of ReduceMixin protocol """ try: return cls._memo[uuid] except KeyError: pass self = cls(py_func, locals, targetoptions) # Make sure this deserialization will be merged with subsequent ones self._set_uuid(uuid) for sig in sigs: self.compile(sig) self._can_compile = can_compile return self def compile(self, sig): with ExitStack() as scope: cres = None def cb_compiler(dur): if cres is not None: self._callback_add_compiler_timer(dur, cres) def cb_llvm(dur): if cres is not None: self._callback_add_llvm_timer(dur, cres) scope.enter_context(ev.install_timer("numba:compiler_lock", cb_compiler)) scope.enter_context(ev.install_timer("numba:llvm_lock", cb_llvm)) scope.enter_context(global_compiler_lock) if not self._can_compile: raise RuntimeError("compilation disabled") # Use counter to track recursion compilation depth with self._compiling_counter: args, return_type = sigutils.normalize_signature(sig) # Don't recompile if signature already exists existing = self.overloads.get(tuple(args)) if existing is not None: return existing.entry_point # Try to load from disk cache cres = self._cache.load_overload(sig, self.targetctx) if cres is not None: self._cache_hits[sig] += 1 # XXX fold this in add_overload()? (also see compiler.py) if not cres.objectmode: self.targetctx.insert_user_function(cres.entry_point, cres.fndesc, [cres.library]) self.add_overload(cres) return cres.entry_point self._cache_misses[sig] += 1 ev_details = dict( dispatcher=self, args=args, return_type=return_type, ) with ev.trigger_event("numba:compile", data=ev_details): try: cres = self._compiler.compile(args, return_type) except errors.ForceLiteralArg as e: def folded(args, kws): return self._compiler.fold_argument_types(args, kws)[1] raise e.bind_fold_arguments(folded) self.add_overload(cres) self._cache.save_overload(sig, cres) return cres.entry_point def get_compile_result(self, sig): """Compile (if needed) and return the compilation result with the given signature. Returns ``CompileResult``. Raises ``NumbaError`` if the signature is incompatible. """ atypes = tuple(sig.args) if atypes not in self.overloads: if self._can_compile: # Compiling may raise any NumbaError self.compile(atypes) else: msg = f"{sig} not available and compilation disabled" raise errors.TypingError(msg) return self.overloads[atypes] def recompile(self): """ Recompile all signatures afresh. """ sigs = list(self.overloads) old_can_compile = self._can_compile # Ensure the old overloads are disposed of, # including compiled functions. self._make_finalizer()() self._reset_overloads() self._cache.flush() self._can_compile = True try: for sig in sigs: self.compile(sig) finally: self._can_compile = old_can_compile @property def stats(self): return _CompileStats( cache_path=self._cache.cache_path, cache_hits=self._cache_hits, cache_misses=self._cache_misses, ) def parallel_diagnostics(self, signature=None, level=1): """ Print parallel diagnostic information for the given signature. If no signature is present it is printed for all known signatures. level is used to adjust the verbosity, level=1 (default) is minimal verbosity, and 2, 3, and 4 provide increasing levels of verbosity. """ def dump(sig): ol = self.overloads[sig] pfdiag = ol.metadata.get('parfor_diagnostics', None) if pfdiag is None: msg = "No parfors diagnostic available, is 'parallel=True' set?" raise ValueError(msg) pfdiag.dump(level) if signature is not None: dump(signature) else: [dump(sig) for sig in self.signatures] def get_metadata(self, signature=None): """ Obtain the compilation metadata for a given signature. """ if signature is not None: return self.overloads[signature].metadata else: return dict( (sig,self.overloads[sig].metadata) for sig in self.signatures ) def get_function_type(self): """Return unique function type of dispatcher when possible, otherwise return None. A Dispatcher instance has unique function type when it contains exactly one compilation result and its compilation has been disabled (via its disable_compile method). """ if not self._can_compile and len(self.overloads) == 1: cres = tuple(self.overloads.values())[0] return types.FunctionType(cres.signature)
Dispatcher
python
airbytehq__airbyte
airbyte-integrations/bases/connector-acceptance-test/unit_tests/test_config.py
{ "start": 9988, "end": 11291 }
class ____: @pytest.mark.parametrize( ("skip_test", "bypass_reason", "unsupported_types", "expectation"), ( (True, None, None, does_not_raise()), (True, None, [config.UnsupportedFileTypeConfig(extension=".csv")], pytest.raises(ValidationError)), (False, None, None, does_not_raise()), (False, "bypass_reason", None, pytest.raises(ValidationError)), (False, "", None, pytest.raises(ValidationError)), (False, None, [config.UnsupportedFileTypeConfig(extension=".csv")], does_not_raise()), ), ) def test_skip_test_behavior(self, skip_test, bypass_reason, unsupported_types, expectation): with expectation: config.FileTypesConfig(skip_test=skip_test, bypass_reason=bypass_reason, unsupported_types=unsupported_types) @pytest.mark.parametrize( ("extension", "expectation"), ( (".csv", does_not_raise()), ("csv", pytest.raises(ValidationError)), (".", pytest.raises(ValidationError)), ("", pytest.raises(ValidationError)), ), ) def test_extension_validation(self, extension, expectation): with expectation: config.UnsupportedFileTypeConfig(extension=extension)
TestFileTypesConfig
python
huggingface__transformers
src/transformers/models/altclip/modeling_altclip.py
{ "start": 23116, "end": 25093 }
class ____(GradientCheckpointingLayer): def __init__(self, config: AltCLIPConfig): super().__init__() self.embed_dim = config.hidden_size self.self_attn = AltCLIPAttention(config) self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) self.mlp = AltCLIPMLP(config) self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, causal_attention_mask: torch.Tensor, output_attentions: Optional[bool] = False, ) -> tuple[torch.FloatTensor]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. `(config.encoder_attention_heads,)`. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. """ residual = hidden_states hidden_states = self.layer_norm1(hidden_states) hidden_states, attn_weights = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, causal_attention_mask=causal_attention_mask, output_attentions=output_attentions, ) hidden_states = residual + hidden_states residual = hidden_states hidden_states = self.layer_norm2(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states outputs = (hidden_states,) if output_attentions: outputs += (attn_weights,) return outputs
AltCLIPEncoderLayer
python
joke2k__faker
tests/providers/test_job.py
{ "start": 4029, "end": 4218 }
class ____: """Test pt_BR job provider""" def test_job(self, faker, num_samples): for _ in range(num_samples): assert faker.job() in PtBrJobProvider.jobs
TestPtBr
python
openai__openai-python
src/openai/types/beta/threads/run_create_params.py
{ "start": 8097, "end": 8325 }
class ____(TypedDict, total=False): file_id: str """The ID of the file to attach to the message.""" tools: Iterable[AdditionalMessageAttachmentTool] """The tools to add this file to."""
AdditionalMessageAttachment
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 927509, "end": 928819 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "content_type", "created_at", "download_count", "download_url", "name", "release", "size", "updated_at", "uploaded_by", "url", ) content_type = sgqlc.types.Field( sgqlc.types.non_null(String), graphql_name="contentType" ) created_at = sgqlc.types.Field( sgqlc.types.non_null(DateTime), graphql_name="createdAt" ) download_count = sgqlc.types.Field( sgqlc.types.non_null(Int), graphql_name="downloadCount" ) download_url = sgqlc.types.Field( sgqlc.types.non_null(URI), graphql_name="downloadUrl" ) name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name") release = sgqlc.types.Field(Release, graphql_name="release") size = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="size") updated_at = sgqlc.types.Field( sgqlc.types.non_null(DateTime), graphql_name="updatedAt" ) uploaded_by = sgqlc.types.Field( sgqlc.types.non_null("User"), graphql_name="uploadedBy" ) url = sgqlc.types.Field(sgqlc.types.non_null(URI), graphql_name="url")
ReleaseAsset
python
modin-project__modin
modin/tests/pandas/utils.py
{ "start": 16317, "end": 30080 }
class ____: """int-like class with non-commutative multiply operation. We need to test that rmul and mul do different things even when multiplication is not commutative, but almost all multiplication is commutative. This class' fake multiplication overloads are not commutative when you multiply an instance of this class with pandas.series, which does not know how to __mul__ with this class. e.g. NonCommutativeMultiplyInteger(2) * pd.Series(1, dtype=int) == pd.Series(2, dtype=int) pd.Series(1, dtype=int) * NonCommutativeMultiplyInteger(2) == pd.Series(3, dtype=int) """ def __init__(self, value: int): if not isinstance(value, int): raise TypeError( f"must initialize with integer, but got {value} of type {type(value)}" ) self.value = value def __mul__(self, other): # Note that we need to check other is an int, otherwise when we (left) mul # this with a series, we'll just multiply self.value by the series, whereas # we want to make the series do an rmul instead. if not isinstance(other, int): return NotImplemented return self.value * other def __rmul__(self, other): return self.value * other + 1 def categories_equals(left, right): assert (left.ordered and right.ordered) or (not left.ordered and not right.ordered) assert_extension_array_equal(left, right) def df_categories_equals(df1, df2): if not hasattr(df1, "select_dtypes"): if isinstance(df1, pandas.CategoricalDtype): categories_equals(df1, df2) elif isinstance(getattr(df1, "dtype"), pandas.CategoricalDtype) and isinstance( getattr(df2, "dtype"), pandas.CategoricalDtype ): categories_equals(df1.dtype, df2.dtype) return True df1_categorical = df1.select_dtypes(include="category") df2_categorical = df2.select_dtypes(include="category") assert df1_categorical.columns.equals(df2_categorical.columns) # Use an index instead of a column name to iterate through columns. There # may be duplicate colum names. e.g. if two columns are named col1, # selecting df1_categorical["col1"] gives a dataframe of width 2 instead of a series. for i in range(len(df1_categorical.columns)): assert_extension_array_equal( df1_categorical.iloc[:, i].values, df2_categorical.iloc[:, i].values, check_dtype=False, ) def assert_empty_frame_equal(df1, df2): """ Test if df1 and df2 are empty. Parameters ---------- df1 : pandas.DataFrame or pandas.Series df2 : pandas.DataFrame or pandas.Series Raises ------ AssertionError If check fails. """ if (df1.empty and not df2.empty) or (df2.empty and not df1.empty): assert False, "One of the passed frames is empty, when other isn't" elif df1.empty and df2.empty and type(df1) is not type(df2): assert False, f"Empty frames have different types: {type(df1)} != {type(df2)}" def assert_all_act_same(condition, *objs): """ Assert that all of the objs give the same boolean result for the passed condition (either all True or all False). Parameters ---------- condition : callable(obj) -> bool Condition to run on the passed objects. *objs : Objects to pass to the condition. Returns ------- bool Result of the condition. """ results = [condition(obj) for obj in objs] if len(results) < 2: return results[0] if len(results) else None assert all(results[0] == res for res in results[1:]) return results[0] def assert_dtypes_equal(df1, df2): """ Assert that the two passed DataFrame/Series objects have equal dtypes. The function doesn't require that the dtypes are identical, it has the following reliefs: 1. The dtypes are not required to be in the same order (e.g. {"col1": int, "col2": float} == {"col2": float, "col1": int}) 2. The dtypes are only required to be in the same class (e.g. both numerical, both categorical, etc...) Parameters ---------- df1 : DataFrame or Series df2 : DataFrame or Series """ if not isinstance( df1, (pandas.Series, pd.Series, pandas.DataFrame, pd.DataFrame) ) or not isinstance( df2, (pandas.Series, pd.Series, pandas.DataFrame, pd.DataFrame) ): return if isinstance(df1.dtypes, (pandas.Series, pd.Series)): dtypes1 = df1.dtypes dtypes2 = df2.dtypes else: # Case when `dtypes` is a scalar dtypes1 = pandas.Series({"col": df1.dtypes}) dtypes2 = pandas.Series({"col": df2.dtypes}) # Don't require for dtypes to be in the same order assert len(dtypes1.index.difference(dtypes2.index)) == 0 assert len(dtypes1) == len(dtypes2) dtype_comparators = ( is_numeric_dtype, lambda obj: is_object_dtype(obj) or is_string_dtype(obj), is_bool_dtype, lambda obj: isinstance(obj, pandas.CategoricalDtype), is_datetime64_any_dtype, is_timedelta64_dtype, lambda obj: isinstance(obj, pandas.PeriodDtype), ) for idx in range(len(dtypes1)): for comparator in dtype_comparators: if assert_all_act_same(comparator, dtypes1.iloc[idx], dtypes2.iloc[idx]): # We met a dtype that both types satisfy, so we can stop iterating # over comparators and compare next dtypes break def assert_set_of_rows_identical(df1, df2): """ Assert that the set of rows for the passed dataframes is identical. Works much slower than ``df1.equals(df2)``, so it's recommended to use this function only in exceptional cases. """ # replacing NaN with None to pass the comparison: 'NaN == NaN -> false; None == None -> True' df1, df2 = map( lambda df: (df.to_frame() if df.ndim == 1 else df).replace({np.nan: None}), (df1, df2), ) rows1 = set((idx, *row.tolist()) for idx, row in df1.iterrows()) rows2 = set((idx, *row.tolist()) for idx, row in df2.iterrows()) assert rows1 == rows2 def sort_data(data): """Sort the passed sequence.""" if isinstance(data, (pandas.DataFrame, pd.DataFrame)): return data.sort_values(data.columns.to_list(), ignore_index=True) elif isinstance(data, (pandas.Series, pd.Series)): return data.sort_values() else: return np.sort(data) def sort_if_range_partitioning(df1, df2, comparator=None, force=False): """Sort the passed objects if 'RangePartitioning' is enabled and compare the sorted results.""" if comparator is None: comparator = df_equals if force or RangePartitioning.get(): df1, df2 = sort_data(df1), sort_data(df2) comparator(df1, df2) def df_equals(df1, df2, check_dtypes=True): """Tests if df1 and df2 are equal. Args: df1: (pandas or modin DataFrame or series) dataframe to test if equal. df2: (pandas or modin DataFrame or series) dataframe to test if equal. Returns: True if df1 is equal to df2. """ # Gets AttributError if modin's groupby object is not import like this from modin.pandas.groupby import DataFrameGroupBy groupby_types = (pandas.core.groupby.DataFrameGroupBy, DataFrameGroupBy) # The typing behavior of how pandas treats its index is not consistent when the # length of the DataFrame or Series is 0, so we just verify that the contents are # the same. if ( hasattr(df1, "index") and hasattr(df2, "index") and len(df1) == 0 and len(df2) == 0 ): if type(df1).__name__ == type(df2).__name__: if hasattr(df1, "name") and hasattr(df2, "name") and df1.name == df2.name: return if ( hasattr(df1, "columns") and hasattr(df2, "columns") and df1.columns.equals(df2.columns) ): return assert False if isinstance(df1, (list, tuple)) and all( isinstance(d, (pd.DataFrame, pd.Series, pandas.DataFrame, pandas.Series)) for d in df1 ): assert isinstance(df2, type(df1)), "Different type of collection" assert len(df1) == len(df2), "Different length result" return (df_equals(d1, d2) for d1, d2 in zip(df1, df2)) if check_dtypes: assert_dtypes_equal(df1, df2) # Convert to pandas if isinstance(df1, (pd.DataFrame, pd.Series)): df1 = to_pandas(df1) if isinstance(df2, (pd.DataFrame, pd.Series)): df2 = to_pandas(df2) if isinstance(df1, pandas.DataFrame) and isinstance(df2, pandas.DataFrame): assert_empty_frame_equal(df1, df2) if isinstance(df1, pandas.DataFrame) and isinstance(df2, pandas.DataFrame): assert_frame_equal( df1, df2, check_dtype=False, check_datetimelike_compat=True, check_index_type=False, check_column_type=False, check_categorical=False, ) df_categories_equals(df1, df2) elif isinstance(df1, pandas.Index) and isinstance(df2, pandas.Index): assert_index_equal(df1, df2) elif isinstance(df1, pandas.Series) and isinstance(df2, pandas.Series): assert_series_equal(df1, df2, check_dtype=False, check_series_type=False) elif ( hasattr(df1, "dtype") and hasattr(df2, "dtype") and isinstance(df1.dtype, pandas.core.dtypes.dtypes.ExtensionDtype) and isinstance(df2.dtype, pandas.core.dtypes.dtypes.ExtensionDtype) ): assert_extension_array_equal(df1, df2) elif isinstance(df1, groupby_types) and isinstance(df2, groupby_types): for g1, g2 in zip(df1, df2): assert g1[0] == g2[0] df_equals(g1[1], g2[1]) elif ( isinstance(df1, pandas.Series) and isinstance(df2, pandas.Series) and df1.empty and df2.empty ): assert all(df1.index == df2.index) assert df1.dtypes == df2.dtypes elif isinstance(df1, pandas.core.arrays.NumpyExtensionArray): assert isinstance(df2, pandas.core.arrays.NumpyExtensionArray) assert df1 == df2 elif isinstance(df1, np.recarray) and isinstance(df2, np.recarray): np.testing.assert_array_equal(df1, df2) else: res = df1 != df2 if res.any() if isinstance(res, np.ndarray) else res: np.testing.assert_almost_equal(df1, df2) def modin_df_almost_equals_pandas(modin_df, pandas_df, max_diff=0.0001): df_categories_equals(modin_df._to_pandas(), pandas_df) modin_df = to_pandas(modin_df) if hasattr(modin_df, "select_dtypes"): modin_df = modin_df.select_dtypes(exclude=["category"]) if hasattr(pandas_df, "select_dtypes"): pandas_df = pandas_df.select_dtypes(exclude=["category"]) if modin_df.equals(pandas_df): return isna = modin_df.isna().all() if isinstance(isna, bool): if isna: assert pandas_df.isna().all() return elif isna.all(): assert pandas_df.isna().all().all() return diff = (modin_df - pandas_df).abs() diff /= pandas_df.abs() diff_max = diff.max() if isinstance(diff, pandas.Series) else diff.max().max() assert diff_max < max_diff, f"{diff_max} >= {max_diff}" def try_modin_df_almost_equals_compare(df1, df2): """Compare two dataframes as nearly equal if possible, otherwise compare as completely equal.""" # `modin_df_almost_equals_pandas` is numeric-only comparator dtypes1, dtypes2 = [ dtype if is_list_like(dtype := df.dtypes) else [dtype] for df in (df1, df2) ] if all(map(is_numeric_dtype, dtypes1)) and all(map(is_numeric_dtype, dtypes2)): modin_df_almost_equals_pandas(df1, df2) else: df_equals(df1, df2) def df_is_empty(df): """Tests if df is empty. Args: df: (pandas or modin DataFrame) dataframe to test if empty. Returns: True if df is empty. """ assert df.size == 0 and df.empty assert df.shape[0] == 0 or df.shape[1] == 0 def arg_keys(arg_name, keys): """Appends arg_name to the front of all values in keys. Args: arg_name: (string) String containing argument name. keys: (list of strings) Possible inputs of argument. Returns: List of strings with arg_name append to front of keys. """ return ["{0}_{1}".format(arg_name, key) for key in keys] def name_contains(test_name, vals): """Determines if any string in vals is a substring of test_name. Args: test_name: (string) String to determine if contains substrings. vals: (list of strings) List of substrings to test for. Returns: True if a substring in vals is in test_name, else False. """ return any(val in test_name for val in vals) def check_df_columns_have_nans(df, cols): """Checks if there are NaN values in specified columns of a dataframe. :param df: Dataframe to check. :param cols: One column name or list of column names. :return: True if specified columns of dataframe contains NaNs. """ return ( pandas.api.types.is_list_like(cols) and ( any(isinstance(x, str) and x in df.columns and df[x].hasnans for x in cols) or any( isinstance(x, pd.Series) and x._parent is df and x.hasnans for x in cols ) ) ) or ( not pandas.api.types.is_list_like(cols) and cols in df.columns and df[cols].hasnans )
NonCommutativeMultiplyInteger
python
spack__spack
lib/spack/spack/solver/requirements.py
{ "start": 2632, "end": 13634 }
class ____: """Parses requirements from package.py files and configuration, and returns rules.""" def __init__(self, configuration: spack.config.Configuration): self.config = configuration self.runtime_pkgs = spack.repo.PATH.packages_with_tags("runtime") self.compiler_pkgs = spack.repo.PATH.packages_with_tags("compiler") self.preferences_from_input: List[Tuple[spack.spec.Spec, str]] = [] def rules(self, pkg: spack.package_base.PackageBase) -> List[RequirementRule]: result = [] result.extend(self.rules_from_input_specs(pkg)) result.extend(self.rules_from_package_py(pkg)) result.extend(self.rules_from_require(pkg)) result.extend(self.rules_from_prefer(pkg)) result.extend(self.rules_from_conflict(pkg)) return result def parse_rules_from_input_specs(self, specs: Sequence[spack.spec.Spec]): self.preferences_from_input.clear() for edge in spack.traverse.traverse_edges(specs, root=False): if edge.propagation == PropagationPolicy.PREFERENCE: for constraint in _split_edge_on_virtuals(edge): root_name = edge.parent.name self.preferences_from_input.append((constraint, root_name)) def rules_from_input_specs(self, pkg: spack.package_base.PackageBase) -> List[RequirementRule]: return [ preference( pkg.name, constraint=s, condition=spack.spec.Spec(f"{root_name} ^[deptypes=link,run]{pkg.name}"), origin=RequirementOrigin.INPUT_SPECS, ) for s, root_name in self.preferences_from_input ] def rules_from_package_py(self, pkg: spack.package_base.PackageBase) -> List[RequirementRule]: rules = [] for when_spec, requirement_list in pkg.requirements.items(): for requirements, policy, message in requirement_list: rules.append( RequirementRule( pkg_name=pkg.name, policy=policy, requirements=requirements, kind=RequirementKind.PACKAGE, condition=when_spec, message=message, origin=RequirementOrigin.DIRECTIVE, ) ) return rules def rules_from_virtual(self, virtual_str: str) -> List[RequirementRule]: kind, requests = self._raw_yaml_data(virtual_str, section="require", virtual=True) result = self._rules_from_requirements(virtual_str, requests, kind=kind) kind, requests = self._raw_yaml_data(virtual_str, section="prefer", virtual=True) result.extend(self._rules_from_preferences(virtual_str, preferences=requests, kind=kind)) kind, requests = self._raw_yaml_data(virtual_str, section="conflict", virtual=True) result.extend(self._rules_from_conflicts(virtual_str, conflicts=requests, kind=kind)) return result def rules_from_require(self, pkg: spack.package_base.PackageBase) -> List[RequirementRule]: kind, requirements = self._raw_yaml_data(pkg.name, section="require") return self._rules_from_requirements(pkg.name, requirements, kind=kind) def rules_from_prefer(self, pkg: spack.package_base.PackageBase) -> List[RequirementRule]: kind, preferences = self._raw_yaml_data(pkg.name, section="prefer") return self._rules_from_preferences(pkg.name, preferences=preferences, kind=kind) def _rules_from_preferences( self, pkg_name: str, *, preferences, kind: RequirementKind ) -> List[RequirementRule]: result = [] for item in preferences: spec, condition, msg = self._parse_prefer_conflict_item(item) result.append( preference(pkg_name, constraint=spec, condition=condition, kind=kind, message=msg) ) return result def rules_from_conflict(self, pkg: spack.package_base.PackageBase) -> List[RequirementRule]: kind, conflicts = self._raw_yaml_data(pkg.name, section="conflict") return self._rules_from_conflicts(pkg.name, conflicts=conflicts, kind=kind) def _rules_from_conflicts( self, pkg_name: str, *, conflicts, kind: RequirementKind ) -> List[RequirementRule]: result = [] for item in conflicts: spec, condition, msg = self._parse_prefer_conflict_item(item) result.append( conflict(pkg_name, constraint=spec, condition=condition, kind=kind, message=msg) ) return result def _parse_prefer_conflict_item(self, item): # The item is either a string or an object with at least a "spec" attribute if isinstance(item, str): spec = parse_spec_from_yaml_string(item) condition = spack.spec.Spec() message = None else: spec = parse_spec_from_yaml_string(item["spec"]) condition = spack.spec.Spec(item.get("when")) message = item.get("message") return spec, condition, message def _raw_yaml_data(self, pkg_name: str, *, section: str, virtual: bool = False): config = self.config.get_config("packages") data = config.get(pkg_name, {}).get(section, []) kind = RequirementKind.PACKAGE if virtual: return RequirementKind.VIRTUAL, data if not data: data = config.get("all", {}).get(section, []) kind = RequirementKind.DEFAULT return kind, data def _rules_from_requirements( self, pkg_name: str, requirements, *, kind: RequirementKind ) -> List[RequirementRule]: """Manipulate requirements from packages.yaml, and return a list of tuples with a uniform structure (name, policy, requirements). """ if isinstance(requirements, str): requirements = [requirements] rules = [] for requirement in requirements: # A string is equivalent to a one_of group with a single element if isinstance(requirement, str): requirement = {"one_of": [requirement]} for policy in ("spec", "one_of", "any_of"): if policy not in requirement: continue constraints = requirement[policy] # "spec" is for specifying a single spec if policy == "spec": constraints = [constraints] policy = "one_of" # validate specs from YAML first, and fail with line numbers if parsing fails. constraints = [ parse_spec_from_yaml_string(constraint, named=kind == RequirementKind.VIRTUAL) for constraint in constraints ] when_str = requirement.get("when") when = parse_spec_from_yaml_string(when_str) if when_str else spack.spec.Spec() constraints = [ x for x in constraints if not self.reject_requirement_constraint(pkg_name, constraint=x, kind=kind) ] if not constraints: continue rules.append( RequirementRule( pkg_name=pkg_name, policy=policy, requirements=constraints, kind=kind, message=requirement.get("message"), condition=when, origin=RequirementOrigin.REQUIRE_YAML, ) ) return rules def reject_requirement_constraint( self, pkg_name: str, *, constraint: spack.spec.Spec, kind: RequirementKind ) -> bool: """Returns True if a requirement constraint should be rejected""" # If it's a specific package requirement, it's never rejected if kind != RequirementKind.DEFAULT: return False # Reject requirements with dependencies for runtimes and compilers # These are usually requests on compilers, in the form of %<compiler> involves_dependencies = bool(constraint.dependencies()) if involves_dependencies and ( pkg_name in self.runtime_pkgs or pkg_name in self.compiler_pkgs ): tty.debug(f"[{__name__}] Rejecting '{constraint}' for compiler package {pkg_name}") return True # Requirements under all: are applied only if they are satisfiable considering only # package rules, so e.g. variants must exist etc. Otherwise, they are rejected. try: s = spack.spec.Spec(pkg_name) s.constrain(constraint) s.validate_or_raise() except spack.error.SpackError as e: tty.debug( f"[{__name__}] Rejecting the default '{constraint}' requirement " f"on '{pkg_name}': {str(e)}" ) return True return False def _split_edge_on_virtuals(edge: spack.spec.DependencySpec) -> List[spack.spec.Spec]: """Split the edge on virtuals and removes the parent.""" if not edge.virtuals: return [spack.spec.Spec(str(edge.copy(keep_parent=False)))] result = [] # We split on virtuals so that "%%c,cxx=gcc" enforces "%%c=gcc" and "%%cxx=gcc" separately for v in edge.virtuals: t = edge.copy(keep_parent=False, keep_virtuals=False) t.update_virtuals(v) t.when = spack.spec.Spec(f"%{v}") result.append(spack.spec.Spec(str(t))) return result def parse_spec_from_yaml_string(string: str, *, named: bool = False) -> spack.spec.Spec: """Parse a spec from YAML and add file/line info to errors, if it's available. Parse a ``Spec`` from the supplied string, but also intercept any syntax errors and add file/line information for debugging using file/line annotations from the string. Args: string: a string representing a ``Spec`` from config YAML. named: if True, the spec must have a name """ try: result = spack.spec.Spec(string) except spack.error.SpecSyntaxError as e: mark = get_mark_from_yaml_data(string) if mark: msg = f"{mark.name}:{mark.line + 1}: {str(e)}" raise spack.error.SpecSyntaxError(msg) from e raise e if named is True and not result.name: msg = f"expected a named spec, but got '{string}' instead" mark = get_mark_from_yaml_data(string) # Add a hint in case it's dependencies deps = result.dependencies() if len(deps) == 1: msg = f"{msg}. Did you mean '{deps[0]}'?" if mark: msg = f"{mark.name}:{mark.line + 1}: {msg}" raise spack.error.SpackError(msg) return result
RequirementParser
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_rds.py
{ "start": 10613, "end": 15507 }
class ____: @classmethod def setup_class(cls): cls.dag = DAG( dag_id="test_dag", schedule=None, default_args={"owner": "airflow", "start_date": DEFAULT_DATE}, ) cls.hook = RdsHook(aws_conn_id=AWS_CONN, region_name="us-east-1") _patch_hook_get_connection(cls.hook) @classmethod def teardown_class(cls): del cls.dag del cls.hook @mock_aws def test_copy_db_instance_snapshot(self): kms_key_arn = _create_kms_key() _create_db_instance(self.hook) _create_db_instance_snapshot(self.hook) instance_snapshot_operator = RdsCopyDbSnapshotOperator( task_id="test_instance", db_type="instance", source_db_snapshot_identifier=DB_INSTANCE_SNAPSHOT, target_db_snapshot_identifier=DB_INSTANCE_SNAPSHOT_COPY, aws_conn_id=AWS_CONN, dag=self.dag, kms_key_id=kms_key_arn, ) _patch_hook_get_connection(instance_snapshot_operator.hook) instance_snapshot_operator.execute(None) result = self.hook.conn.describe_db_snapshots(DBSnapshotIdentifier=DB_INSTANCE_SNAPSHOT_COPY) instance_snapshots = result.get("DBSnapshots") assert instance_snapshots assert len(instance_snapshots) == 1 @mock_aws @patch.object(RdsHook, "wait_for_db_snapshot_state") def test_copy_db_instance_snapshot_no_wait(self, mock_await_status): kms_key_arn = _create_kms_key() _create_db_instance(self.hook) _create_db_instance_snapshot(self.hook) instance_snapshot_operator = RdsCopyDbSnapshotOperator( task_id="test_instance_no_wait", db_type="instance", source_db_snapshot_identifier=DB_INSTANCE_SNAPSHOT, target_db_snapshot_identifier=DB_INSTANCE_SNAPSHOT_COPY, aws_conn_id=AWS_CONN, dag=self.dag, wait_for_completion=False, kms_key_id=kms_key_arn, ) _patch_hook_get_connection(instance_snapshot_operator.hook) instance_snapshot_operator.execute(None) result = self.hook.conn.describe_db_snapshots(DBSnapshotIdentifier=DB_INSTANCE_SNAPSHOT_COPY) instance_snapshots = result.get("DBSnapshots") assert instance_snapshots assert len(instance_snapshots) == 1 mock_await_status.assert_not_called() @mock_aws def test_copy_db_cluster_snapshot(self): kms_key_arn = _create_kms_key() _create_db_cluster(self.hook) _create_db_cluster_snapshot(self.hook) cluster_snapshot_operator = RdsCopyDbSnapshotOperator( task_id="test_cluster", db_type="cluster", source_db_snapshot_identifier=DB_CLUSTER_SNAPSHOT, target_db_snapshot_identifier=DB_CLUSTER_SNAPSHOT_COPY, aws_conn_id=AWS_CONN, dag=self.dag, kms_key_id=kms_key_arn, ) _patch_hook_get_connection(cluster_snapshot_operator.hook) cluster_snapshot_operator.execute(None) result = self.hook.conn.describe_db_cluster_snapshots( DBClusterSnapshotIdentifier=DB_CLUSTER_SNAPSHOT_COPY ) cluster_snapshots = result.get("DBClusterSnapshots") assert cluster_snapshots assert len(cluster_snapshots) == 1 @mock_aws @patch.object(RdsHook, "wait_for_db_snapshot_state") def test_copy_db_cluster_snapshot_no_wait(self, mock_await_status): kms_key_arn = _create_kms_key() _create_db_cluster(self.hook) _create_db_cluster_snapshot(self.hook) cluster_snapshot_operator = RdsCopyDbSnapshotOperator( task_id="test_cluster_no_wait", db_type="cluster", source_db_snapshot_identifier=DB_CLUSTER_SNAPSHOT, target_db_snapshot_identifier=DB_CLUSTER_SNAPSHOT_COPY, aws_conn_id=AWS_CONN, dag=self.dag, kms_key_id=kms_key_arn, ) _patch_hook_get_connection(cluster_snapshot_operator.hook) cluster_snapshot_operator.execute(None) result = self.hook.conn.describe_db_cluster_snapshots( DBClusterSnapshotIdentifier=DB_CLUSTER_SNAPSHOT_COPY ) cluster_snapshots = result.get("DBClusterSnapshots") assert cluster_snapshots assert len(cluster_snapshots) == 1 mock_await_status.assert_not_called() def test_template_fields(self): operator = RdsCopyDbSnapshotOperator( task_id="test_cluster_no_wait", db_type="cluster", source_db_snapshot_identifier=DB_CLUSTER_SNAPSHOT, target_db_snapshot_identifier=DB_CLUSTER_SNAPSHOT_COPY, aws_conn_id=AWS_CONN, region_name=REGION, ) validate_template_fields(operator)
TestRdsCopyDbSnapshotOperator
python
ray-project__ray
rllib/models/torch/torch_action_dist.py
{ "start": 7038, "end": 8779 }
class ____(TorchCategorical): """MultiCategorical distribution for MultiDiscrete action spaces. The action space must be uniform, meaning all nvec items have the same size, e.g. MultiDiscrete([10, 10, 10]), where 10 is the number of candidates to pick from and 3 is the slate size (pick 3 out of 10). When picking candidates, no candidate must be picked more than once. """ def __init__( self, inputs: List[TensorType], model: TorchModelV2 = None, temperature: float = 1.0, action_space: Optional[gym.spaces.MultiDiscrete] = None, all_slates=None, ): assert temperature > 0.0, "Categorical `temperature` must be > 0.0!" # Allow softmax formula w/ temperature != 1.0: # Divide inputs by temperature. super().__init__(inputs / temperature, model) self.action_space = action_space # Assert uniformness of the action space (all discrete buckets have the same # size). assert isinstance(self.action_space, gym.spaces.MultiDiscrete) and all( n == self.action_space.nvec[0] for n in self.action_space.nvec ) self.all_slates = all_slates @override(ActionDistribution) def deterministic_sample(self) -> TensorType: # Get a sample from the underlying Categorical (batch of ints). sample = super().deterministic_sample() # Use the sampled ints to pick the actual slates. return torch.take_along_dim(self.all_slates, sample.long(), dim=-1) @override(ActionDistribution) def logp(self, x: TensorType) -> TensorType: # TODO: Implement. return torch.ones_like(self.inputs[:, 0]) @OldAPIStack
TorchSlateMultiCategorical
python
pytorch__pytorch
torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py
{ "start": 3413, "end": 3885 }
class ____(DefaultAllocMixin, ReduceScatter): def __call__( self, output_tensor: torch.Tensor, input_tensor: torch.Tensor, group: dist.ProcessGroup, op: _ReduceOp, async_op: bool = False, ) -> dist.Work: return dist.reduce_scatter_tensor( output=output_tensor, input=input_tensor, group=group, op=op, async_op=async_op, )
DefaultReduceScatter
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_axis54.py
{ "start": 306, "end": 1726 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_axis54.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "column"}) chart.axis_ids = [63560704, 74118272] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series({"values": "=Sheet1!$A$1:$A$5"}) chart.add_series({"values": "=Sheet1!$B$1:$B$5"}) chart.add_series({"values": "=Sheet1!$C$1:$C$5"}) chart.set_x_axis( { "name": "XXX", "name_fill": {"color": "yellow"}, "name_border": {"color": "red"}, } ) chart.set_y_axis( { "name": "YYY", "name_fill": {"color": "red"}, "name_border": {"color": "yellow"}, } ) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
kamyu104__LeetCode-Solutions
Python/generate-parentheses.py
{ "start": 81, "end": 1049 }
class ____(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ result, curr = [], [] stk = [(1, (n, n))] while stk: step, args = stk.pop() if step == 1: left, right = args if left == 0 and right == 0: result.append("".join(curr)) if left < right: stk.append((3, tuple())) stk.append((1, (left, right-1))) stk.append((2, (')'))) if left > 0: stk.append((3, tuple())) stk.append((1, (left-1, right))) stk.append((2, ('('))) elif step == 2: curr.append(args[0]) elif step == 3: curr.pop() return result # Time: O(4^n / n^(3/2)) ~= Catalan numbers # Space: O(n) # recursive solution
Solution
python
kamyu104__LeetCode-Solutions
Python/build-an-array-with-stack-operations.py
{ "start": 29, "end": 378 }
class ____(object): def buildArray(self, target, n): """ :type target: List[int] :type n: int :rtype: List[str] """ result, curr = [], 1 for t in target: result.extend(["Push", "Pop"]*(t-curr)) result.append("Push") curr = t+1 return result
Solution
python
bokeh__bokeh
tests/unit/bokeh/model/test_util_model.py
{ "start": 4022, "end": 5811 }
class ____: @pytest.mark.parametrize('typ', (int, float, str)) def test_scalar(self, typ) -> None: obj = typ() vals = set() assert bmu.visit_value_and_its_immediate_references(obj, lambda x: vals.add(x)) is None assert vals == set() @pytest.mark.parametrize('typ', (tuple, list)) def test_seq(self, typ) -> None: r1 = LayoutDOM() r2 = LayoutDOM() obj = typ([r1, r2]) vals = set() assert bmu.visit_value_and_its_immediate_references(obj, lambda x: vals.add(x)) is None assert vals == { r1, r2 } def test_dict(self) -> None: r1 = LayoutDOM() r2 = LayoutDOM() obj = dict(r1=r1, r2=r2) vals = set() assert bmu.visit_value_and_its_immediate_references(obj, lambda x: vals.add(x)) is None assert vals == { r1, r2 } def test_Model(self) -> None: r1 = LayoutDOM() r2 = LayoutDOM() r3 = LayoutDOM() row = Row(children=[r3]) obj = Row(children=[r1, r2, row]) vals = set() assert bmu.visit_value_and_its_immediate_references(obj, lambda x: vals.add(x)) is None assert vals == { obj } # TODO (bev) test for HasProps (recurses) #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
Test_visit_value_and_its_immediate_references
python
joke2k__faker
faker/providers/lorem/da_DK/__init__.py
{ "start": 68, "end": 18520 }
class ____(LoremProvider): """Implement lorem provider for ``da_DK`` locale. # NOQA""" word_list = ( "område", "verden", "nødvendig", "ligge", "magt", "drøm", "midt", "indeholde", "plads", "viden", "etage", "forstå", "social", "hvornår", "andre", "vente", "bære", "bank", "station", "budget", "hjerte", "politisk", "ret", "fod", "åben", "sammenligne", "national", "offer", "hver", "økonomi", "morgen", "masse", "bestemme", "race", "nogen", "forekomme", "at", "især", "kraft", "andet", "følelse", "bred", "problem", "hospital", "tusind", "TV", "bold", "vælge", "medicinsk", "dårligst", "ja", "miljø", "forlig", "netværk", "beskrive", "beløb", "publikum", "scene", "tanke", "form", "officer", "cykle", "celle", "løb", "passere", "spise", "efterår", "spekulerer", "luft", "medier", "kant", "tre", "rækkevidde", "møde", "resultat", "aftensmad", "uge", "overveje", "se", "ur", "forbrydelse", "os", "television", "krig", "videnskab", "eksempel", "stemme", "give", "forfatter", "hellere", "behandling", "senere", "syv", "par", "hundrede", "hud", "enkelt", "liste", "aften", "ud", "altid", "tryk", "effekt", "ting", "sager", "rød", "så", "hel", "vil", "have", "leder", "inde", "fordel", "taske", "aldrig", "forskellige", "artikel", "grine", "forklare", "jeg", "minut", "være", "eksisterer", "forkert", "rig", "dække", "konference", "sikker", "ejendom", "udmelding", "plukke", "blive", "ekspert", "hele", "vejen", "igennem", "år", "strøm", "store", "nå", "hende", "købe", "tegne", "fattige", "kort", "rolle", "sandsynligvis", "der", "placere", "familie", "forskning", "dag", "telefon", "kan", "mund", "finansiel", "evne", "design", "politik", "medlem", "anden", "lave", "læge", "skulle", "gerne", "myndighed", "dyrke", "sende", "kilde", "forbi", "arbejde", "århundrede", "dårligt", "interesse", "vest", "lade", "jeres", "vindue", "bestemte", "spørge", "sige", "dette", "operation", "lille", "miljømæssigt", "genkende", "tilbud", "ven", "fysisk", "nu", "svare", "hun", "ske", "syd", "fuld", "trods", "administration", "ny", "endelig", "fremstille", "besked", "figur", "skilt", "trin", "information", "forholde", "ned", "faktisk", "direkte", "succes", "tjene", "debat", "varme", "barn", "niveau", "fyr", "træ", "eftermiddagen", "karakter", "forlade", "sprog", "godt", "ind", "problemer", "underviser", "stor", "ryste", "bestyrelse", "gå", "central", "synge", "ord", "oplade", "datter", "adresse", "hed", "seng", "rapport", "over", "penge", "alder", "tendens", "køkken", "arbejder", "tilstand", "side", "bekymre", "blod", "vigtigste", "bedst", "sang", "imidlertid", "nævne", "tab", "hit", "vellykket", "virkelig", "tage", "smerte", "professor", "mørk", "vind", "årti", "hotel", "projekt", "traditionel", "indvirkning", "kollektion", "seksuel", "pris", "skulder", "rejse", "finde", "interview", "ifølge", "grad", "medarbejder", "trussel", "sommer", "stå", "hvorfor", "pæn", "individuel", "avis", "industri", "nat", "alle", "bruge", "handling", "vej", "hård", "brev", "olie", "ved", "påvirke", "parat", "stærk", "vigtig", "ressource", "værdi", "påstand", "struktur", "virkelighed", "disse", "komme", "data", "position", "glemme", "vægt", "af", "mål", "varsel", "prøve", "jord", "død", "blå", "strategi", "vend", "tilbage", "læs", "start", "bedre", "vise", "selvom", "konto", "på", "måle", "kvalitet", "nord", "vestlig", "skyde", "liv", "køre", "sandhed", "kunstner", "jo", "da", "formue", "bjørn", "historiker", "du", "titel", "udenlandsk", "kontanter", "korn", "heller", "ikke", "overlevelse", "beskytte", "baseball", "før", "forhandle", "afhængig", "fase", "genetisk", "stille", "fugl", "grøntsag", "tillid", "episode", "kunstnerisk", "markedsføring", "perfekt", "afspejle", "emne", "jet", "synlig", "ugentlig", "undersøgelse", "tank", "enhed", "gensidig", "psykolog", "fru", "øjeblikket", "indlysende", "årsag", "tilstedeværelse", "parkering", "forår", "tå", "muskel", "fange", "frokost", "forpligtelse", "spænding", "tilhører", "gentleman", "mig", "jury", "eventuelt", "gård", "alsidig", "passager", "øjeblik", "jæger", "vane", "erkende", "erhverve", "livsstil", "respons", "landdistrikter", "fantasi", "afgørende", "langt", "fond", "insistere", "parkere", "opnå", "fløde", "forskel", "væsentligt", "lappe", "morder", "længde", "poesi", "udbredt", "ungdom", "fjerde", "bevæbnet", "mirakel", "musiker", "bind", "punkt", "frihed", "rør", "genopretning", "forhandler", "kun", "ben", "klinge", "nød", "tænker", "græsplæne", "lag", "sko", "røg", "blandt", "karriere", "angst", "dimension", "vital", "kerne", "gul", "tælle", "forventer", "klinik", "opbevaring", "relevant", "måske", "meget", "egen", "chip", "trykke", "stil", "sofistikeret", "begrænsning", "resterende", "pulver", "slag", "fiktion", "aggressiv", "anholdelse", "syre", "glip", "afslut", "igangværende", "afvige", "forestille", "inflation", "regnet", "te", "sværge", "afdeling", "DNA", "tåre", "skib", "frembringe", "ivrige", "tilføjelse", "boliger", "bombe", "helikopter", "tag", "negativ", "regn", "dokument", "omdømme", "sikkert", "peber", "retfærdig", "skygge", "type", "distrikt", "betaling", "kontrast", "opdage", "signal", "gnide", "svært", "uanset", "sikkerhed", "ovn", "major", "butik", "forsigtigt", "flygtning", "korrekt", "bro", "men", "kunst", "religion", "forsøg", "kost", "kunne", "levende", "gevinst", "kolesterol", "sovs", "bag", "i", "billede", "desuden", "modtage", "udgave", "hal", "skelne", "anerkende", "bygge", "nummer", "distribuere", "væk", "fortælle", "mysterium", "siden", "samling", "gen", "stof", "global", "stjæle", "funktion", "præsidentvalg", "respekt", "løg", "beundre", "sælge", "mangfoldighed", "vidner", "fejl", "domfældelse", "teenager", "solid", "fødselsdag", "som", "formand", "konkurrence", "er", "indsigt", "nærheden", "betyde", "annonce", "dem", "skære", "reaktion", "romantisk", "smag", "udgør", "lethed", "misbrug", "sukker", "støj", "senat", "syg", "forvirring", "formål", "trick", "hul", "klaver", "operere", "grave", "gætte", "regime", "model", "sommetider", "politimand", "nødsituation", "rigtigt", "træt", "laver", "mad", "investere", "reb", "ofte", "restaurant", "ekstraordinær", "fortælling", "angreb", "størrelse", "stjerne", "overraskende", "elementære", "kommunikere", "top", "til", "fødsel", "spiseskefuld", "konventionelle", "køretøj", "film", "gear", "kul", "væg", "køn", "voldsom", "vin", "værdifuld", "forlægger", "session", "fabrikant", "arkitekt", "direktør", "begge", "ødelæggelse", "permanent", "kristen", "klatre", "økonom", "sats", "kæledyr", "særlig", "metode", "tro", "tid", "konsensus", "spids", "kategori", "forstyrre", "terrorist", "klare", "kat", "ønske", "tur", "skønhed", "knap", "print", "mulighed", "rette", "høring", "levested", "bebrejde", "øverst", "underskud", "veje", "virksomhed", "helt", "implementere", "produktion", "sol", "stand", "plan", "omfavne", "batteri", "sind", "håndbevægelse", "husstand", "lastbil", "begreb", "udseende", "dræbe", "sig", "selv", "hjælpe", "bevise", "universel", "tekst", "uafhængighed", "snart", "nødvendigvis", "sektor", "alkohol", "ansvarlig", "besøg", "ly", "kvarter", "smuds", "bidrag", "kamp", "ankomme", "fodbold", "spejl", "ventilator", "skæbne", "majs", "kræft", "spore", "legeme", "udvælgelse", "uddanne", "fisk", "diagram", "stående", "massiv", "byrde", "tilladelse", "samme", "måler", "vælg", "person", "tilstrækkelig", "vedtage", "instruktion", "musikalsk", "bevare", "kop", "gentage", "skrivebord", "sjæl", "nyttig", "fuldt", "nærme", "overbevise", "psykologi", "detaljeret", "dom", "kyst", "profil", "finansiere", "tale", "repræsentant", "reagere", "tegning", "mandskab", "sekvens", "konsulent", "formode", "skov", "skjule", "lunge", "ankomst", "hjemløs", "kirke", "spændende", "guld", "time", "alligevel", "flytte", "begavet", "brug", "koncentration", "desperat", "væsen", "radio", "skrig", "million", "objektiv", "nederlag", "nederste", "holde", "senior", "matematik", "support", "rose", "pund", "hegn", "medlemskab", "tilmeld", "gyldige", "forsvar", "brun", "kæmpe", "privat", "investering", "fejre", "advarsel", "foreslå", "overrasket", "mord", "garanti", "berømthed", "frugt", "match", "alene", "tættere", "søg", "flaske", "kriterier", "offentlig", "centrum", "argument", "stat", "formel", "opgave", "teknologi", "magtfulde", "sammenhæng", "søge", "chef", "villig", "bekymring", "uddannelse", "ville", "overse", "flad", "højttaler", "forsvinde", "lige", "forbyde", "forbedre", "besøgende", "lancering", "baggrund", "pie", "lugt", "klinisk", "udvej", "alternativ", "afgrøde", "øge", "dele", "indsats", "vært", "betyder", "find", "immigrant", "lænke", "konstant", "strategisk", "stipendium", "skuldertræk", "rådgiver", "bage", "udbyder", "løbet", "enorm", "binde", "omsorg", "flyve", "tung", "indkomst", "let", "bevægelse", "opstå", "bruser", "hen", "imod", "fylde", "mekanisme", "tæt", "nylig", "pensionering", "procedure", "generelt", "henvise", "oversætte", "tildele", "indpakning", "medhjælper", "næste", "håndværk", "dybt", "specialist", "strand", "fundament", "mejse", "overvinde", "plante", "hej", "initial", "forhandling", "hals", "måne", "støvle", "kongres", "forberedelse", "minde", "opmærksomhed", "afsnit", "kunde", "undskyld", "afstand", "din", "passe", "hus", "odds", "nogle", "udvikling", "skandale", "med", "kok", "tårn", "invitere", "skade", "konflikt", "fordi", "guvernør", "også", "rolige", "natur", "hvordan", "venlig", "ledsage", "borgmester", "via", "stolt", "gammel", "erstatte", "lejlighed", "kritisk", "forudsige", "fed", "attribut", "vagt", "vi", "forurening", "nation", "transportør", "søn", "de", "umulig", "hør", "opskrift", "underholdning", "brændstof", "live", "univers", "glide", "foreslog", "indre", "sne", "krænkelse", "sky", "masser", "provins", "gal", "institution", "henviser", "moderne", "initiativ", "republikansk", "begravelse", "urban", "begrænset", "sent", "flyselskab", "kage", "bekostning", "album", "lyd", "rykke", "følge", "mursten", "super", "snor", "høj", "kaffe", "vågne", "leje", "universitetsområde", "bånd", "defensiv", "had", "udvidelse", "mere", "facilitet", "variere", "våben", "styrke", "junior", "faret", "vild", "hemmelighed", "stirre", "efter", "tom", "eliminere", "personale", "version", "bogstaveligt", "talt", "sædvanlig", "adgang", "observation", "opførsel", "fiasko", "psykologisk", "fænomen", "deltage", "informere", "indtægter", "beslutte", "sjovt", "høre", "under", "synes", "råd", "reduktion", "japansk", "overalt", "programmmere", "brygge", ) parts_of_speech: Dict[str, tuple] = {}
Provider
python
uqfoundation__dill
dill/tests/test_nested.py
{ "start": 977, "end": 1188 }
class ____: def __init__(self, augend): self.augend = augend self.zero = [0] def __call__(self, addend): return addend + self.augend + self.zero[0] # some basic class stuff
c2adder
python
doocs__leetcode
solution/3400-3499/3411.Maximum Subarray With Equal Products/Solution.py
{ "start": 0, "end": 486 }
class ____: def maxLength(self, nums: List[int]) -> int: n = len(nums) ans = 0 max_p = lcm(*nums) * max(nums) for i in range(n): p, g, l = 1, 0, 1 for j in range(i, n): p *= nums[j] g = gcd(g, nums[j]) l = lcm(l, nums[j]) if p == g * l: ans = max(ans, j - i + 1) if p > max_p: break return ans
Solution
python
pyca__cryptography
tests/hazmat/primitives/test_kbkdf.py
{ "start": 685, "end": 14619 }
class ____: def test_invalid_key(self, backend): kdf = KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) key = kdf.derive(b"material") kdf = KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) with pytest.raises(InvalidKey): kdf.verify(b"material2", key) def test_already_finalized(self, backend): kdf = KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) kdf.derive(b"material") with pytest.raises(AlreadyFinalized): kdf.derive(b"material2") kdf = KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) key = kdf.derive(b"material") with pytest.raises(AlreadyFinalized): kdf.verify(b"material", key) kdf = KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) kdf.verify(b"material", key) with pytest.raises(AlreadyFinalized): kdf.verify(b"material", key) def test_derive_into(self, backend): kdf = KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) buf = bytearray(32) n = kdf.derive_into(b"material", buf) assert n == 32 # Verify the output matches what derive would produce kdf2 = KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) expected = kdf2.derive(b"material") assert buf == expected @pytest.mark.parametrize(("buflen", "outlen"), [(31, 32), (33, 32)]) def test_derive_into_buffer_incorrect_size(self, buflen, outlen, backend): kdf = KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, outlen, 4, 4, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) buf = bytearray(buflen) with pytest.raises(ValueError, match="buffer must be"): kdf.derive_into(b"material", buf) def test_derive_into_already_finalized(self, backend): kdf = KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) buf = bytearray(32) kdf.derive_into(b"material", buf) with pytest.raises(AlreadyFinalized): kdf.derive_into(b"material2", buf) def test_key_length(self, backend): error = OverflowError if sys.maxsize <= 2**31 else ValueError with pytest.raises(error): KBKDFHMAC( hashes.SHA1(), Mode.CounterMode, 85899345920, 4, 4, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) def test_rlen(self, backend): with pytest.raises(ValueError): KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 5, 4, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) def test_r_type(self, backend): with pytest.raises(TypeError): KBKDFHMAC( hashes.SHA1(), Mode.CounterMode, 32, b"r", # type: ignore[arg-type] 4, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) def test_zero_llen(self, backend): with pytest.raises(ValueError): KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 0, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) def test_l_type(self, backend): with pytest.raises(TypeError): KBKDFHMAC( hashes.SHA1(), Mode.CounterMode, 32, 4, b"l", # type: ignore[arg-type] CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) def test_l(self, backend): with pytest.raises(ValueError): KBKDFHMAC( hashes.SHA1(), Mode.CounterMode, 32, 4, None, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) def test_unsupported_mode(self, backend): with pytest.raises(TypeError): KBKDFHMAC( hashes.SHA256(), None, # type: ignore[arg-type] 32, 4, 4, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) def test_unsupported_location(self, backend): with pytest.raises(TypeError): KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, None, # type: ignore[arg-type] b"label", b"context", None, backend=backend, ) def test_unsupported_parameters(self, backend): with pytest.raises(ValueError): KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.BeforeFixed, b"label", b"context", b"fixed", backend=backend, ) def test_missing_break_location(self, backend): with pytest.raises( ValueError, match=re.escape("Please specify a break_location") ): KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.MiddleFixed, b"label", b"context", None, backend=backend, ) with pytest.raises( ValueError, match=re.escape("Please specify a break_location") ): KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.MiddleFixed, b"label", b"context", None, backend=backend, break_location=None, ) def test_keyword_only_break_location(self, backend): with pytest.raises( TypeError, match=r"\d+ positional arguments but \d+ were given\Z" ): KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.MiddleFixed, b"label", b"context", None, backend, 0, # type: ignore[misc] ) def test_invalid_break_location(self, backend): with pytest.raises(OverflowError): KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.MiddleFixed, b"label", b"context", None, backend=backend, break_location=-1, ) with pytest.raises( ValueError, match=re.escape("break_location offset > len(fixed)") ): kdf = KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.MiddleFixed, b"label", b"context", None, backend=backend, break_location=18, ) kdf.derive(b"input key") def test_ignored_break_location_before(self, backend): with pytest.raises( ValueError, match=re.escape( "break_location is ignored when location is not" " CounterLocation.MiddleFixed" ), ): KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, break_location=0, ) def test_ignored_break_location_after(self, backend): with pytest.raises( ValueError, match=re.escape( "break_location is ignored when location is not" " CounterLocation.MiddleFixed" ), ): KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.AfterFixed, b"label", b"context", None, backend=backend, break_location=0, ) def test_unsupported_hash(self, backend): with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH): KBKDFHMAC( DummyHashAlgorithm(), Mode.CounterMode, 32, 4, 4, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) def test_unsupported_algorithm(self, backend): with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH): KBKDFHMAC( DummyHashAlgorithm(), Mode.CounterMode, 32, 4, 4, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) def test_unicode_error_label(self, backend): with pytest.raises(TypeError): KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.BeforeFixed, "label", # type: ignore[arg-type] b"context", None, backend=backend, ) def test_unicode_error_context(self, backend): with pytest.raises(TypeError): KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.BeforeFixed, b"label", "context", # type: ignore[arg-type] None, backend=backend, ) def test_unicode_error_key_material(self, backend): with pytest.raises(TypeError): kdf = KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 32, 4, 4, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) kdf.derive("material") # type: ignore[arg-type] def test_buffer_protocol(self, backend): kdf = KBKDFHMAC( hashes.SHA256(), Mode.CounterMode, 10, 4, 4, CounterLocation.BeforeFixed, b"label", b"context", None, backend=backend, ) key = kdf.derive(bytearray(b"material")) assert key == b"\xb7\x01\x05\x98\xf5\x1a\x12L\xc7."
TestKBKDFHMAC
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/partition_sets.py
{ "start": 5928, "end": 6126 }
class ____(graphene.ObjectType): class Meta: name = "PartitionKeyRange" start = graphene.NonNull(graphene.String) end = graphene.NonNull(graphene.String)
GraphenePartitionKeyRange
python
sqlalchemy__sqlalchemy
test/dialect/oracle/test_dialect.py
{ "start": 3929, "end": 5280 }
class ____(fixtures.TestBase): __backend__ = True __only_on__ = "oracle+oracledb" def _run_in_process(self, fn, fn_kw=None): if config.db.dialect.is_async: config.skip_test("thick mode unsupported in async mode") ctx = get_context("spawn") queue = ctx.Queue() process = ctx.Process( target=fn, args=(config.db_url, queue), kwargs=fn_kw or {} ) try: process.start() process.join(10) eq_(process.exitcode, 0) return queue.get_nowait() finally: process.kill() @testing.combinations({}, {"thick_mode": None}, {"thick_mode": False}) def test_thin_mode(self, options): from ._oracledb_mode import run_thin_mode mode, is_thin = self._run_in_process(run_thin_mode, options) is_true(is_thin) is_true(mode.startswith("python-oracledb thn")) @testing.combinations(True, {}, {"driver_name": "custom-driver-name"}) def test_thick_mode(self, value): from ._oracledb_mode import run_thick_mode mode, is_thin = self._run_in_process( run_thick_mode, {"thick_mode": value} ) is_false(is_thin) if isinstance(value, dict) and value.get("driver_name"): eq_(mode.strip(), "custom-driver-name")
OracledbMode
python
kubernetes-client__python
kubernetes/client/models/v1_network_policy_list.py
{ "start": 383, "end": 6972 }
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', 'items': 'list[V1NetworkPolicy]', 'kind': 'str', 'metadata': 'V1ListMeta' } attribute_map = { 'api_version': 'apiVersion', 'items': 'items', 'kind': 'kind', 'metadata': 'metadata' } def __init__(self, api_version=None, items=None, kind=None, metadata=None, local_vars_configuration=None): # noqa: E501 """V1NetworkPolicyList - 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._items = None self._kind = None self._metadata = None self.discriminator = None if api_version is not None: self.api_version = api_version self.items = items if kind is not None: self.kind = kind if metadata is not None: self.metadata = metadata @property def api_version(self): """Gets the api_version of this V1NetworkPolicyList. # 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 V1NetworkPolicyList. # noqa: E501 :rtype: str """ return self._api_version @api_version.setter def api_version(self, api_version): """Sets the api_version of this V1NetworkPolicyList. 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 V1NetworkPolicyList. # noqa: E501 :type: str """ self._api_version = api_version @property def items(self): """Gets the items of this V1NetworkPolicyList. # noqa: E501 items is a list of schema objects. # noqa: E501 :return: The items of this V1NetworkPolicyList. # noqa: E501 :rtype: list[V1NetworkPolicy] """ return self._items @items.setter def items(self, items): """Sets the items of this V1NetworkPolicyList. items is a list of schema objects. # noqa: E501 :param items: The items of this V1NetworkPolicyList. # noqa: E501 :type: list[V1NetworkPolicy] """ if self.local_vars_configuration.client_side_validation and items is None: # noqa: E501 raise ValueError("Invalid value for `items`, must not be `None`") # noqa: E501 self._items = items @property def kind(self): """Gets the kind of this V1NetworkPolicyList. # 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 V1NetworkPolicyList. # noqa: E501 :rtype: str """ return self._kind @kind.setter def kind(self, kind): """Sets the kind of this V1NetworkPolicyList. 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 V1NetworkPolicyList. # noqa: E501 :type: str """ self._kind = kind @property def metadata(self): """Gets the metadata of this V1NetworkPolicyList. # noqa: E501 :return: The metadata of this V1NetworkPolicyList. # noqa: E501 :rtype: V1ListMeta """ return self._metadata @metadata.setter def metadata(self, metadata): """Sets the metadata of this V1NetworkPolicyList. :param metadata: The metadata of this V1NetworkPolicyList. # noqa: E501 :type: V1ListMeta """ self._metadata = metadata 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, V1NetworkPolicyList): 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, V1NetworkPolicyList): return True return self.to_dict() != other.to_dict()
V1NetworkPolicyList
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 68788, "end": 69213 }
class ____(axis_ticks_pad_major_x, axis_ticks_pad_major_y): """ Axis major-tick padding Parameters ---------- theme_element : float Value in points. Note ---- Padding is not applied when the [](`~plotnine.theme.themeables.axis_ticks_major`) are blank, but it does apply when the [](`~plotnine.theme.themeables.axis_ticks_length_major`) is zero. """
axis_ticks_pad_major
python
keras-team__keras
keras/src/layers/regularization/spatial_dropout_test.py
{ "start": 135, "end": 3851 }
class ____(test_case.TestCase): @pytest.mark.requires_trainable_backend def test_spatial_dropout_1d(self): self.run_layer_test( layers.SpatialDropout1D, init_kwargs={"rate": 0.5}, call_kwargs={"training": True}, input_shape=(2, 3, 4), assert_built_after_instantiation=True, ) self.run_layer_test( layers.SpatialDropout1D, init_kwargs={"rate": 0.5}, call_kwargs={"training": False}, input_shape=(2, 3, 4), assert_built_after_instantiation=True, ) @pytest.mark.requires_trainable_backend def test_spatial_dropout_2d(self): self.run_layer_test( layers.SpatialDropout2D, init_kwargs={"rate": 0.5}, call_kwargs={"training": True}, input_shape=(2, 3, 4, 5), assert_built_after_instantiation=True, ) self.run_layer_test( layers.SpatialDropout2D, init_kwargs={"rate": 0.5, "data_format": "channels_first"}, call_kwargs={"training": True}, input_shape=(2, 3, 4, 5), assert_built_after_instantiation=True, ) @pytest.mark.requires_trainable_backend def test_spatial_dropout_3d(self): self.run_layer_test( layers.SpatialDropout3D, init_kwargs={"rate": 0.5}, call_kwargs={"training": True}, input_shape=(2, 3, 4, 4, 5), assert_built_after_instantiation=True, ) self.run_layer_test( layers.SpatialDropout3D, init_kwargs={"rate": 0.5, "data_format": "channels_first"}, call_kwargs={"training": True}, input_shape=(2, 3, 4, 4, 5), assert_built_after_instantiation=True, ) def test_spatial_dropout_1D_dynamic(self): inputs = layers.Input((3, 2)) layer = layers.SpatialDropout1D(0.5) layer(inputs, training=True) def test_spatial_dropout_1D_correctness(self): inputs = np.ones((10, 3, 10)) layer = layers.SpatialDropout1D(0.5) outputs = layer(inputs, training=True) self.assertAllClose(outputs[:, 0, :], outputs[:, 1, :]) def test_spatial_dropout_2D_dynamic(self): inputs = layers.Input((3, 2, 4)) layer = layers.SpatialDropout2D(0.5) layer(inputs, training=True) def test_spatial_dropout_2D_correctness(self): if backend.config.image_data_format() == "channels_last": inputs = np.ones((10, 3, 3, 10)) else: inputs = np.ones((10, 10, 3, 3)) layer = layers.SpatialDropout2D(0.5) outputs = layer(inputs, training=True) if backend.config.image_data_format() == "channels_last": self.assertAllClose(outputs[:, 0, 0, :], outputs[:, 1, 1, :]) else: self.assertAllClose(outputs[:, :, 0, 0], outputs[:, :, 1, 1]) def test_spatial_dropout_3D_dynamic(self): inputs = layers.Input((3, 2, 4, 2)) layer = layers.SpatialDropout3D(0.5) layer(inputs, training=True) def test_spatial_dropout_3D_correctness(self): if backend.config.image_data_format() == "channels_last": inputs = np.ones((10, 3, 3, 3, 10)) else: inputs = np.ones((10, 10, 3, 3, 3)) layer = layers.SpatialDropout3D(0.5) outputs = layer(inputs, training=True) if backend.config.image_data_format() == "channels_last": self.assertAllClose(outputs[:, 0, 0, 0, :], outputs[:, 1, 1, 1, :]) else: self.assertAllClose(outputs[:, :, 0, 0, 0], outputs[:, :, 1, 1, 1])
SpatialDropoutTest
python
tensorflow__tensorflow
tensorflow/python/keras/engine/base_layer.py
{ "start": 4304, "end": 123419 }
class ____(module.Module, version_utils.LayerVersionSelector): """This is the class from which all layers inherit. A layer is a callable object that takes as input one or more tensors and that outputs one or more tensors. It involves *computation*, defined in the `call()` method, and a *state* (weight variables), defined either in the constructor `__init__()` or in the `build()` method. Users will just instantiate a layer and then treat it as a callable. Args: trainable: Boolean, whether the layer's variables should be trainable. name: String name of the layer. dtype: The dtype of the layer's computations and weights. Can also be a `tf.keras.mixed_precision.Policy`, which allows the computation and weight dtype to differ. Default of `None` means to use `tf.keras.mixed_precision.global_policy()`, which is a float32 policy unless set to different value. dynamic: Set this to `True` if your layer should only be run eagerly, and should not be used to generate a static computation graph. This would be the case for a Tree-RNN or a recursive network, for example, or generally for any layer that manipulates tensors using Python control flow. If `False`, we assume that the layer can safely be used to generate a static computation graph. Attributes: name: The name of the layer (string). dtype: The dtype of the layer's weights. variable_dtype: Alias of `dtype`. compute_dtype: The dtype of the layer's computations. Layers automatically cast inputs to this dtype which causes the computations and output to also be in this dtype. When mixed precision is used with a `tf.keras.mixed_precision.Policy`, this will be different than `variable_dtype`. dtype_policy: The layer's dtype policy. See the `tf.keras.mixed_precision.Policy` documentation for details. trainable_weights: List of variables to be included in backprop. non_trainable_weights: List of variables that should not be included in backprop. weights: The concatenation of the lists trainable_weights and non_trainable_weights (in this order). trainable: Whether the layer should be trained (boolean), i.e. whether its potentially-trainable weights should be returned as part of `layer.trainable_weights`. input_spec: Optional (list of) `InputSpec` object(s) specifying the constraints on inputs that can be accepted by the layer. We recommend that descendants of `Layer` implement the following methods: * `__init__()`: Defines custom layer attributes, and creates layer state variables that do not depend on input shapes, using `add_weight()`. * `build(self, input_shape)`: This method can be used to create weights that depend on the shape(s) of the input(s), using `add_weight()`. `__call__()` will automatically build the layer (if it has not been built yet) by calling `build()`. * `call(self, inputs, *args, **kwargs)`: Called in `__call__` after making sure `build()` has been called. `call()` performs the logic of applying the layer to the input tensors (which should be passed in as argument). Two reserved keyword arguments you can optionally use in `call()` are: - `training` (boolean, whether the call is in inference mode or training mode). See more details in [the layer/model subclassing guide]( https://www.tensorflow.org/guide/keras/custom_layers_and_models#privileged_training_argument_in_the_call_method) - `mask` (boolean tensor encoding masked timesteps in the input, used in RNN layers). See more details in [the layer/model subclassing guide]( https://www.tensorflow.org/guide/keras/custom_layers_and_models#privileged_mask_argument_in_the_call_method) A typical signature for this method is `call(self, inputs)`, and user could optionally add `training` and `mask` if the layer need them. `*args` and `**kwargs` is only useful for future extension when more input parameters are planned to be added. * `get_config(self)`: Returns a dictionary containing the configuration used to initialize this layer. If the keys differ from the arguments in `__init__`, then override `from_config(self)` as well. This method is used when saving the layer or a model that contains this layer. Examples: Here's a basic example: a layer with two variables, `w` and `b`, that returns `y = w . x + b`. It shows how to implement `build()` and `call()`. Variables set as attributes of a layer are tracked as weights of the layers (in `layer.weights`). ```python class SimpleDense(Layer): def __init__(self, units=32): super(SimpleDense, self).__init__() self.units = units def build(self, input_shape): # Create the state of the layer (weights) w_init = tf.random_normal_initializer() self.w = tf.Variable( initial_value=w_init(shape=(input_shape[-1], self.units), dtype='float32'), trainable=True) b_init = tf.zeros_initializer() self.b = tf.Variable( initial_value=b_init(shape=(self.units,), dtype='float32'), trainable=True) def call(self, inputs): # Defines the computation from inputs to outputs return tf.matmul(inputs, self.w) + self.b # Instantiates the layer. linear_layer = SimpleDense(4) # This will also call `build(input_shape)` and create the weights. y = linear_layer(tf.ones((2, 2))) assert len(linear_layer.weights) == 2 # These weights are trainable, so they're listed in `trainable_weights`: assert len(linear_layer.trainable_weights) == 2 ``` Note that the method `add_weight()` offers a shortcut to create weights: ```python class SimpleDense(Layer): def __init__(self, units=32): super(SimpleDense, self).__init__() self.units = units def build(self, input_shape): self.w = self.add_weight(shape=(input_shape[-1], self.units), initializer='random_normal', trainable=True) self.b = self.add_weight(shape=(self.units,), initializer='random_normal', trainable=True) def call(self, inputs): return tf.matmul(inputs, self.w) + self.b ``` Besides trainable weights, updated via backpropagation during training, layers can also have non-trainable weights. These weights are meant to be updated manually during `call()`. Here's a example layer that computes the running sum of its inputs: ```python class ComputeSum(Layer): def __init__(self, input_dim): super(ComputeSum, self).__init__() # Create a non-trainable weight. self.total = tf.Variable(initial_value=tf.zeros((input_dim,)), trainable=False) def call(self, inputs): self.total.assign_add(tf.reduce_sum(inputs, axis=0)) return self.total my_sum = ComputeSum(2) x = tf.ones((2, 2)) y = my_sum(x) print(y.numpy()) # [2. 2.] y = my_sum(x) print(y.numpy()) # [4. 4.] assert my_sum.weights == [my_sum.total] assert my_sum.non_trainable_weights == [my_sum.total] assert my_sum.trainable_weights == [] ``` For more information about creating layers, see the guide [Making new Layers and Models via subclassing]( https://www.tensorflow.org/guide/keras/custom_layers_and_models) """ # See tf.Module for the usage of this property. # The key for _obj_reference_counts_dict is a Trackable, which could be a # variable or layer etc. tf.Module._flatten will fail to flatten the key # since it is trying to convert Trackable to a string. This attribute can be # ignored even after the fix of nest lib, since the trackable object should # already been available as individual attributes. _obj_reference_counts_dict # just contains a copy of them. _TF_MODULE_IGNORED_PROPERTIES = frozenset(itertools.chain( ('_obj_reference_counts_dict',), module.Module._TF_MODULE_IGNORED_PROPERTIES )) # When loading from a SavedModel, Layers typically can be revived into a # generic Layer wrapper. Sometimes, however, layers may implement methods # that go beyond this wrapper, as in the case of PreprocessingLayers' # `adapt` method. When this is the case, layer implementers can override # must_restore_from_config to return True; layers with this property must # be restored into their actual objects (and will fail if the object is # not available to the restoration code). _must_restore_from_config = False def _get_cell_name(self): canonical_name = get_canonical_name_for_symbol( self.__class__, api_name='keras', add_prefix_to_v1_names=True) if canonical_name is not None: return 'tf.{}'.format(canonical_name) return self.__class__.__module__ + '.' + self.__class__.__name__ def _instrument_layer_creation(self): self._instrumented_keras_api = False self._instrumented_keras_layer_class = False self._instrumented_keras_model_class = False if not getattr(self, '_disable_keras_instrumentation', False): self._instrumented_keras_api = True if getattr(self, '_is_model_for_instrumentation', False): self._instrumented_keras_model_class = True else: self._instrumented_keras_layer_class = True @trackable.no_automatic_dependency_tracking def __init__(self, trainable=True, name=None, dtype=None, dynamic=False, **kwargs): self._instrument_layer_creation() # These properties should be set by the user via keyword arguments. # note that 'dtype', 'input_shape' and 'batch_input_shape' # are only applicable to input layers: do not pass these keywords # to non-input layers. allowed_kwargs = { 'input_dim', 'input_shape', 'batch_input_shape', 'batch_size', 'weights', 'activity_regularizer', 'autocast', 'implementation', } # Validate optional keyword arguments. generic_utils.validate_kwargs(kwargs, allowed_kwargs) # Mutable properties # Indicates whether the layer's weights are updated during training # and whether the layer's updates are run during training. self._trainable = trainable # A stateful layer is a layer whose updates are run during inference too, # for instance stateful RNNs. self._stateful = False # Indicates whether `build` needs to be called upon layer call, to create # the layer's weights. self.built = False # Provides information about which inputs are compatible with the layer. self._input_spec = None # SavedModel-related attributes. # Record the build input shape for loading purposes. # TODO(kathywu): Move this to Layer._set_save_spec once cl/290121460 is # submitted. self._build_input_shape = None self._saved_model_inputs_spec = None # `Layer.compute_mask` will be called at the end of `Layer.__call__` if # `Layer.compute_mask` is overridden, or if the `Layer` subclass sets # `self.supports_masking=True`. self._supports_masking = not generic_utils.is_default(self.compute_mask) self._init_set_name(name) self._activity_regularizer = regularizers.get( kwargs.pop('activity_regularizer', None)) self._maybe_create_attribute('_trainable_weights', []) self._maybe_create_attribute('_non_trainable_weights', []) self._updates = [] # Object to store all thread local layer properties. self._thread_local = threading.local() # A list of zero-argument lambdas which return Tensors, used for variable # regularizers. self._callable_losses = [] # A list of symbolic Tensors containing activity regularizers and losses # manually added through `add_loss` in graph-building mode. self._losses = [] # A list of metric instances corresponding to the symbolic metric tensors # added using the `add_metric` API. self._metrics = [] # Ensures the same metric is not added multiple times in `MirroredStrategy`. self._metrics_lock = threading.Lock() # Both graph and subclassed networks have a dtype policy. For graph # networks, the policy's compute and variable dtypes are ignored. Such # networks only use the policy if it is a PolicyV1, in which case it uses # the PolicyV1's loss_scale (Policy does not have a loss_scale). For # subclassed networks, the compute and variable dtypes are used as like any # ordinary layer. self._set_dtype_policy(dtype) # Boolean indicating whether the layer automatically casts its inputs to the # layer's compute_dtype. self._autocast = kwargs.get('autocast', base_layer_utils.v2_dtype_behavior_enabled()) # Tracks `TrackableDataStructure`s, `Module`s, and `Layer`s. # Ordered by when the object was assigned as an attr. # Entries are unique. self._maybe_create_attribute('_self_tracked_trackables', []) # These lists will be filled via successive calls # to self._add_inbound_node(). # Used in symbolic mode only, only in conjunction with graph-networks self._inbound_nodes_value = [] self._outbound_nodes_value = [] self._init_call_fn_args() # Whether the `call` method can be used to build a TF graph without issues. # This attribute has no effect if the model is created using the Functional # API. Instead, `model.dynamic` is determined based on the internal layers. self._dynamic = dynamic # Manage input shape information if passed. if 'input_dim' in kwargs and 'input_shape' not in kwargs: # Backwards compatibility: alias 'input_dim' to 'input_shape'. kwargs['input_shape'] = (kwargs['input_dim'],) if 'input_shape' in kwargs or 'batch_input_shape' in kwargs: # In this case we will later create an input layer # to insert before the current layer if 'batch_input_shape' in kwargs: batch_input_shape = tuple(kwargs['batch_input_shape']) elif 'input_shape' in kwargs: if 'batch_size' in kwargs: batch_size = kwargs['batch_size'] else: batch_size = None batch_input_shape = (batch_size,) + tuple(kwargs['input_shape']) self._batch_input_shape = batch_input_shape # Manage initial weight values if passed. self._initial_weights = kwargs.get('weights', None) # Whether the layer will track any layers that is set as attribute on itself # as sub-layers, the weights from the sub-layers will be included in the # parent layer's variables() as well. # Default to True, which means auto tracking is turned on. Certain subclass # might want to turn it off, like Sequential model. self._auto_track_sub_layers = True # For backwards compat reasons, most built-in layers do not guarantee # That they will 100% preserve the structure of input args when saving # / loading configs. E.g. they may un-nest an arg that is # a list with one element. self._preserve_input_structure_in_config = False @trackable.no_automatic_dependency_tracking @generic_utils.default def build(self, input_shape): """Creates the variables of the layer (optional, for subclass implementers). This is a method that implementers of subclasses of `Layer` or `Model` can override if they need a state-creation step in-between layer instantiation and layer call. This is typically used to create the weights of `Layer` subclasses. Args: input_shape: Instance of `TensorShape`, or list of instances of `TensorShape` if the layer expects a list of inputs (one instance per input). """ # Only record the build input shapes of overridden build methods. if not hasattr(self.build, '_is_default'): self._build_input_shape = input_shape self.built = True @doc_controls.for_subclass_implementers def call(self, inputs, *args, **kwargs): # pylint: disable=unused-argument """This is where the layer's logic lives. Note here that `call()` method in `tf.keras` is little bit different from `keras` API. In `keras` API, you can pass support masking for layers as additional arguments. Whereas `tf.keras` has `compute_mask()` method to support masking. Args: inputs: Input tensor, or dict/list/tuple of input tensors. The first positional `inputs` argument is subject to special rules: - `inputs` must be explicitly passed. A layer cannot have zero arguments, and `inputs` cannot be provided via the default value of a keyword argument. - NumPy array or Python scalar values in `inputs` get cast as tensors. - Keras mask metadata is only collected from `inputs`. - Layers are built (`build(input_shape)` method) using shape info from `inputs` only. - `input_spec` compatibility is only checked against `inputs`. - Mixed precision input casting is only applied to `inputs`. If a layer has tensor arguments in `*args` or `**kwargs`, their casting behavior in mixed precision should be handled manually. - The SavedModel input specification is generated using `inputs` only. - Integration with various ecosystem packages like TFMOT, TFLite, TF.js, etc is only supported for `inputs` and not for tensors in positional and keyword arguments. *args: Additional positional arguments. May contain tensors, although this is not recommended, for the reasons above. **kwargs: Additional keyword arguments. May contain tensors, although this is not recommended, for the reasons above. The following optional keyword arguments are reserved: - `training`: Boolean scalar tensor of Python boolean indicating whether the `call` is meant for training or inference. - `mask`: Boolean input mask. If the layer's `call()` method takes a `mask` argument, its default value will be set to the mask generated for `inputs` by the previous layer (if `input` did come from a layer that generated a corresponding mask, i.e. if it came from a Keras layer with masking support). Returns: A tensor or list/tuple of tensors. """ return inputs @doc_controls.for_subclass_implementers def _add_trackable(self, trackable_object, trainable): """Adds a Trackable object to this layer's state. Args: trackable_object: The tf.tracking.Trackable object to add. trainable: Boolean, whether the variable should be part of the layer's "trainable_variables" (e.g. variables, biases) or "non_trainable_variables" (e.g. BatchNorm mean and variance). Returns: The TrackableWeightHandler used to track this object. """ if isinstance(trackable_object, base_layer_utils.TrackableWeightHandler): handler = trackable_object else: handler = base_layer_utils.TrackableWeightHandler(trackable_object) if trainable: self._trainable_weights.append(handler) else: self._non_trainable_weights.append(handler) return handler @doc_controls.for_subclass_implementers def add_weight(self, name=None, shape=None, dtype=None, initializer=None, regularizer=None, trainable=None, constraint=None, use_resource=None, synchronization=tf_variables.VariableSynchronization.AUTO, aggregation=tf_variables.VariableAggregation.NONE, **kwargs): """Adds a new variable to the layer. Args: name: Variable name. shape: Variable shape. Defaults to scalar if unspecified. dtype: The type of the variable. Defaults to `self.dtype`. initializer: Initializer instance (callable). regularizer: Regularizer instance (callable). trainable: Boolean, whether the variable should be part of the layer's "trainable_variables" (e.g. variables, biases) or "non_trainable_variables" (e.g. BatchNorm mean and variance). Note that `trainable` cannot be `True` if `synchronization` is set to `ON_READ`. constraint: Constraint instance (callable). use_resource: Whether to use `ResourceVariable`. synchronization: Indicates when a distributed a variable will be aggregated. Accepted values are constants defined in the class `tf.VariableSynchronization`. By default the synchronization is set to `AUTO` and the current `DistributionStrategy` chooses when to synchronize. If `synchronization` is set to `ON_READ`, `trainable` must not be set to `True`. aggregation: Indicates how a distributed variable will be aggregated. Accepted values are constants defined in the class `tf.VariableAggregation`. **kwargs: Additional keyword arguments. Accepted values are `getter`, `collections`, `experimental_autocast` and `caching_device`. Returns: The variable created. Raises: ValueError: When giving unsupported dtype and no initializer or when trainable has been set to True with synchronization set as `ON_READ`. """ if shape is None: shape = () kwargs.pop('partitioner', None) # Ignored. # Validate optional keyword arguments. for kwarg in kwargs: if kwarg not in ['collections', 'experimental_autocast', 'caching_device', 'getter']: raise TypeError('Unknown keyword argument:', kwarg) collections_arg = kwargs.pop('collections', None) # 'experimental_autocast' can be set to False by the caller to indicate an # AutoCastVariable should never be created. autocast = kwargs.pop('experimental_autocast', True) # See the docstring for tf.Variable about the details for caching_device. caching_device = kwargs.pop('caching_device', None) if dtype is None: dtype = self.dtype or backend.floatx() dtype = dtypes.as_dtype(dtype) if self._dtype_policy.variable_dtype is None: # The policy is "_infer", so we infer the policy from the variable dtype. self._set_dtype_policy(policy.Policy(dtype.base_dtype.name)) initializer = initializers.get(initializer) regularizer = regularizers.get(regularizer) constraint = constraints.get(constraint) if synchronization == tf_variables.VariableSynchronization.ON_READ: if trainable: raise ValueError( 'Synchronization value can be set to ' 'VariableSynchronization.ON_READ only for non-trainable variables. ' 'You have specified trainable=True and ' 'synchronization=VariableSynchronization.ON_READ.') else: # Set trainable to be false when variable is to be synced on read. trainable = False elif trainable is None: trainable = True # Initialize variable when no initializer provided if initializer is None: # If dtype is DT_FLOAT, provide a uniform unit scaling initializer if dtype.is_floating: initializer = initializers.get('glorot_uniform') # If dtype is DT_INT/DT_UINT, provide a default value `zero` # If dtype is DT_BOOL, provide a default value `FALSE` elif dtype.is_integer or dtype.is_unsigned or dtype.is_bool: initializer = initializers.get('zeros') # NOTES:Do we need to support for handling DT_STRING and DT_COMPLEX here? elif 'getter' not in kwargs: # When `getter` is specified, it's possibly fine for `initializer` to be # None since it's up to the custom `getter` to raise error in case it # indeed needs `initializer`. raise ValueError('An initializer for variable %s of type %s is required' ' for layer %s' % (name, dtype.base_dtype, self.name)) getter = kwargs.pop('getter', base_layer_utils.make_variable) if (autocast and self._dtype_policy.compute_dtype != self._dtype_policy.variable_dtype and dtype.is_floating): old_getter = getter # Wrap variable constructor to return an AutoCastVariable. def getter(*args, **kwargs): # pylint: disable=function-redefined variable = old_getter(*args, **kwargs) return autocast_variable.create_autocast_variable(variable) # Also the caching_device does not work with the mixed precision API, # disable it if it is specified. # TODO(b/142020079): Reenable it once the bug is fixed. if caching_device is not None: tf_logging.warning( '`caching_device` does not work with mixed precision API. Ignoring ' 'user specified `caching_device`.') caching_device = None variable = self._add_variable_with_custom_getter( name=name, shape=shape, # TODO(allenl): a `make_variable` equivalent should be added as a # `Trackable` method. getter=getter, # Manage errors in Layer rather than Trackable. overwrite=True, initializer=initializer, dtype=dtype, constraint=constraint, trainable=trainable, use_resource=use_resource, collections=collections_arg, synchronization=synchronization, aggregation=aggregation, caching_device=caching_device) if regularizer is not None: # TODO(fchollet): in the future, this should be handled at the # level of variable creation, and weight regularization losses # should be variable attributes. name_in_scope = variable.name[:variable.name.find(':')] self._handle_weight_regularization(name_in_scope, variable, regularizer) if base_layer_utils.is_split_variable(variable): for v in variable: backend.track_variable(v) if trainable: self._trainable_weights.append(v) else: self._non_trainable_weights.append(v) else: backend.track_variable(variable) if trainable: self._trainable_weights.append(variable) else: self._non_trainable_weights.append(variable) return variable @generic_utils.default def get_config(self): """Returns the config of the layer. A layer config is a Python dictionary (serializable) containing the configuration of a layer. The same layer can be reinstantiated later (without its trained weights) from this configuration. The config of a layer does not include connectivity information, nor the layer class name. These are handled by `Network` (one layer of abstraction above). Note that `get_config()` does not guarantee to return a fresh copy of dict every time it is called. The callers should make a copy of the returned dict if they want to modify it. Returns: Python dictionary. """ all_args = tf_inspect.getfullargspec(self.__init__).args config = { 'name': self.name, 'trainable': self.trainable, } if hasattr(self, '_batch_input_shape'): config['batch_input_shape'] = self._batch_input_shape config['dtype'] = policy.serialize(self._dtype_policy) if hasattr(self, 'dynamic'): # Only include `dynamic` in the `config` if it is `True` if self.dynamic: config['dynamic'] = self.dynamic elif 'dynamic' in all_args: all_args.remove('dynamic') expected_args = config.keys() # Finds all arguments in the `__init__` that are not in the config: extra_args = [arg for arg in all_args if arg not in expected_args] # Check that either the only argument in the `__init__` is `self`, # or that `get_config` has been overridden: if len(extra_args) > 1 and hasattr(self.get_config, '_is_default'): raise NotImplementedError('Layer %s has arguments in `__init__` and ' 'therefore must override `get_config`.' % self.__class__.__name__) return config @classmethod def from_config(cls, config): """Creates a layer from its config. This method is the reverse of `get_config`, capable of instantiating the same layer from the config dictionary. It does not handle layer connectivity (handled by Network), nor weights (handled by `set_weights`). Args: config: A Python dictionary, typically the output of get_config. Returns: A layer instance. """ return cls(**config) def compute_output_shape(self, input_shape): """Computes the output shape of the layer. If the layer has not been built, this method will call `build` on the layer. This assumes that the layer will later be used with inputs that match the input shape provided here. Args: input_shape: Shape tuple (tuple of integers) or list of shape tuples (one per output tensor of the layer). Shape tuples can include None for free dimensions, instead of an integer. Returns: An input shape tuple. """ if context.executing_eagerly(): # In this case we build the model first in order to do shape inference. # This is acceptable because the framework only calls # `compute_output_shape` on shape values that the layer would later be # built for. It would however cause issues in case a user attempts to # use `compute_output_shape` manually with shapes that are incompatible # with the shape the Layer will be called on (these users will have to # implement `compute_output_shape` themselves). self._maybe_build(input_shape) with func_graph.FuncGraph(str(self.name) + '_scratch_graph').as_default(): input_shape = tf_utils.convert_shapes(input_shape, to_tuples=False) def _make_placeholder_like(shape): ph = backend.placeholder(shape=shape, dtype=self.dtype) ph._keras_mask = None return ph inputs = nest.map_structure(_make_placeholder_like, input_shape) try: outputs = self(inputs, training=False) except TypeError as e: raise NotImplementedError( 'We could not automatically infer the static shape of the ' 'layer\'s output. Please implement the ' '`compute_output_shape` method on your layer (%s).' % self.__class__.__name__) from e return nest.map_structure(lambda t: t.shape, outputs) raise NotImplementedError( 'Please run in eager mode or implement the `compute_output_shape` ' 'method on your layer (%s).' % self.__class__.__name__) @doc_controls.for_subclass_implementers def compute_output_signature(self, input_signature): """Compute the output tensor signature of the layer based on the inputs. Unlike a TensorShape object, a TensorSpec object contains both shape and dtype information for a tensor. This method allows layers to provide output dtype information if it is different from the input dtype. For any layer that doesn't implement this function, the framework will fall back to use `compute_output_shape`, and will assume that the output dtype matches the input dtype. Args: input_signature: Single TensorSpec or nested structure of TensorSpec objects, describing a candidate input for the layer. Returns: Single TensorSpec or nested structure of TensorSpec objects, describing how the layer would transform the provided input. Raises: TypeError: If input_signature contains a non-TensorSpec object. """ def check_type_return_shape(s): if not isinstance(s, tensor_lib.TensorSpec): raise TypeError('Only TensorSpec signature types are supported, ' 'but saw signature entry: {}.'.format(s)) return s.shape input_shape = nest.map_structure(check_type_return_shape, input_signature) output_shape = self.compute_output_shape(input_shape) dtype = self._compute_dtype if dtype is None: input_dtypes = [s.dtype for s in nest.flatten(input_signature)] # Default behavior when self.dtype is None, is to use the first input's # dtype. dtype = input_dtypes[0] return nest.map_structure( lambda s: tensor_lib.TensorSpec(dtype=dtype, shape=s), output_shape) def _keras_tensor_symbolic_call(self, inputs, input_masks, args, kwargs): if self.dynamic: # We will use static shape inference to return symbolic tensors # matching the specifications of the layer outputs. # Since `self.dynamic` is True, we will never attempt to # run the underlying TF graph (which is disconnected). # TODO(fchollet): consider py_func as an alternative, which # would enable us to run the underlying graph if needed. input_signature = nest.map_structure( lambda x: tensor_lib.TensorSpec(shape=x.shape, dtype=x.dtype), inputs) output_signature = self.compute_output_signature(input_signature) return nest.map_structure(keras_tensor.KerasTensor, output_signature) else: return self._infer_output_signature(inputs, args, kwargs, input_masks) def _infer_output_signature(self, inputs, args, kwargs, input_masks): """TODO(kaftan): Docstring.""" call_fn = self.call # Wrapping `call` function in autograph to allow for dynamic control # flow and control dependencies in call. We are limiting this to # subclassed layers as autograph is strictly needed only for # subclassed layers and models. # tf_convert will respect the value of autograph setting in the # enclosing tf.function, if any. if (base_layer_utils.is_subclassed(self) and not base_layer_utils.from_saved_model(self)): call_fn = autograph.tf_convert(self.call, ag_ctx.control_status_ctx()) # We enter a scratch graph and build placeholder inputs inside of it that # match the input args. # We then call the layer inside of the scratch graph to identify the # output signatures, then we build KerasTensors corresponding to those # outputs. scratch_graph = func_graph.FuncGraph(str(self.name) + '_scratch_graph') with scratch_graph.as_default(): inputs = nest.map_structure( keras_tensor.keras_tensor_to_placeholder, inputs) args = nest.map_structure( keras_tensor.keras_tensor_to_placeholder, args) kwargs = nest.map_structure( keras_tensor.keras_tensor_to_placeholder, kwargs) input_masks = nest.map_structure( keras_tensor.keras_tensor_to_placeholder, input_masks) with backend.name_scope(self._name_scope()): # pylint: disable=not-callable with autocast_variable.enable_auto_cast_variables( self._compute_dtype_object): # Build layer if applicable (if the `build` method has been # overridden). # TODO(kaftan): do we maybe_build here, or have we already done it? self._maybe_build(inputs) inputs = self._maybe_cast_inputs(inputs) outputs = call_fn(inputs, *args, **kwargs) self._handle_activity_regularization(inputs, outputs) self._set_mask_metadata(inputs, outputs, input_masks, build_graph=False) outputs = nest.map_structure( keras_tensor.keras_tensor_from_tensor, outputs) if hasattr(self, '_set_inputs') and not self.inputs: # TODO(kaftan): figure out if we need to do this at all # Subclassed network: explicitly set metadata normally set by # a call to self._set_inputs(). self._set_inputs(inputs, outputs) del scratch_graph return outputs @generic_utils.default def compute_mask(self, inputs, mask=None): # pylint: disable=unused-argument """Computes an output mask tensor. Args: inputs: Tensor or list of tensors. mask: Tensor or list of tensors. Returns: None or a tensor (or list of tensors, one per output tensor of the layer). """ if not self._supports_masking: if any(m is not None for m in nest.flatten(mask)): raise TypeError('Layer ' + self.name + ' does not support masking, ' 'but was passed an input_mask: ' + str(mask)) # masking not explicitly supported: return None as mask. return None # if masking is explicitly supported, by default # carry over the input mask return mask def __call__(self, *args, **kwargs): """Wraps `call`, applying pre- and post-processing steps. Args: *args: Positional arguments to be passed to `self.call`. **kwargs: Keyword arguments to be passed to `self.call`. Returns: Output tensor(s). Note: - The following optional keyword arguments are reserved for specific uses: * `training`: Boolean scalar tensor of Python boolean indicating whether the `call` is meant for training or inference. * `mask`: Boolean input mask. - If the layer's `call` method takes a `mask` argument (as some Keras layers do), its default value will be set to the mask generated for `inputs` by the previous layer (if `input` did come from a layer that generated a corresponding mask, i.e. if it came from a Keras layer with masking support. - If the layer is not built, the method will call `build`. Raises: ValueError: if the layer's `call` method returns None (an invalid value). RuntimeError: if `super().__init__()` was not called in the constructor. """ if not hasattr(self, '_thread_local'): raise RuntimeError( 'You must call `super().__init__()` in the layer constructor.') # `inputs` (the first arg in the method spec) is special cased in # layer call due to historical reasons. # This special casing currently takes the form of: # - 'inputs' must be explicitly passed. A layer cannot have zero arguments, # and inputs cannot have been provided via the default value of a kwarg. # - numpy/scalar values in `inputs` get converted to tensors # - implicit masks / mask metadata are only collected from 'inputs` # - Layers are built using shape info from 'inputs' only # - input_spec compatibility is only checked against `inputs` # - mixed precision casting (autocast) is only applied to `inputs`, # not to any other argument. # - setting the SavedModel saving spec. inputs, args, kwargs = self._split_out_first_arg(args, kwargs) input_list = nest.flatten(inputs) # Functional Model construction mode is invoked when `Layer`s are called on # symbolic `KerasTensor`s, i.e.: # >> inputs = tf.keras.Input(10) # >> outputs = MyLayer()(inputs) # Functional construction mode. # >> model = tf.keras.Model(inputs, outputs) if _in_functional_construction_mode(self, inputs, args, kwargs, input_list): return self._functional_construction_call(inputs, args, kwargs, input_list) # Maintains info about the `Layer.call` stack. call_context = base_layer_utils.call_context() # Accept NumPy and scalar inputs by converting to Tensors. if any(isinstance(x, ( np_arrays.ndarray, np.ndarray, float, int)) for x in input_list): inputs = nest.map_structure(_convert_numpy_or_python_types, inputs) input_list = nest.flatten(inputs) # Handle `mask` propagation from previous layer to current layer. Masks can # be propagated explicitly via the `mask` argument, or implicitly via # setting the `_keras_mask` attribute on the inputs to a Layer. Masks passed # explicitly take priority. input_masks, mask_is_implicit = self._get_input_masks( inputs, input_list, args, kwargs) if self._expects_mask_arg and mask_is_implicit: kwargs['mask'] = input_masks # Training mode for `Layer.call` is set via (in order of priority): # (1) The `training` argument passed to this `Layer.call`, if it is not None # (2) The training mode of an outer `Layer.call`. # (3) The default mode set by `tf.keras.backend.set_learning_phase` (if set) # (4) Any non-None default value for `training` specified in the call # signature # (5) False (treating the layer as if it's in inference) args, kwargs, training_mode = self._set_training_mode( args, kwargs, call_context) # Losses are cleared for all sublayers on the outermost `Layer.call`. # Losses are not cleared on inner `Layer.call`s, because sublayers can be # called multiple times. if not call_context.in_call: self._clear_losses() eager = context.executing_eagerly() with call_context.enter( layer=self, inputs=inputs, build_graph=not eager, training=training_mode): input_spec.assert_input_compatibility(self.input_spec, inputs, self.name) if eager: call_fn = self.call name_scope = self._name else: name_scope = self._name_scope() # Avoid autoincrementing. # pylint: disable=not-callable call_fn = self._autographed_call() with ops.name_scope_v2(name_scope): if not self.built: self._maybe_build(inputs) if self._autocast: inputs = self._maybe_cast_inputs(inputs, input_list) with autocast_variable.enable_auto_cast_variables( self._compute_dtype_object): outputs = call_fn(inputs, *args, **kwargs) if self._activity_regularizer: self._handle_activity_regularization(inputs, outputs) if self._supports_masking: self._set_mask_metadata(inputs, outputs, input_masks, not eager) if self._saved_model_inputs_spec is None: self._set_save_spec(inputs) return outputs def _functional_construction_call(self, inputs, args, kwargs, input_list): call_context = base_layer_utils.call_context() # Accept NumPy and scalar inputs by converting to Tensors. if any(isinstance(x, ( np_arrays.ndarray, np.ndarray, float, int)) for x in input_list): def _convert_non_tensor(x): # Don't call `ops.convert_to_tensor` on all `inputs` because # `SparseTensors` can't be converted to `Tensor`. if isinstance(x, (np_arrays.ndarray, np.ndarray, float, int)): return tensor_conversion.convert_to_tensor_v2_with_dispatch(x) return x inputs = nest.map_structure(_convert_non_tensor, inputs) input_list = nest.flatten(inputs) # Handle `mask` propagation from previous layer to current layer. Masks can # be propagated explicitly via the `mask` argument, or implicitly via # setting the `_keras_mask` attribute on the inputs to a Layer. Masks passed # explicitly take priority. mask_arg_passed_by_framework = False input_masks, mask_is_implicit = self._get_input_masks( inputs, input_list, args, kwargs) if self._expects_mask_arg and mask_is_implicit: kwargs['mask'] = input_masks mask_arg_passed_by_framework = True # If `training` argument is None or not explicitly passed, # propagate `training` value from this layer's calling layer. training_value = None training_arg_passed_by_framework = False # Priority 1: `training` was explicitly passed a non-None value. if self._call_arg_was_passed('training', args, kwargs): training_value = self._get_call_arg_value('training', args, kwargs) if not self._expects_training_arg: kwargs.pop('training') if training_value is None: # Priority 2: `training` was passed to a parent layer. if call_context.training is not None: training_value = call_context.training # Priority 3: `learning_phase()` has been set. elif backend.global_learning_phase_is_set(): training_value = backend.learning_phase() # Force the training_value to be bool type which matches to the contract # for layer/model call args. if tensor_util.is_tf_type(training_value): training_value = math_ops.cast(training_value, dtypes.bool) else: training_value = bool(training_value) # Priority 4: trace layer with the default training argument specified # in the `call` signature (or in inference mode if the `call` signature # specifies no non-None default). else: training_value = self._default_training_arg # In cases (2), (3), (4) the training argument is passed automatically # by the framework, and will not be hard-coded into the model. if self._expects_training_arg: args, kwargs = self._set_call_arg_value('training', training_value, args, kwargs) training_arg_passed_by_framework = True with call_context.enter( layer=self, inputs=inputs, build_graph=True, training=training_value): # Check input assumptions set after layer building, e.g. input shape. outputs = self._keras_tensor_symbolic_call( inputs, input_masks, args, kwargs) if outputs is None: raise ValueError('A layer\'s `call` method should return a ' 'Tensor or a list of Tensors, not None ' '(layer: ' + self.name + ').') if training_arg_passed_by_framework: args, kwargs = self._set_call_arg_value( 'training', None, args, kwargs, pop_kwarg_if_none=True) if mask_arg_passed_by_framework: kwargs.pop('mask') # Node connectivity does not special-case the first argument. outputs = self._set_connectivity_metadata((inputs,) + args, kwargs, outputs) return outputs def _set_training_mode(self, args, kwargs, call_context): training_mode = None if self._expects_training_arg: # (1) `training` was passed to this `Layer.call`. if self._call_arg_was_passed('training', args, kwargs): training_mode = self._get_call_arg_value('training', args, kwargs) # If no `training` arg was passed, or `None` was explicitly passed, # the framework will make a decision about the training mode is. if training_mode is None: call_ctx_training = call_context.training # (2) `training` mode is inferred from an outer `Layer.call`. if call_ctx_training is not None: training_mode = call_ctx_training # (3) User set `tf.keras.backend.set_learning_phase`. elif backend.global_learning_phase_is_set(): training_mode = backend.learning_phase() # Ensure value is a `bool` or `tf.bool`. if isinstance(training_mode, bool): pass elif tensor_util.is_tf_type(training_mode): training_mode = math_ops.cast(training_mode, dtypes.bool) else: training_mode = bool(training_mode) # (4) We default to using `call`'s default value for `training`, # or treating the layer as if it is in inference if no non-None default # is specified in the `call` signature. else: training_mode = self._default_training_arg # For case (2), (3), (4) `training` arg is passed by framework. args, kwargs = self._set_call_arg_value('training', training_mode, args, kwargs) else: if 'training' in kwargs: # `training` was passed to this `Layer` but is not needed for # `Layer.call`. It will set the default mode for inner `Layer.call`s. training_mode = kwargs.pop('training') else: # Grab the current `training` mode from any outer `Layer.call`. training_mode = call_context.training return args, kwargs, training_mode def _autographed_call(self): # Wrapping `call` function in autograph to allow for dynamic control # flow and control dependencies in call. We are limiting this to # subclassed layers as autograph is strictly needed only for # subclassed layers and models. # tf_convert will respect the value of autograph setting in the # enclosing tf.function, if any. if (base_layer_utils.is_subclassed(self) and not base_layer_utils.from_saved_model(self)): return autograph.tf_convert(self.call, ag_ctx.control_status_ctx()) else: return self.call @property def dtype(self): """The dtype of the layer weights. This is equivalent to `Layer.dtype_policy.variable_dtype`. Unless mixed precision is used, this is the same as `Layer.compute_dtype`, the dtype of the layer's computations. """ return self._dtype_policy.variable_dtype @property def name(self): """Name of the layer (string), set in the constructor.""" return self._name @property def supports_masking(self): """Whether this layer supports computing a mask using `compute_mask`.""" return self._supports_masking @supports_masking.setter def supports_masking(self, value): self._supports_masking = value @property def dynamic(self): """Whether the layer is dynamic (eager-only); set in the constructor.""" return any(layer._dynamic for layer in self._flatten_layers()) @property @doc_controls.do_not_doc_inheritable def stateful(self): return any(layer._stateful for layer in self._flatten_layers()) @stateful.setter def stateful(self, value): self._stateful = value @property def trainable(self): return self._trainable @trainable.setter def trainable(self, value): for layer in self._flatten_layers(): layer._trainable = value @property def activity_regularizer(self): """Optional regularizer function for the output of this layer.""" return self._activity_regularizer @activity_regularizer.setter def activity_regularizer(self, regularizer): """Optional regularizer function for the output of this layer.""" self._activity_regularizer = regularizer @property def input_spec(self): """`InputSpec` instance(s) describing the input format for this layer. When you create a layer subclass, you can set `self.input_spec` to enable the layer to run input compatibility checks when it is called. Consider a `Conv2D` layer: it can only be called on a single input tensor of rank 4. As such, you can set, in `__init__()`: ```python self.input_spec = tf.keras.layers.InputSpec(ndim=4) ``` Now, if you try to call the layer on an input that isn't rank 4 (for instance, an input of shape `(2,)`, it will raise a nicely-formatted error: ``` ValueError: Input 0 of layer conv2d is incompatible with the layer: expected ndim=4, found ndim=1. Full shape received: [2] ``` Input checks that can be specified via `input_spec` include: - Structure (e.g. a single input, a list of 2 inputs, etc) - Shape - Rank (ndim) - Dtype For more information, see `tf.keras.layers.InputSpec`. Returns: A `tf.keras.layers.InputSpec` instance, or nested structure thereof. """ return self._input_spec @input_spec.setter # Must be decorated to prevent tracking, since the input_spec can be nested # InputSpec objects. @trackable.no_automatic_dependency_tracking def input_spec(self, value): for v in nest.flatten(value): if v is not None and not isinstance(v, InputSpec): raise TypeError('Layer input_spec must be an instance of InputSpec. ' 'Got: {}'.format(v)) self._input_spec = value @property def trainable_weights(self): """List of all trainable weights tracked by this layer. Trainable weights are updated via gradient descent during training. Returns: A list of trainable variables. """ if self.trainable: children_weights = self._gather_children_attribute('trainable_variables') return self._dedup_weights(self._trainable_weights + children_weights) else: return [] @property def non_trainable_weights(self): """List of all non-trainable weights tracked by this layer. Non-trainable weights are *not* updated during training. They are expected to be updated manually in `call()`. Returns: A list of non-trainable variables. """ if self.trainable: children_weights = self._gather_children_attribute( 'non_trainable_variables') non_trainable_weights = self._non_trainable_weights + children_weights else: children_weights = self._gather_children_attribute('variables') non_trainable_weights = ( self._trainable_weights + self._non_trainable_weights + children_weights) return self._dedup_weights(non_trainable_weights) @property def weights(self): """Returns the list of all layer variables/weights. Returns: A list of variables. """ return self.trainable_weights + self.non_trainable_weights @property @doc_controls.do_not_generate_docs def updates(self): warnings.warn('`layer.updates` will be removed in a future version. ' 'This property should not be used in TensorFlow 2.0, ' 'as `updates` are applied automatically.') return [] @property def losses(self): """List of losses added using the `add_loss()` API. Variable regularization tensors are created when this property is accessed, so it is eager safe: accessing `losses` under a `tf.GradientTape` will propagate gradients back to the corresponding variables. Examples: >>> class MyLayer(tf.keras.layers.Layer): ... def call(self, inputs): ... self.add_loss(tf.abs(tf.reduce_mean(inputs))) ... return inputs >>> l = MyLayer() >>> l(np.ones((10, 1))) >>> l.losses [1.0] >>> inputs = tf.keras.Input(shape=(10,)) >>> x = tf.keras.layers.Dense(10)(inputs) >>> outputs = tf.keras.layers.Dense(1)(x) >>> model = tf.keras.Model(inputs, outputs) >>> # Activity regularization. >>> len(model.losses) 0 >>> model.add_loss(tf.abs(tf.reduce_mean(x))) >>> len(model.losses) 1 >>> inputs = tf.keras.Input(shape=(10,)) >>> d = tf.keras.layers.Dense(10, kernel_initializer='ones') >>> x = d(inputs) >>> outputs = tf.keras.layers.Dense(1)(x) >>> model = tf.keras.Model(inputs, outputs) >>> # Weight regularization. >>> model.add_loss(lambda: tf.reduce_mean(d.kernel)) >>> model.losses [<tf.Tensor: shape=(), dtype=float32, numpy=1.0>] Returns: A list of tensors. """ collected_losses = [] for layer in self._flatten_layers(): # If any eager losses are present, we assume the model to be part of an # eager training loop (either a custom one or the one used when # `run_eagerly=True`) and so we always return just the eager losses. if layer._eager_losses: # Filter placeholder losses that may have been added by revived layers. # (see base_layer_utils for details). if (layer._eager_losses[0] is not base_layer_utils.REVIVED_LOSS_PLACEHOLDER): collected_losses.extend(layer._eager_losses) else: collected_losses.extend(layer._losses) for regularizer in layer._callable_losses: loss_tensor = regularizer() if loss_tensor is not None: collected_losses.append(loss_tensor) return collected_losses def add_loss(self, losses, **kwargs): """Add loss tensor(s), potentially dependent on layer inputs. Some losses (for instance, activity regularization losses) may be dependent on the inputs passed when calling a layer. Hence, when reusing the same layer on different inputs `a` and `b`, some entries in `layer.losses` may be dependent on `a` and some on `b`. This method automatically keeps track of dependencies. This method can be used inside a subclassed layer or model's `call` function, in which case `losses` should be a Tensor or list of Tensors. Example: ```python class MyLayer(tf.keras.layers.Layer): def call(self, inputs): self.add_loss(tf.abs(tf.reduce_mean(inputs))) return inputs ``` This method can also be called directly on a Functional Model during construction. In this case, any loss Tensors passed to this Model must be symbolic and be able to be traced back to the model's `Input`s. These losses become part of the model's topology and are tracked in `get_config`. Example: ```python inputs = tf.keras.Input(shape=(10,)) x = tf.keras.layers.Dense(10)(inputs) outputs = tf.keras.layers.Dense(1)(x) model = tf.keras.Model(inputs, outputs) # Activity regularization. model.add_loss(tf.abs(tf.reduce_mean(x))) ``` If this is not the case for your loss (if, for example, your loss references a `Variable` of one of the model's layers), you can wrap your loss in a zero-argument lambda. These losses are not tracked as part of the model's topology since they can't be serialized. Example: ```python inputs = tf.keras.Input(shape=(10,)) d = tf.keras.layers.Dense(10) x = d(inputs) outputs = tf.keras.layers.Dense(1)(x) model = tf.keras.Model(inputs, outputs) # Weight regularization. model.add_loss(lambda: tf.reduce_mean(d.kernel)) ``` Args: losses: Loss tensor, or list/tuple of tensors. Rather than tensors, losses may also be zero-argument callables which create a loss tensor. **kwargs: Additional keyword arguments for backward compatibility. Accepted values: inputs - Deprecated, will be automatically inferred. """ kwargs.pop('inputs', None) if kwargs: raise TypeError('Unknown keyword arguments: %s' % (kwargs.keys(),)) def _tag_callable(loss): """Tags callable loss tensor as `_unconditional_loss`.""" if callable(loss): # We run the loss without autocasting, as regularizers are often # numerically unstable in float16. with autocast_variable.enable_auto_cast_variables(None): loss = loss() if loss is None: return None # Will be filtered out when computing the .losses property if not tensor_util.is_tf_type(loss): loss = tensor_conversion.convert_to_tensor_v2_with_dispatch( loss, dtype=backend.floatx() ) loss._unconditional_loss = True # pylint: disable=protected-access return loss losses = nest.flatten(losses) callable_losses = [] eager_losses = [] symbolic_losses = [] for loss in losses: if callable(loss): callable_losses.append(functools.partial(_tag_callable, loss)) continue if loss is None: continue if not tensor_util.is_tf_type(loss) and not isinstance( loss, keras_tensor.KerasTensor): loss = tensor_conversion.convert_to_tensor_v2_with_dispatch( loss, dtype=backend.floatx() ) # TF Functions should take the eager path. if ((tf_utils.is_symbolic_tensor(loss) or isinstance(loss, keras_tensor.KerasTensor)) and not base_layer_utils.is_in_tf_function()): symbolic_losses.append(loss) elif tensor_util.is_tf_type(loss): eager_losses.append(loss) self._callable_losses.extend(callable_losses) in_call_context = base_layer_utils.call_context().in_call if eager_losses and not in_call_context: raise ValueError( 'Expected a symbolic Tensors or a callable for the loss value. ' 'Please wrap your loss computation in a zero argument `lambda`.') self._eager_losses.extend(eager_losses) for symbolic_loss in symbolic_losses: if getattr(self, '_is_graph_network', False): self._graph_network_add_loss(symbolic_loss) else: # Possible a loss was added in a Layer's `build`. self._losses.append(symbolic_loss) def _clear_losses(self): """Used every step in eager to reset losses.""" # Set to thread local directly to avoid Layer.__setattr__ overhead. if not getattr(self, '_self_tracked_trackables', None): # Fast path for single Layer. self._thread_local._eager_losses = [] else: for layer in self._flatten_layers(): layer._thread_local._eager_losses = [] @property def metrics(self): """List of metrics added using the `add_metric()` API. Example: >>> input = tf.keras.layers.Input(shape=(3,)) >>> d = tf.keras.layers.Dense(2) >>> output = d(input) >>> d.add_metric(tf.reduce_max(output), name='max') >>> d.add_metric(tf.reduce_min(output), name='min') >>> [m.name for m in d.metrics] ['max', 'min'] Returns: A list of `Metric` objects. """ collected_metrics = [] for layer in self._flatten_layers(): with layer._metrics_lock: collected_metrics.extend(layer._metrics) return collected_metrics def add_metric(self, value, name=None, **kwargs): """Adds metric tensor to the layer. This method can be used inside the `call()` method of a subclassed layer or model. ```python class MyMetricLayer(tf.keras.layers.Layer): def __init__(self): super(MyMetricLayer, self).__init__(name='my_metric_layer') self.mean = tf.keras.metrics.Mean(name='metric_1') def call(self, inputs): self.add_metric(self.mean(inputs)) self.add_metric(tf.reduce_sum(inputs), name='metric_2') return inputs ``` This method can also be called directly on a Functional Model during construction. In this case, any tensor passed to this Model must be symbolic and be able to be traced back to the model's `Input`s. These metrics become part of the model's topology and are tracked when you save the model via `save()`. ```python inputs = tf.keras.Input(shape=(10,)) x = tf.keras.layers.Dense(10)(inputs) outputs = tf.keras.layers.Dense(1)(x) model = tf.keras.Model(inputs, outputs) model.add_metric(math_ops.reduce_sum(x), name='metric_1') ``` Note: Calling `add_metric()` with the result of a metric object on a Functional Model, as shown in the example below, is not supported. This is because we cannot trace the metric result tensor back to the model's inputs. ```python inputs = tf.keras.Input(shape=(10,)) x = tf.keras.layers.Dense(10)(inputs) outputs = tf.keras.layers.Dense(1)(x) model = tf.keras.Model(inputs, outputs) model.add_metric(tf.keras.metrics.Mean()(x), name='metric_1') ``` Args: value: Metric tensor. name: String metric name. **kwargs: Additional keyword arguments for backward compatibility. Accepted values: `aggregation` - When the `value` tensor provided is not the result of calling a `keras.Metric` instance, it will be aggregated by default using a `keras.Metric.Mean`. """ kwargs_keys = list(kwargs.keys()) if (len(kwargs_keys) > 1 or (len(kwargs_keys) == 1 and kwargs_keys[0] != 'aggregation')): raise TypeError('Unknown keyword arguments: ', str(kwargs.keys())) from_metric_obj = hasattr(value, '_metric_obj') is_symbolic = isinstance(value, keras_tensor.KerasTensor) in_call_context = base_layer_utils.call_context().in_call if name is None and not from_metric_obj: # Eg. `self.add_metric(math_ops.reduce_sum(x))` # In eager mode, we use metric name to lookup a metric. Without a name, # a new Mean metric wrapper will be created on every model/layer call. # So, we raise an error when no name is provided. # We will do the same for symbolic mode for consistency although a name # will be generated if no name is provided. # We will not raise this error in the foll use case for the sake of # consistency as name in provided in the metric constructor. # mean = metrics.Mean(name='my_metric') # model.add_metric(mean(outputs)) raise ValueError('Please provide a name for your metric like ' '`self.add_metric(tf.reduce_sum(inputs), ' 'name=\'mean_activation\')`') elif from_metric_obj: name = value._metric_obj.name if not in_call_context and not is_symbolic: raise ValueError('Expected a symbolic Tensor for the metric value, ' 'received: ' + str(value)) # If a metric was added in a Layer's `call` or `build`. if in_call_context or not getattr(self, '_is_graph_network', False): # TF Function path should take the eager path. # If the given metric is available in `metrics` list we just update state # on it, otherwise we create a new metric instance and # add it to the `metrics` list. metric_obj = getattr(value, '_metric_obj', None) # Tensors that come from a Metric object already updated the Metric state. should_update_state = not metric_obj name = metric_obj.name if metric_obj else name with self._metrics_lock: match = self._get_existing_metric(name) if match: metric_obj = match elif metric_obj: self._metrics.append(metric_obj) else: # Build the metric object with the value's dtype if it defines one metric_obj = metrics_mod.Mean( name=name, dtype=getattr(value, 'dtype', None)) self._metrics.append(metric_obj) if should_update_state: metric_obj(value) else: if from_metric_obj: raise ValueError('Using the result of calling a `Metric` object ' 'when calling `add_metric` on a Functional ' 'Model is not supported. Please pass the ' 'Tensor to monitor directly.') # Insert layers into the Keras Graph Network. aggregation = None if from_metric_obj else 'mean' self._graph_network_add_metric(value, aggregation, name) @doc_controls.do_not_doc_inheritable def add_update(self, updates, inputs=None): """Add update op(s), potentially dependent on layer inputs. Weight updates (for instance, the updates of the moving mean and variance in a BatchNormalization layer) may be dependent on the inputs passed when calling a layer. Hence, when reusing the same layer on different inputs `a` and `b`, some entries in `layer.updates` may be dependent on `a` and some on `b`. This method automatically keeps track of dependencies. This call is ignored when eager execution is enabled (in that case, variable updates are run on the fly and thus do not need to be tracked for later execution). Args: updates: Update op, or list/tuple of update ops, or zero-arg callable that returns an update op. A zero-arg callable should be passed in order to disable running the updates by setting `trainable=False` on this Layer, when executing in Eager mode. inputs: Deprecated, will be automatically inferred. """ if inputs is not None: tf_logging.warning( '`add_update` `inputs` kwarg has been deprecated. You no longer need ' 'to pass a value to `inputs` as it is being automatically inferred.') call_context = base_layer_utils.call_context() # No need to run updates during Functional API construction. if call_context.in_keras_graph: return # Callable updates are disabled by setting `trainable=False`. if not call_context.frozen: for update in nest.flatten(updates): if callable(update): update() # pylint: disable=not-callable def set_weights(self, weights): """Sets the weights of the layer, from NumPy arrays. The weights of a layer represent the state of the layer. This function sets the weight values from numpy arrays. The weight values should be passed in the order they are created by the layer. Note that the layer's weights must be instantiated before calling this function, by calling the layer. For example, a `Dense` layer returns a list of two values: the kernel matrix and the bias vector. These can be used to set the weights of another `Dense` layer: >>> layer_a = tf.keras.layers.Dense(1, ... kernel_initializer=tf.constant_initializer(1.)) >>> a_out = layer_a(tf.convert_to_tensor([[1., 2., 3.]])) >>> layer_a.get_weights() [array([[1.], [1.], [1.]], dtype=float32), array([0.], dtype=float32)] >>> layer_b = tf.keras.layers.Dense(1, ... kernel_initializer=tf.constant_initializer(2.)) >>> b_out = layer_b(tf.convert_to_tensor([[10., 20., 30.]])) >>> layer_b.get_weights() [array([[2.], [2.], [2.]], dtype=float32), array([0.], dtype=float32)] >>> layer_b.set_weights(layer_a.get_weights()) >>> layer_b.get_weights() [array([[1.], [1.], [1.]], dtype=float32), array([0.], dtype=float32)] Args: weights: a list of NumPy arrays. The number of arrays and their shape must match number of the dimensions of the weights of the layer (i.e. it should match the output of `get_weights`). Raises: ValueError: If the provided weights list does not match the layer's specifications. """ params = self.weights expected_num_weights = 0 for param in params: if isinstance(param, base_layer_utils.TrackableWeightHandler): expected_num_weights += param.num_tensors else: expected_num_weights += 1 if expected_num_weights != len(weights): raise ValueError( 'You called `set_weights(weights)` on layer "%s" ' 'with a weight list of length %s, but the layer was ' 'expecting %s weights. Provided weights: %s...' % (self.name, len(weights), expected_num_weights, str(weights)[:50])) weight_index = 0 weight_value_tuples = [] for param in params: if isinstance(param, base_layer_utils.TrackableWeightHandler): num_tensors = param.num_tensors tensors = weights[weight_index:weight_index + num_tensors] param.set_weights(tensors) weight_index += num_tensors else: weight = weights[weight_index] weight_shape = weight.shape if hasattr(weight, 'shape') else () ref_shape = param.shape if not ref_shape.is_compatible_with(weight_shape): raise ValueError( 'Layer weight shape %s not compatible with provided weight ' 'shape %s' % (ref_shape, weight_shape)) weight_value_tuples.append((param, weight)) weight_index += 1 backend.batch_set_value(weight_value_tuples) # Perform any layer defined finalization of the layer state. for layer in self._flatten_layers(): layer.finalize_state() def get_weights(self): """Returns the current weights of the layer, as NumPy arrays. The weights of a layer represent the state of the layer. This function returns both trainable and non-trainable weight values associated with this layer as a list of NumPy arrays, which can in turn be used to load state into similarly parameterized layers. For example, a `Dense` layer returns a list of two values: the kernel matrix and the bias vector. These can be used to set the weights of another `Dense` layer: >>> layer_a = tf.keras.layers.Dense(1, ... kernel_initializer=tf.constant_initializer(1.)) >>> a_out = layer_a(tf.convert_to_tensor([[1., 2., 3.]])) >>> layer_a.get_weights() [array([[1.], [1.], [1.]], dtype=float32), array([0.], dtype=float32)] >>> layer_b = tf.keras.layers.Dense(1, ... kernel_initializer=tf.constant_initializer(2.)) >>> b_out = layer_b(tf.convert_to_tensor([[10., 20., 30.]])) >>> layer_b.get_weights() [array([[2.], [2.], [2.]], dtype=float32), array([0.], dtype=float32)] >>> layer_b.set_weights(layer_a.get_weights()) >>> layer_b.get_weights() [array([[1.], [1.], [1.]], dtype=float32), array([0.], dtype=float32)] Returns: Weights values as a list of NumPy arrays. """ weights = self.weights output_weights = [] for weight in weights: if isinstance(weight, base_layer_utils.TrackableWeightHandler): output_weights.extend(weight.get_tensors()) else: output_weights.append(weight) return backend.batch_get_value(output_weights) @doc_controls.do_not_generate_docs def finalize_state(self): """Finalizes the layers state after updating layer weights. This function can be subclassed in a layer and will be called after updating a layer weights. It can be overridden to finalize any additional layer state after a weight update. """ pass @doc_controls.do_not_generate_docs def get_updates_for(self, inputs): """Deprecated, do NOT use! Retrieves updates relevant to a specific set of inputs. Args: inputs: Input tensor or list/tuple of input tensors. Returns: List of update ops of the layer that depend on `inputs`. """ warnings.warn('`layer.get_updates_for` is deprecated and ' 'will be removed in a future version. ' 'Please use `layer.updates` method instead.') return self.updates @doc_controls.do_not_generate_docs def get_losses_for(self, inputs): """Deprecated, do NOT use! Retrieves losses relevant to a specific set of inputs. Args: inputs: Input tensor or list/tuple of input tensors. Returns: List of loss tensors of the layer that depend on `inputs`. """ warnings.warn('`layer.get_losses_for` is deprecated and ' 'will be removed in a future version. ' 'Please use `layer.losses` instead.') return self.losses @doc_controls.do_not_doc_inheritable def get_input_mask_at(self, node_index): """Retrieves the input mask tensor(s) of a layer at a given node. Args: node_index: Integer, index of the node from which to retrieve the attribute. E.g. `node_index=0` will correspond to the first time the layer was called. Returns: A mask tensor (or list of tensors if the layer has multiple inputs). """ inputs = self.get_input_at(node_index) if isinstance(inputs, list): return [getattr(x, '_keras_mask', None) for x in inputs] else: return getattr(inputs, '_keras_mask', None) @doc_controls.do_not_doc_inheritable def get_output_mask_at(self, node_index): """Retrieves the output mask tensor(s) of a layer at a given node. Args: node_index: Integer, index of the node from which to retrieve the attribute. E.g. `node_index=0` will correspond to the first time the layer was called. Returns: A mask tensor (or list of tensors if the layer has multiple outputs). """ output = self.get_output_at(node_index) if isinstance(output, list): return [getattr(x, '_keras_mask', None) for x in output] else: return getattr(output, '_keras_mask', None) @property @doc_controls.do_not_doc_inheritable def input_mask(self): """Retrieves the input mask tensor(s) of a layer. Only applicable if the layer has exactly one inbound node, i.e. if it is connected to one incoming layer. Returns: Input mask tensor (potentially None) or list of input mask tensors. Raises: AttributeError: if the layer is connected to more than one incoming layers. """ inputs = self.input if isinstance(inputs, list): return [getattr(x, '_keras_mask', None) for x in inputs] else: return getattr(inputs, '_keras_mask', None) @property @doc_controls.do_not_doc_inheritable def output_mask(self): """Retrieves the output mask tensor(s) of a layer. Only applicable if the layer has exactly one inbound node, i.e. if it is connected to one incoming layer. Returns: Output mask tensor (potentially None) or list of output mask tensors. Raises: AttributeError: if the layer is connected to more than one incoming layers. """ output = self.output if isinstance(output, list): return [getattr(x, '_keras_mask', None) for x in output] else: return getattr(output, '_keras_mask', None) @doc_controls.do_not_doc_inheritable def get_input_shape_at(self, node_index): """Retrieves the input shape(s) of a layer at a given node. Args: node_index: Integer, index of the node from which to retrieve the attribute. E.g. `node_index=0` will correspond to the first time the layer was called. Returns: A shape tuple (or list of shape tuples if the layer has multiple inputs). Raises: RuntimeError: If called in Eager mode. """ return self._get_node_attribute_at_index(node_index, 'input_shapes', 'input shape') @doc_controls.do_not_doc_inheritable def get_output_shape_at(self, node_index): """Retrieves the output shape(s) of a layer at a given node. Args: node_index: Integer, index of the node from which to retrieve the attribute. E.g. `node_index=0` will correspond to the first time the layer was called. Returns: A shape tuple (or list of shape tuples if the layer has multiple outputs). Raises: RuntimeError: If called in Eager mode. """ return self._get_node_attribute_at_index(node_index, 'output_shapes', 'output shape') @doc_controls.do_not_doc_inheritable def get_input_at(self, node_index): """Retrieves the input tensor(s) of a layer at a given node. Args: node_index: Integer, index of the node from which to retrieve the attribute. E.g. `node_index=0` will correspond to the first input node of the layer. Returns: A tensor (or list of tensors if the layer has multiple inputs). Raises: RuntimeError: If called in Eager mode. """ return self._get_node_attribute_at_index(node_index, 'input_tensors', 'input') @doc_controls.do_not_doc_inheritable def get_output_at(self, node_index): """Retrieves the output tensor(s) of a layer at a given node. Args: node_index: Integer, index of the node from which to retrieve the attribute. E.g. `node_index=0` will correspond to the first output node of the layer. Returns: A tensor (or list of tensors if the layer has multiple outputs). Raises: RuntimeError: If called in Eager mode. """ return self._get_node_attribute_at_index(node_index, 'output_tensors', 'output') @property def input(self): """Retrieves the input tensor(s) of a layer. Only applicable if the layer has exactly one input, i.e. if it is connected to one incoming layer. Returns: Input tensor or list of input tensors. Raises: RuntimeError: If called in Eager mode. AttributeError: If no inbound nodes are found. """ if not self._inbound_nodes: raise AttributeError('Layer ' + self.name + ' is not connected, no input to return.') return self._get_node_attribute_at_index(0, 'input_tensors', 'input') @property def output(self): """Retrieves the output tensor(s) of a layer. Only applicable if the layer has exactly one output, i.e. if it is connected to one incoming layer. Returns: Output tensor or list of output tensors. Raises: AttributeError: if the layer is connected to more than one incoming layers. RuntimeError: if called in Eager mode. """ if not self._inbound_nodes: raise AttributeError('Layer ' + self.name + ' has no inbound nodes.') return self._get_node_attribute_at_index(0, 'output_tensors', 'output') @property @doc_controls.do_not_doc_inheritable def input_shape(self): """Retrieves the input shape(s) of a layer. Only applicable if the layer has exactly one input, i.e. if it is connected to one incoming layer, or if all inputs have the same shape. Returns: Input shape, as an integer shape tuple (or list of shape tuples, one tuple per input tensor). Raises: AttributeError: if the layer has no defined input_shape. RuntimeError: if called in Eager mode. """ if not self._inbound_nodes: raise AttributeError('The layer has never been called ' 'and thus has no defined input shape.') all_input_shapes = set( [str(node.input_shapes) for node in self._inbound_nodes]) if len(all_input_shapes) == 1: return self._inbound_nodes[0].input_shapes else: raise AttributeError('The layer "' + str(self.name) + ' has multiple inbound nodes, ' 'with different input shapes. Hence ' 'the notion of "input shape" is ' 'ill-defined for the layer. ' 'Use `get_input_shape_at(node_index)` ' 'instead.') def count_params(self): """Count the total number of scalars composing the weights. Returns: An integer count. Raises: ValueError: if the layer isn't yet built (in which case its weights aren't yet defined). """ if not self.built: if getattr(self, '_is_graph_network', False): with tf_utils.maybe_init_scope(self): self._maybe_build(self.inputs) else: raise ValueError('You tried to call `count_params` on ' + self.name + ', but the layer isn\'t built. ' 'You can build it manually via: `' + self.name + '.build(batch_input_shape)`.') return layer_utils.count_params(self.weights) @property @doc_controls.do_not_doc_inheritable def output_shape(self): """Retrieves the output shape(s) of a layer. Only applicable if the layer has one output, or if all outputs have the same shape. Returns: Output shape, as an integer shape tuple (or list of shape tuples, one tuple per output tensor). Raises: AttributeError: if the layer has no defined output shape. RuntimeError: if called in Eager mode. """ if not self._inbound_nodes: raise AttributeError('The layer has never been called ' 'and thus has no defined output shape.') all_output_shapes = set( [str(node.output_shapes) for node in self._inbound_nodes]) if len(all_output_shapes) == 1: return self._inbound_nodes[0].output_shapes else: raise AttributeError('The layer "%s"' ' has multiple inbound nodes, ' 'with different output shapes. Hence ' 'the notion of "output shape" is ' 'ill-defined for the layer. ' 'Use `get_output_shape_at(node_index)` ' 'instead.' % self.name) @property @doc_controls.do_not_doc_inheritable def inbound_nodes(self): """Deprecated, do NOT use! Only for compatibility with external Keras.""" return self._inbound_nodes @property @doc_controls.do_not_doc_inheritable def outbound_nodes(self): """Deprecated, do NOT use! Only for compatibility with external Keras.""" return self._outbound_nodes ############################################################################## # Methods & attributes below are public aliases of other methods. # ############################################################################## @doc_controls.do_not_doc_inheritable def apply(self, inputs, *args, **kwargs): """Deprecated, do NOT use! This is an alias of `self.__call__`. Args: inputs: Input tensor(s). *args: additional positional arguments to be passed to `self.call`. **kwargs: additional keyword arguments to be passed to `self.call`. Returns: Output tensor(s). """ warnings.warn('`layer.apply` is deprecated and ' 'will be removed in a future version. ' 'Please use `layer.__call__` method instead.') return self.__call__(inputs, *args, **kwargs) @doc_controls.do_not_doc_inheritable def add_variable(self, *args, **kwargs): """Deprecated, do NOT use! Alias for `add_weight`.""" warnings.warn('`layer.add_variable` is deprecated and ' 'will be removed in a future version. ' 'Please use `layer.add_weight` method instead.') return self.add_weight(*args, **kwargs) @property @doc_controls.do_not_generate_docs def variables(self): """Returns the list of all layer variables/weights. Alias of `self.weights`. Note: This will not track the weights of nested `tf.Modules` that are not themselves Keras layers. Returns: A list of variables. """ return self.weights @property @doc_controls.do_not_generate_docs def trainable_variables(self): return self.trainable_weights @property @doc_controls.do_not_generate_docs def non_trainable_variables(self): return self.non_trainable_weights ############################################################################## # Methods & attributes below are all private and only used by the framework. # ############################################################################## @property def _inbound_nodes(self): return self._inbound_nodes_value @_inbound_nodes.setter @trackable.no_automatic_dependency_tracking def _inbound_nodes(self, value): self._inbound_nodes_value = value @property def _outbound_nodes(self): return self._outbound_nodes_value @_outbound_nodes.setter @trackable.no_automatic_dependency_tracking def _outbound_nodes(self, value): self._outbound_nodes_value = value def _set_dtype_policy(self, dtype): """Sets self._dtype_policy.""" if isinstance(dtype, policy.Policy): self._dtype_policy = dtype elif isinstance(dtype, dict): self._dtype_policy = policy.deserialize(dtype) elif isinstance(dtype, str) and dtype in ('mixed_float16', 'mixed_bfloat16'): # The isinstance check is required since np.dtype raises an error if # compared to a non-dtype string. self._dtype_policy = policy.Policy(dtype) elif dtype: self._dtype_policy = policy.Policy(dtypes.as_dtype(dtype).name) else: self._dtype_policy = policy.global_policy() if (self._dtype_policy.name == 'mixed_float16' and not loss_scale_optimizer.strategy_supports_loss_scaling()): # Although only loss scaling doesn't support certain strategies, to avoid # confusion, we disallow the 'mixed_float16' policy with unsupported # strategies. This is because 'mixed_float16' requires loss scaling for # numeric stability. strategy = distribute_lib.get_strategy() raise ValueError('Mixed precision is not supported with the ' 'tf.distribute.Strategy: %s. Either stop using mixed ' 'precision by removing the use of the "%s" policy or ' 'use a different Strategy, e.g. a MirroredStrategy.' % (strategy.__class__.__name__, self._dtype_policy.name)) # Performance optimization: cache the compute dtype as a Dtype object or # None, so that str to Dtype conversion doesn't happen in Layer.__call__. # TODO(b/157486353): Investigate returning DTypes in Policy. if self._dtype_policy.compute_dtype: self._compute_dtype_object = dtypes.as_dtype( self._dtype_policy.compute_dtype) else: self._compute_dtype_object = None @property def dtype_policy(self): """The dtype policy associated with this layer. This is an instance of a `tf.keras.mixed_precision.Policy`. """ return self._dtype_policy @property def compute_dtype(self): """The dtype of the layer's computations. This is equivalent to `Layer.dtype_policy.compute_dtype`. Unless mixed precision is used, this is the same as `Layer.dtype`, the dtype of the weights. Layers automatically cast their inputs to the compute dtype, which causes computations and the output to be in the compute dtype as well. This is done by the base Layer class in `Layer.__call__`, so you do not have to insert these casts if implementing your own layer. Layers often perform certain internal computations in higher precision when `compute_dtype` is float16 or bfloat16 for numeric stability. The output will still typically be float16 or bfloat16 in such cases. Returns: The layer's compute dtype. """ return self._dtype_policy.compute_dtype @property def _compute_dtype(self): """Deprecated alias of `compute_dtype`.""" return self._dtype_policy.compute_dtype @property def variable_dtype(self): """Alias of `Layer.dtype`, the dtype of the weights.""" return self.dtype def _maybe_cast_inputs(self, inputs, input_list=None): """Maybe casts the inputs to the compute dtype. If self._compute_dtype is floating-point, and self_autocast is True, floating-point inputs are casted to self._compute_dtype. Args: inputs: Input tensor, or structure of input tensors. input_list: Flat list of input tensors. Returns: `inputs`, but tensors may have been casted to self._compute_dtype """ if not input_list: input_list = nest.flatten(inputs) compute_dtype_object = self._compute_dtype_object should_autocast = ( self._autocast and compute_dtype_object and compute_dtype_object.is_floating) if (should_autocast and any(map(self._should_cast_single_input, input_list))): # Only perform expensive `nest` operation when needed. return nest.map_structure(self._cast_single_input, inputs) else: return inputs def _should_cast_single_input(self, x): if isinstance(x, _AUTOCAST_TYPES): return (self._compute_dtype_object and x.dtype != self._compute_dtype_object and x.dtype.is_floating) return False def _cast_single_input(self, x): """Cast a single Tensor or TensorSpec to the compute dtype.""" if self._should_cast_single_input(x): return math_ops.cast(x, self._compute_dtype_object) else: return x # _dtype used to be an attribute set in the constructor. We still expose it # because some clients still use it. # TODO(reedwm): Deprecate, then remove the _dtype property. @property def _dtype(self): # This is equivalent to returning self.dtype . We do not return self.dtype # as it would cause infinite recursion in a few subclasses, which override # "dtype" to return self._dtype. return self._dtype_policy.variable_dtype @_dtype.setter def _dtype(self, value): value = dtypes.as_dtype(value).name self._set_dtype_policy(policy.Policy(value)) def _name_scope(self): # pylint: disable=method-hidden if not tf2.enabled(): return self.name name_scope = self.name current_name_scope = ops.get_name_scope() if current_name_scope: name_scope = current_name_scope + '/' + name_scope if name_scope: # Note that the trailing `/` prevents autogenerated # numerical suffixes to get appended. It will also fully reset # nested name scope (i.e. the outer name scope has no effect). name_scope += '/' return name_scope def _init_set_name(self, name, zero_based=True): if not name: self._name = backend.unique_object_name( generic_utils.to_snake_case(self.__class__.__name__), zero_based=zero_based) else: backend.observe_object_name(name) self._name = name def _get_existing_metric(self, name=None): match = [m for m in self._metrics if m.name == name] if not match: return if len(match) > 1: raise ValueError( 'Please provide different names for the metrics you have added. ' 'We found {} metrics with the name: "{}"'.format(len(match), name)) return match[0] def _handle_weight_regularization(self, name, variable, regularizer): """Create lambdas which compute regularization losses.""" def _loss_for_variable(v): """Creates a regularization loss `Tensor` for variable `v`.""" with backend.name_scope(name + '/Regularizer'): regularization = regularizer(v) return regularization if base_layer_utils.is_split_variable(variable): for v in variable: self.add_loss(functools.partial(_loss_for_variable, v)) else: self.add_loss(functools.partial(_loss_for_variable, variable)) def _handle_activity_regularization(self, inputs, outputs): # Apply activity regularization. # Note that it should be applied every time the layer creates a new # output, since it is output-specific. if self._activity_regularizer: output_list = nest.flatten(outputs) with backend.name_scope('ActivityRegularizer'): for output in output_list: activity_loss = self._activity_regularizer(output) batch_size = math_ops.cast( array_ops.shape(output)[0], activity_loss.dtype) # Make activity regularization strength batch-agnostic. mean_activity_loss = activity_loss / batch_size self.add_loss(mean_activity_loss) def _set_mask_metadata(self, inputs, outputs, previous_mask, build_graph): # Many `Layer`s don't need to call `compute_mask`. # This method is optimized to do as little work as needed for the common # case. if not self._supports_masking: return flat_outputs = nest.flatten(outputs) mask_already_computed = ( getattr(self, '_compute_output_and_mask_jointly', False) or all(getattr(x, '_keras_mask', None) is not None for x in flat_outputs)) if mask_already_computed: if build_graph: self._set_mask_keras_history_checked(flat_outputs) return output_masks = self.compute_mask(inputs, previous_mask) if output_masks is None: return flat_masks = nest.flatten(output_masks) for tensor, mask in zip(flat_outputs, flat_masks): try: tensor._keras_mask = mask except AttributeError: # C Type such as np.ndarray. pass if build_graph: self._set_mask_keras_history_checked(flat_outputs) def _set_mask_keras_history_checked(self, flat_outputs): for output in flat_outputs: if getattr(output, '_keras_mask', None) is not None: # Do not track masks for `TensorFlowOpLayer` construction. output._keras_mask._keras_history_checked = True def _get_input_masks(self, inputs, input_list, args, kwargs): if not self._supports_masking and not self._expects_mask_arg: # Input masks only need to be retrieved if they are needed for `call` # or `compute_mask`. input_masks = None implicit_mask = False elif self._call_arg_was_passed('mask', args, kwargs): input_masks = self._get_call_arg_value('mask', args, kwargs) implicit_mask = False else: input_masks = [getattr(t, '_keras_mask', None) for t in input_list] if all(mask is None for mask in input_masks): input_masks = None implicit_mask = False else: # Only do expensive `nest` op when masking is actually being used. input_masks = nest.pack_sequence_as(inputs, input_masks) implicit_mask = True return input_masks, implicit_mask def _call_arg_was_passed(self, arg_name, args, kwargs, inputs_in_args=False): # Performance optimization: do no work in most common case. if not args and not kwargs: return False if arg_name in kwargs: return True call_fn_args = self._call_fn_args if not inputs_in_args: # Ignore `inputs` arg. call_fn_args = call_fn_args[1:] return arg_name in dict(zip(call_fn_args, args)) def _get_call_arg_value(self, arg_name, args, kwargs, inputs_in_args=False): if arg_name in kwargs: return kwargs[arg_name] call_fn_args = self._call_fn_args if not inputs_in_args: # Ignore `inputs` arg. call_fn_args = call_fn_args[1:] args_dict = dict(zip(call_fn_args, args)) return args_dict[arg_name] def _set_call_arg_value( self, arg_name, new_value, args, kwargs, inputs_in_args=False, pop_kwarg_if_none=False): arg_pos = self._call_fn_arg_positions.get(arg_name, None) if arg_pos is not None: if not inputs_in_args: # Ignore `inputs` arg. arg_pos = arg_pos - 1 if len(args) > arg_pos: args = list(args) args[arg_pos] = new_value return tuple(args), kwargs if new_value is None and pop_kwarg_if_none: kwargs.pop(arg_name, None) else: kwargs[arg_name] = new_value return args, kwargs def _set_connectivity_metadata(self, args, kwargs, outputs): # If the layer returns tensors from its inputs unmodified, # we copy them to avoid loss of KerasHistory metadata. flat_outputs = nest.flatten(outputs) flat_inputs = nest.flatten((args, kwargs)) input_ids_set = {id(i) for i in flat_inputs} outputs_copy = [] for x in flat_outputs: if id(x) in input_ids_set: with backend.name_scope(self.name): x = array_ops.identity(x) outputs_copy.append(x) outputs = nest.pack_sequence_as(outputs, outputs_copy) # Create node, Node wires itself to inbound and outbound layers. # The Node constructor actually updates this layer's self._inbound_nodes, # sets _keras_history on the outputs, and adds itself to the # `_outbound_nodes` of the layers that produced the inputs to this # layer call. node_module.Node(self, call_args=args, call_kwargs=kwargs, outputs=outputs) return outputs def _get_node_attribute_at_index(self, node_index, attr, attr_name): """Private utility to retrieves an attribute (e.g. inputs) from a node. This is used to implement the methods: - get_input_shape_at - get_output_shape_at - get_input_at etc... Args: node_index: Integer index of the node from which to retrieve the attribute. attr: Exact node attribute name. attr_name: Human-readable attribute name, for error messages. Returns: The layer's attribute `attr` at the node of index `node_index`. Raises: RuntimeError: If the layer has no inbound nodes, or if called in Eager mode. ValueError: If the index provided does not match any node. """ if not self._inbound_nodes: raise RuntimeError('The layer has never been called ' 'and thus has no defined ' + attr_name + '.') if not len(self._inbound_nodes) > node_index: raise ValueError('Asked to get ' + attr_name + ' at node ' + str(node_index) + ', but the layer has only ' + str(len(self._inbound_nodes)) + ' inbound nodes.') values = getattr(self._inbound_nodes[node_index], attr) if isinstance(values, list) and len(values) == 1: return values[0] else: return values def _maybe_build(self, inputs): # Check input assumptions set before layer building, e.g. input rank. if not self.built: input_spec.assert_input_compatibility( self.input_spec, inputs, self.name) input_list = nest.flatten(inputs) if input_list and self._dtype_policy.compute_dtype is None: try: dtype = input_list[0].dtype.base_dtype.name except AttributeError: pass else: self._set_dtype_policy(policy.Policy(dtype)) input_shapes = None # Converts Tensors / CompositeTensors to TensorShapes. if all(hasattr(x, 'shape') for x in input_list): input_shapes = tf_utils.get_shapes(inputs) else: # Converts input shape to TensorShapes. try: input_shapes = tf_utils.convert_shapes(inputs, to_tuples=False) except ValueError: pass # Only call `build` if the user has manually overridden the build method. if not hasattr(self.build, '_is_default'): # Any setup work performed only once should happen in an `init_scope` # to avoid creating symbolic Tensors that will later pollute any eager # operations. with tf_utils.maybe_init_scope(self): self.build(input_shapes) # pylint:disable=not-callable # We must set also ensure that the layer is marked as built, and the build # shape is stored since user defined build functions may not be calling # `super.build()` Layer.build(self, input_shapes) # Optionally load weight values specified at layer instantiation. if self._initial_weights is not None: with ops.init_scope(): # Using `init_scope` since we want variable assignment in # `set_weights` to be treated like variable initialization. self.set_weights(self._initial_weights) self._initial_weights = None def _symbolic_call(self, inputs): input_shapes = nest.map_structure(lambda x: x.shape, inputs) output_shapes = self.compute_output_shape(input_shapes) # Convert to TensorShape so that nest.map_structure will not map into # individual dim of the shape. output_shapes = tf_utils.convert_shapes(output_shapes, to_tuples=False) def _make_placeholder_like(shape): ph = backend.placeholder(shape=shape, dtype=self.dtype) ph._keras_mask = None return ph return nest.map_structure(_make_placeholder_like, output_shapes) def _get_trainable_state(self): """Get the `trainable` state of each sublayer. Returns: A dict mapping all sublayers to their `trainable` value. """ trainable_state = weakref.WeakKeyDictionary() for layer in self._flatten_layers(): trainable_state[layer] = layer.trainable return trainable_state def _set_trainable_state(self, trainable_state): """Set `trainable` state for each sublayer.""" for layer in self._flatten_layers(): if layer in trainable_state: layer.trainable = trainable_state[layer] @property def _obj_reference_counts(self): """A dictionary counting the number of attributes referencing an object.""" self._maybe_create_attribute('_obj_reference_counts_dict', object_identity.ObjectIdentityDictionary()) return self._obj_reference_counts_dict @trackable.no_automatic_dependency_tracking def _maybe_create_attribute(self, name, default_value): """Create the attribute with the default value if it hasn't been created. This is useful for fields that is used for tracking purpose, _trainable_weights, or _layers. Note that user could create a layer subclass and assign an internal field before invoking the Layer.__init__(), the __setattr__() need to create the tracking fields and __init__() need to not override them. Args: name: String, the name of the attribute. default_value: Object, the default value of the attribute. """ if not hasattr(self, name): self.__setattr__(name, default_value) def __delattr__(self, name): # For any super.__delattr__() call, we will directly use the implementation # in Trackable and skip the behavior in AutoTrackable. The Layer was # originally use Trackable as base class, the change of using Module as base # class forced us to have AutoTrackable in the class hierarchy. # # TODO(b/180760306) Keeping the status quo of skipping _delattr__ and # __setattr__ in AutoTrackable may be unsustainable. existing_value = getattr(self, name, None) # If this value is replacing an existing object assigned to an attribute, we # should clean it out to avoid leaking memory. First we check if there are # other attributes referencing it. reference_counts = self._obj_reference_counts if existing_value not in reference_counts: super(autotrackable.AutoTrackable, self).__delattr__(name) # pylint: disable=bad-super-call return reference_count = reference_counts[existing_value] if reference_count > 1: # There are other remaining references. We can't remove this object from # _layers etc. reference_counts[existing_value] = reference_count - 1 super(autotrackable.AutoTrackable, self).__delattr__(name) # pylint: disable=bad-super-call return else: # This is the last remaining reference. del reference_counts[existing_value] super(autotrackable.AutoTrackable, self).__delattr__(name) # pylint: disable=bad-super-call if (isinstance(existing_value, Layer) or base_layer_utils.has_weights(existing_value)): super(autotrackable.AutoTrackable, self).__setattr__( # pylint: disable=bad-super-call '_self_tracked_trackables', [l for l in self._self_tracked_trackables if l is not existing_value]) if isinstance(existing_value, tf_variables.Variable): super(autotrackable.AutoTrackable, self).__setattr__( # pylint: disable=bad-super-call '_trainable_weights', [w for w in self._trainable_weights if w is not existing_value]) super(autotrackable.AutoTrackable, self).__setattr__( # pylint: disable=bad-super-call '_non_trainable_weights', [w for w in self._non_trainable_weights if w is not existing_value]) def __setattr__(self, name, value): if (name == '_self_setattr_tracking' or not getattr(self, '_self_setattr_tracking', True) or # Exclude @property.setters from tracking hasattr(self.__class__, name)): try: super(autotrackable.AutoTrackable, self).__setattr__(name, value) # pylint: disable=bad-super-call except AttributeError: raise AttributeError( ('Can\'t set the attribute "{}", likely because it conflicts with ' 'an existing read-only @property of the object. Please choose a ' 'different name.').format(name)) return # Wraps data structures in `Trackable`, unwraps `NoDependency` objects. value = data_structures.sticky_attribute_assignment( trackable=self, value=value, name=name) reference_counts = self._obj_reference_counts reference_counts[value] = reference_counts.get(value, 0) + 1 # Clean out the old attribute, which clears _layers and _trainable_weights # if necessary. try: self.__delattr__(name) except AttributeError: pass # Keep track of metric instance created in subclassed layer. for val in nest.flatten(value): if isinstance(val, metrics_mod.Metric) and hasattr(self, '_metrics'): self._metrics.append(val) # Append value to self._self_tracked_trackables if relevant if (getattr(self, '_auto_track_sub_layers', True) and (isinstance(value, module.Module) or base_layer_utils.has_weights(value))): self._maybe_create_attribute('_self_tracked_trackables', []) # We need to check object identity to avoid de-duplicating empty # container types which compare equal. if not any((layer is value for layer in self._self_tracked_trackables)): self._self_tracked_trackables.append(value) if hasattr(value, '_use_resource_variables'): # Legacy layers (V1 tf.layers) must always use # resource variables. value._use_resource_variables = True # Append value to list of trainable / non-trainable weights if relevant # TODO(b/125122625): This won't pick up on any variables added to a # list/dict after creation. for val in nest.flatten(value, expand_composites=True): if not isinstance(val, tf_variables.Variable): continue # Users may add extra weights/variables # simply by assigning them to attributes (invalid for graph networks) self._maybe_create_attribute('_trainable_weights', []) self._maybe_create_attribute('_non_trainable_weights', []) if val.trainable: if any(val is w for w in self._trainable_weights): continue self._trainable_weights.append(val) else: if any(val is w for w in self._non_trainable_weights): continue self._non_trainable_weights.append(val) backend.track_variable(val) # TODO(b/180760306) Skip the auto trackable from tf.Module to keep status # quo. See the comment at __delattr__. super(autotrackable.AutoTrackable, self).__setattr__(name, value) # pylint: disable=bad-super-call def _gather_children_attribute(self, attribute): assert attribute in { 'variables', 'trainable_variables', 'non_trainable_variables' } if hasattr(self, '_self_tracked_trackables'): nested_layers = self._flatten_modules(include_self=False, recursive=False) return list( itertools.chain.from_iterable( getattr(layer, attribute) for layer in nested_layers)) return [] def _flatten_layers(self, recursive=True, include_self=True): for m in self._flatten_modules( recursive=recursive, include_self=include_self): if isinstance(m, Layer): yield m def _flatten_modules(self, recursive=True, include_self=True): """Flattens `tf.Module` instances (excluding `Metrics`). Args: recursive: Whether to recursively flatten through submodules. include_self: Whether to include this `Layer` instance. Yields: `tf.Module` instance tracked by this `Layer`. """ if include_self: yield self # Only instantiate set and deque if needed. trackables = getattr(self, '_self_tracked_trackables', None) if trackables: seen_object_ids = set() deque = collections.deque(trackables) while deque: trackable_obj = deque.popleft() trackable_id = id(trackable_obj) if trackable_id in seen_object_ids: continue seen_object_ids.add(trackable_id) # Metrics are not considered part of the Layer's topology. if (isinstance(trackable_obj, module.Module) and not isinstance(trackable_obj, metrics_mod.Metric)): yield trackable_obj # Introspect recursively through sublayers. if recursive: subtrackables = getattr(trackable_obj, '_self_tracked_trackables', None) if subtrackables: deque.extendleft(reversed(subtrackables)) elif isinstance(trackable_obj, data_structures.TrackableDataStructure): # Data structures are introspected even with `recursive=False`. tracked_values = trackable_obj._values if tracked_values: deque.extendleft(reversed(tracked_values)) # This is a hack so that the is_layer (within # training/trackable/layer_utils.py) check doesn't get the weights attr. # TODO(b/110718070): Remove when fixed. def _is_layer(self): return True def _init_call_fn_args(self, expects_training_arg=None): # Clear cached call function arguments. self.__class__._call_full_argspec.fget.cache.pop(self, None) self.__class__._call_fn_args.fget.cache.pop(self, None) self.__class__._call_accepts_kwargs.fget.cache.pop(self, None) call_fn_args = self._call_fn_args call_fn_args += self._call_full_argspec.kwonlyargs or [] if expects_training_arg is None: self._expects_training_arg = ('training' in call_fn_args or self._call_accepts_kwargs) else: # Use value encoded into the metadata when loading from the SavedModel. self._expects_training_arg = expects_training_arg # The default training arg will be any (non-None) default specified in the # method signature, or None if no value is specified. call_fn_arg_defaults = self._call_fn_arg_defaults.copy() call_fn_arg_defaults.update(self._call_full_argspec.kwonlydefaults or {}) self._default_training_arg = call_fn_arg_defaults.get('training') self._expects_mask_arg = ('mask' in call_fn_args or self._call_accepts_kwargs) @property @layer_utils.cached_per_instance def _call_full_argspec(self): # Argspec inspection is expensive and the call spec is used often, so it # makes sense to cache the result. return tf_inspect.getfullargspec(self.call) @property @layer_utils.cached_per_instance def _call_fn_args(self): all_args = self._call_full_argspec.args # Scrub `self` that appears if a decorator was applied. if all_args and all_args[0] == 'self': return all_args[1:] return all_args @property @layer_utils.cached_per_instance def _call_fn_arg_defaults(self): call_fn_args = self._call_fn_args call_fn_defaults = self._call_full_argspec.defaults or [] defaults = dict() # The call arg defaults are an n-tuple of the last n elements of the args # list. (n = # of elements that have a default argument) for i in range(-1 * len(call_fn_defaults), 0): defaults[call_fn_args[i]] = call_fn_defaults[i] return defaults @property @layer_utils.cached_per_instance def _call_fn_arg_positions(self): call_fn_arg_positions = dict() for pos, arg in enumerate(self._call_fn_args): call_fn_arg_positions[arg] = pos return call_fn_arg_positions @property @layer_utils.cached_per_instance def _call_accepts_kwargs(self): return self._call_full_argspec.varkw is not None @property def _eager_losses(self): # A list of loss values containing activity regularizers and losses # manually added through `add_loss` during eager execution. It is cleared # after every batch. # Because we plan on eventually allowing a same model instance to be trained # in eager mode or graph mode alternatively, we need to keep track of # eager losses and symbolic losses via separate attributes. if not hasattr(self._thread_local, '_eager_losses'): self._thread_local._eager_losses = [] return self._thread_local._eager_losses @_eager_losses.setter def _eager_losses(self, losses): self._thread_local._eager_losses = losses def _dedup_weights(self, weights): """Dedupe weights while maintaining order as much as possible.""" output, seen_ids = [], set() for w in weights: if id(w) not in seen_ids: output.append(w) # Track the Variable's identity to avoid __eq__ issues. seen_ids.add(id(w)) return output def _split_out_first_arg(self, args, kwargs): # Grab the argument corresponding to the first argument in the # layer's `call` method spec. This will either be the first positional # argument, or it will be provided as a keyword argument. if args: inputs = args[0] args = args[1:] elif self._call_fn_args[0] in kwargs: kwargs = copy.copy(kwargs) inputs = kwargs.pop(self._call_fn_args[0]) else: raise ValueError( 'The first argument to `Layer.call` must always be passed.') return inputs, args, kwargs # SavedModel properties. Please see keras/saving/saved_model for details. @trackable.no_automatic_dependency_tracking def _set_save_spec(self, inputs): if self._saved_model_inputs_spec is not None: return # Already set. self._saved_model_inputs_spec = nest.map_structure(tf_utils.get_tensor_spec, inputs) def _get_save_spec(self, dynamic_batch=True): if self._saved_model_inputs_spec is None: return None return nest.map_structure( lambda t: tf_utils.get_tensor_spec(t, dynamic_batch=dynamic_batch), self._saved_model_inputs_spec) @property def _trackable_saved_model_saver(self): return layer_serialization.LayerSavedModelSaver(self) @property def _object_identifier(self): return self._trackable_saved_model_saver.object_identifier @property def _tracking_metadata(self): """Info about this layer to be saved into the SavedModel.""" return self._trackable_saved_model_saver.tracking_metadata def _trackable_children(self, save_type='checkpoint', **kwargs): if save_type == 'savedmodel': cache = kwargs['cache'] # TODO(b/213628533): This must be called before super() to ensure # that any input shape changes are applied before getting the config of # the model. children = self._trackable_saved_model_saver.trackable_children(cache) else: children = {} children.update(super()._trackable_children(save_type, **kwargs)) return children @property def _use_input_spec_as_call_signature(self): # Whether input spec can be used as the call signature when tracing the # Layer for SavedModel. By default, this is set to `True` for layers # exported from the Keras library, because the layers more rigidly define # the `input_specs` property (many custom layers only set the `ndims`) return get_canonical_name_for_symbol(type(self), api_name='keras') is not None def __getstate__(self): # Override to support `copy.deepcopy` and pickling. # Thread-local objects cannot be copied in Python 3, so pop these. # Thread-local objects are used to cache losses in MirroredStrategy, and # so shouldn't be copied. state = self.__dict__.copy() state.pop('_thread_local', None) state.pop('_metrics_lock', None) return state def __setstate__(self, state): state['_thread_local'] = threading.local() state['_metrics_lock'] = threading.Lock() # Bypass Trackable logic as `__dict__` already contains this info. object.__setattr__(self, '__dict__', state)
Layer
python
numpy__numpy
numpy/lib/tests/test__datasource.py
{ "start": 4985, "end": 7473 }
class ____: def test_ValidHTTP(self, tmp_path): ds = datasource.DataSource(tmp_path) _, netloc, upath, _, _, _ = urlparse(valid_httpurl()) local_path = os.path.join(tmp_path, netloc, upath.strip(os.sep).strip('/')) assert_equal(local_path, ds.abspath(valid_httpurl())) def test_ValidFile(self, tmp_path): ds = datasource.DataSource(tmp_path) tmpfile = valid_textfile(tmp_path) tmpfilename = os.path.split(tmpfile)[-1] # Test with filename only assert_equal(tmpfile, ds.abspath(tmpfilename)) # Test filename with complete path assert_equal(tmpfile, ds.abspath(tmpfile)) def test_InvalidHTTP(self, tmp_path): ds = datasource.DataSource(tmp_path) _, netloc, upath, _, _, _ = urlparse(invalid_httpurl()) invalidhttp = os.path.join(tmp_path, netloc, upath.strip(os.sep).strip('/')) assert_(invalidhttp != ds.abspath(valid_httpurl())) def test_InvalidFile(self, tmp_path): ds = datasource.DataSource(tmp_path) invalidfile = valid_textfile(tmp_path) tmpfile = valid_textfile(tmp_path) tmpfilename = os.path.split(tmpfile)[-1] # Test with filename only assert_(invalidfile != ds.abspath(tmpfilename)) # Test filename with complete path assert_(invalidfile != ds.abspath(tmpfile)) def test_sandboxing(self, tmp_path): ds = datasource.DataSource(tmp_path) tmpfile = valid_textfile(tmp_path) tmpfilename = os.path.split(tmpfile)[-1] path = lambda x: os.path.abspath(ds.abspath(x)) assert_(path(valid_httpurl()).startswith(str(tmp_path))) assert_(path(invalid_httpurl()).startswith(str(tmp_path))) assert_(path(tmpfile).startswith(str(tmp_path))) assert_(path(tmpfilename).startswith(str(tmp_path))) for fn in malicious_files: assert_(path(http_path + fn).startswith(str(tmp_path))) assert_(path(fn).startswith(str(tmp_path))) def test_windows_os_sep(self, tmp_path): orig_os_sep = os.sep try: os.sep = '\\' self.test_ValidHTTP(tmp_path) self.test_ValidFile(tmp_path) self.test_InvalidHTTP(tmp_path) self.test_InvalidFile(tmp_path) self.test_sandboxing(tmp_path) finally: os.sep = orig_os_sep
TestDataSourceAbspath
python
great-expectations__great_expectations
great_expectations/exceptions/resource_freshness.py
{ "start": 1627, "end": 1939 }
class ____(ResourceFreshnessError): def __init__(self, name: str) -> None: super().__init__( f"ExpectationSuite '{name}' has changed since it has last been saved. " "Please update with `<SUITE_OBJECT>.save()`, then try your action again." )
ExpectationSuiteNotFreshError
python
huggingface__transformers
src/transformers/models/got_ocr2/image_processing_got_ocr2.py
{ "start": 1462, "end": 5437 }
class ____(ImagesKwargs, total=False): """ crop_to_patches (`bool`, *optional*, defaults to `False`): Whether to crop the image to patches. Can be overridden by the `crop_to_patches` parameter in the `preprocess` method. min_patches (`int`, *optional*, defaults to 1): The minimum number of patches to be extracted from the image. Only has an effect if `crop_to_patches` is set to `True`. Can be overridden by the `min_patches` parameter in the `preprocess` method. max_patches (`int`, *optional*, defaults to 12): The maximum number of patches to be extracted from the image. Only has an effect if `crop_to_patches` is set to `True`. Can be overridden by the `max_patches` parameter in the `preprocess` method. """ crop_to_patches: bool min_patches: int max_patches: int # Similar to image_processing_mllama.get_all_supported_aspect_ratios @lru_cache(maxsize=10) def get_all_supported_aspect_ratios(min_image_tiles: int, max_image_tiles: int) -> list[tuple[int, int]]: """ Computes all allowed aspect ratios for a given minimum and maximum number of input tiles. This function calculates all possible arrangements of tiles that can be formed within the constraint of the minimum and maximum number of tiles. Each arrangement is represented by its aspect ratio (width/height) and the corresponding tile configuration. Args: min_image_tiles (`int`): The minimum number of tiles allowed. max_image_tiles (`int`): The maximum number of tiles allowed. Returns: `list[tuple[int, int]]`: A list of tuples, each tuple representing a valid (width, height) configuration in terms of number of tiles. Example: >>> get_all_supported_aspect_ratios(1, 4) [(1, 1), (1, 2), (2, 1), (1, 3), (3, 1), (1, 4), (2, 2), (4, 1)] """ aspect_ratios = [] for width in range(1, max_image_tiles + 1): for height in range(1, max_image_tiles + 1): if width * height <= max_image_tiles and width * height >= min_image_tiles: aspect_ratios.append((width, height)) aspect_ratios = sorted(aspect_ratios, key=lambda x: x[0] * x[1]) return aspect_ratios @lru_cache(maxsize=100) def get_optimal_tiled_canvas( original_image_size: tuple[int, int], target_tile_size: tuple[int, int], min_image_tiles: int, max_image_tiles: int, ) -> tuple[int, int]: """ Given a minimum and maximum number of tiles, find the canvas with the closest aspect ratio to the original image aspect ratio. In case of tie-breaking condition when two canvases have the same aspect ratio difference, we favor the canvas with more tiles, until the area covered by the tiles is more than twice the target area, in order to avoid unnecessarily excessive tiling. """ possible_tile_arrangements = get_all_supported_aspect_ratios(min_image_tiles, max_image_tiles) original_height, original_width = original_image_size target_tile_height, target_tile_width = target_tile_size aspect_ratio = original_width / original_height area = original_width * original_height # find the grid with the best aspect ratio best_ratio_diff = float("inf") best_grid = (1, 1) for grid in possible_tile_arrangements: grid_aspect_ratio = grid[0] / grid[1] ratio_diff = abs(aspect_ratio - grid_aspect_ratio) if ratio_diff < best_ratio_diff: best_ratio_diff = ratio_diff best_grid = grid elif ratio_diff == best_ratio_diff: # if the aspect ratio difference is the same, we favor the grid with more patches # until the area covered by the patches is more than twice the original image area if area > 0.5 * target_tile_height * target_tile_width * grid[0] * grid[1]: best_grid = grid return best_grid
GotOcr2ImageProcessorKwargs
python
tensorflow__tensorflow
tensorflow/lite/tools/visualize.py
{ "start": 7232, "end": 17766 }
class ____: """Maps a list of tensor indices to a tooltip hoverable indicator of more.""" def __init__(self, subgraph_data): self.data = subgraph_data def __call__(self, x): html = "" if x is None: return html html += "<span class='tooltip'><span class='tooltipcontent'>" for i in x: tensor = self.data["tensors"][i] html += str(i) + " " html += NameListToString(tensor["name"]) + " " html += TensorTypeToName(tensor["type"]) + " " html += (repr(tensor["shape"]) if "shape" in tensor else "[]") html += (repr(tensor["shape_signature"]) if "shape_signature" in tensor else "[]") + "<br>" html += "</span>" html += repr(x) html += "</span>" return html def QuantizationMapper(q): """Pretty-print the quantization dictionary, truncating large arrays.""" if not q: return "" items_str = [] for key, value in q.items(): key_str = repr(key) # In TFLite, quantization arrays can be large. if isinstance(value, list) and len(value) > 20: head = value[:10] tail = value[-10:] value_str = (f"[{', '.join(map(repr, head))}, ..., " f"{', '.join(map(repr, tail))}]") else: value_str = repr(value) items_str.append(f"{key_str}: {value_str}") return f"{{{', '.join(items_str)}}}" def GenerateGraph(subgraph_idx, g, opcode_mapper): """Produces the HTML required to have a d3 visualization of the dag.""" def TensorName(idx): return "t%d" % idx def OpName(idx): return "o%d" % idx edges = [] nodes = [] first = {} second = {} pixel_mult = 200 # TODO(aselle): multiplier for initial placement width_mult = 170 # TODO(aselle): multiplier for initial placement for op_index, op in enumerate(g["operators"] or []): if op["inputs"] is not None: for tensor_input_position, tensor_index in enumerate(op["inputs"]): if tensor_index not in first: first[tensor_index] = ((op_index - 0.5 + 1) * pixel_mult, (tensor_input_position + 1) * width_mult) edges.append({ "source": TensorName(tensor_index), "target": OpName(op_index) }) if op["outputs"] is not None: for tensor_output_position, tensor_index in enumerate(op["outputs"]): if tensor_index not in second: second[tensor_index] = ((op_index + 0.5 + 1) * pixel_mult, (tensor_output_position + 1) * width_mult) edges.append({ "target": TensorName(tensor_index), "source": OpName(op_index) }) nodes.append({ "id": OpName(op_index), "name": opcode_mapper(op["opcode_index"]), "group": 2, "x": pixel_mult, "y": (op_index + 1) * pixel_mult }) for tensor_index, tensor in enumerate(g["tensors"]): initial_y = ( first[tensor_index] if tensor_index in first else second[tensor_index] if tensor_index in second else (0, 0)) nodes.append({ "id": TensorName(tensor_index), "name": "%r (%d)" % (getattr(tensor, "shape", []), tensor_index), "group": 1, "x": initial_y[1], "y": initial_y[0] }) graph_str = json.dumps({"nodes": nodes, "edges": edges}) html = _D3_HTML_TEMPLATE % (graph_str, subgraph_idx) return html def GenerateTableHtml(items, keys_to_print, display_index=True): """Given a list of object values and keys to print, make an HTML table. Args: items: Items to print an array of dicts. keys_to_print: (key, display_fn). `key` is a key in the object. i.e. items[0][key] should exist. display_fn is the mapping function on display. i.e. the displayed html cell will have the string returned by `mapping_fn(items[0][key])`. display_index: add a column which is the index of each row in `items`. Returns: An html table. """ html = "" # Print the list of items html += "<table class='data-table'>\n" html += "<tr>\n" if display_index: html += "<th>index</th>" for h, mapper in keys_to_print: html += "<th>%s</th>" % h html += "</tr>\n" for idx, tensor in enumerate(items): html += "<tr>\n" if display_index: html += "<td>%d</td>" % idx # print tensor.keys() for h, mapper in keys_to_print: val = tensor[h] if h in tensor else None val = val if mapper is None else mapper(val) html += "<td><div class='cell-content'>%s</div></td>\n" % val html += "</tr>\n" html += "</table>\n" return html def CamelCaseToSnakeCase(camel_case_input): """Converts an identifier in CamelCase to snake_case.""" s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", camel_case_input) return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower() def FlatbufferToDict(fb, preserve_as_numpy): """Converts a hierarchy of FB objects into a nested dict. We avoid transforming big parts of the flat buffer into python arrays. This speeds conversion from ten minutes to a few seconds on big graphs. Args: fb: a flat buffer structure. (i.e. ModelT) preserve_as_numpy: true if all downstream np.arrays should be preserved. false if all downstream np.array should become python arrays Returns: A dictionary representing the flatbuffer rather than a flatbuffer object. """ if isinstance(fb, int) or isinstance(fb, float) or isinstance(fb, str): return fb elif hasattr(fb, "__dict__"): result = {} for attribute_name in dir(fb): attribute = fb.__getattribute__(attribute_name) if not callable(attribute) and attribute_name[0] != "_": snake_name = CamelCaseToSnakeCase(attribute_name) preserve = True if attribute_name == "buffers" else preserve_as_numpy result[snake_name] = FlatbufferToDict(attribute, preserve) return result elif isinstance(fb, np.ndarray): return fb if preserve_as_numpy else fb.tolist() elif hasattr(fb, "__len__"): return [FlatbufferToDict(entry, preserve_as_numpy) for entry in fb] else: return fb def CreateDictFromFlatbuffer(buffer_data): model_obj = schema_fb.Model.GetRootAsModel(buffer_data, 0) model = schema_fb.ModelT.InitFromObj(model_obj) return FlatbufferToDict(model, preserve_as_numpy=False) def create_html(tflite_input, input_is_filepath=True): # pylint: disable=invalid-name """Returns html description with the given tflite model. Args: tflite_input: TFLite flatbuffer model path or model object. input_is_filepath: Tells if tflite_input is a model path or a model object. Returns: Dump of the given tflite model in HTML format. Raises: RuntimeError: If the input is not valid. """ # Convert the model into a JSON flatbuffer using flatc (build if doesn't # exist. if input_is_filepath: if not os.path.exists(tflite_input): raise RuntimeError("Invalid filename %r" % tflite_input) if tflite_input.endswith(".tflite") or tflite_input.endswith(".bin"): with open(tflite_input, "rb") as file_handle: file_data = bytearray(file_handle.read()) data = CreateDictFromFlatbuffer(file_data) elif tflite_input.endswith(".json"): data = json.load(open(tflite_input)) else: raise RuntimeError("Input file was not .tflite or .json") else: data = CreateDictFromFlatbuffer(tflite_input) html = "" html += _CSS html += "<h1>TensorFlow Lite Model</h2>" data["filename"] = tflite_input if input_is_filepath else ( "Null (used model object)") # Avoid special case toplevel_stuff = [("filename", None), ("version", None), ("description", None)] html += "<table class='data-table'>\n" for key, mapping in toplevel_stuff: if not mapping: mapping = lambda x: x val = mapping(data.get(key)) html += ("<tr><th>%s</th><td><div class='cell-content'>%s</div></td></tr>\n" % (key, val)) html += "</table>\n" # Spec on what keys to display buffer_keys_to_display = [("data", DataSizeMapper())] operator_keys_to_display = [("builtin_code", BuiltinCodeToName), ("custom_code", NameListToString), ("version", None)] # Update builtin code fields. for d in data["operator_codes"]: d["builtin_code"] = max(d["builtin_code"], d["deprecated_builtin_code"]) for subgraph_idx, g in enumerate(data["subgraphs"]): # Subgraph local specs on what to display html += "<div class='subgraph'>" tensor_mapper = TensorMapper(g) opcode_mapper = OpCodeMapper(data) op_keys_to_display = [("inputs", tensor_mapper), ("outputs", tensor_mapper), ("builtin_options", None), ("opcode_index", opcode_mapper)] tensor_keys_to_display = [("name", NameListToString), ("type", TensorTypeToName), ("shape", None), ("shape_signature", None), ("buffer", None), ("quantization", QuantizationMapper)] html += "<h2>Subgraph %d</h2>\n" % subgraph_idx # Inputs and outputs. html += "<h3>Inputs/Outputs</h3>\n" html += GenerateTableHtml([{ "inputs": g["inputs"], "outputs": g["outputs"] }], [("inputs", tensor_mapper), ("outputs", tensor_mapper)], display_index=False) # Print the tensors. html += "<h3>Tensors</h3>\n" html += GenerateTableHtml(g["tensors"], tensor_keys_to_display) # Print the ops. if g["operators"]: html += "<h3>Ops</h3>\n" html += GenerateTableHtml(g["operators"], op_keys_to_display) # Visual graph. html += "<svg id='subgraph%d' width='1600' height='900'></svg>\n" % ( subgraph_idx,) html += GenerateGraph(subgraph_idx, g, opcode_mapper) html += "</div>" # Buffers have no data, but maybe in the future they will html += "<h2>Buffers</h2>\n" html += GenerateTableHtml(data["buffers"], buffer_keys_to_display) # Operator codes html += "<h2>Operator Codes</h2>\n" html += GenerateTableHtml(data["operator_codes"], operator_keys_to_display) html += "</body></html>\n" return html def main(argv): try: tflite_input = argv[1] html_output = argv[2] except IndexError: print("Usage: %s <input tflite> <output html>" % (argv[0])) else: html = create_html(tflite_input) with open(html_output, "w") as output_file: output_file.write(html) if __name__ == "__main__": main(sys.argv)
TensorMapper
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_permissions.py
{ "start": 2152, "end": 2323 }
class ____: @check_permission(Permissions.LAUNCH_PIPELINE_EXECUTION) def mutate(self, graphene_info: ResolveInfo, **_kwargs): pass
FakeEnumPermissionMutation
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-cassandra/llama_index/tools/cassandra/cassandra_database_wrapper.py
{ "start": 17684, "end": 17961 }
class ____(Exception): """ Exception raised for errors in the database schema. Attributes: message -- explanation of the error """ def __init__(self, message: str): self.message = message super().__init__(self.message)
DatabaseError
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli_tests/cli_tests/api_tests/deployment_tests/test_business_logic.py
{ "start": 2128, "end": 3554 }
class ____: """Test the deployment formatting functions.""" def _create_sample_deployment_list(self): """Create sample DeploymentList from fixture data.""" # Load from fixture and convert to domain objects response = load_recorded_graphql_responses("deployment", "success_multiple_deployments")[0] deployments = [ Deployment( id=dep["deploymentId"], name=dep["deploymentName"], type=DeploymentType(dep["deploymentType"]), ) for dep in response["fullDeployments"] ] return DeploymentList(items=deployments, total=len(deployments)) def test_format_deployments_text_output(self, snapshot): """Test formatting deployments as text.""" deployment_list = self._create_sample_deployment_list() result = format_deployments(deployment_list, as_json=False) # Snapshot the entire text output snapshot.assert_match(result) def test_format_deployments_json_output(self, snapshot): """Test formatting deployments as JSON.""" deployment_list = self._create_sample_deployment_list() result = format_deployments(deployment_list, as_json=True) # For JSON, we want to snapshot the parsed structure to avoid formatting differences parsed = json.loads(result) snapshot.assert_match(parsed)
TestFormatDeployments
python
wireservice__csvkit
csvkit/convert/fixed.py
{ "start": 2848, "end": 4092 }
class ____: """ Instantiated with a schema, able to return a sequence of trimmed strings representing fields given a fixed-length line. Flexible about where the columns are, as long as they are headed with the literal names 'column', 'start', and 'length'. """ def __init__(self, schema): self.fields = [] # A list of FixedWidthFields schema_reader = agate.csv.reader(schema) schema_decoder = SchemaDecoder(next(schema_reader)) for i, row in enumerate(schema_reader): try: self.fields.append(schema_decoder(row)) except Exception as e: raise ValueError("Error reading schema at line %i: %s" % (i + 2, e)) def parse(self, line): values = [] for field in self.fields: values.append(line[field.start:field.start + field.length].strip()) return values def parse_dict(self, line): """ Convenience method returns a dict. Equivalent to ``dict(zip(self.headers,self.parse(line)))``. """ return dict(zip(self.headers, self.parse(line))) @property def headers(self): return [field.name for field in self.fields]
FixedWidthRowParser
python
pytorch__pytorch
test/test_overrides.py
{ "start": 49989, "end": 50183 }
class ____(TestCase): # Regression test for gh-55868 def test_rnn(self): model = torch.nn.RNN(10, 20, 2) input = Wrapper(torch.randn(1, 5, 10)) model(input)
TestRNN
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocolExplicit1.py
{ "start": 1201, "end": 1240 }
class ____(Protocol5): pass
Concrete5
python
getsentry__sentry
tests/snuba/api/endpoints/test_organization_events_mep.py
{ "start": 130106, "end": 146434 }
class ____( MetricsEnhancedPerformanceTestCase ): viewname = "sentry-api-0-organization-events" def setUp(self) -> None: super().setUp() self.url = reverse( self.viewname, kwargs={"organization_id_or_slug": self.organization.slug} ) self.features = {"organizations:on-demand-metrics-extraction-widgets": True} def _create_specs( self, params: dict[str, Any], groupbys: list[str] | None = None ) -> list[OnDemandMetricSpec]: """Creates all specs based on the parameters that would be passed to the endpoint.""" specs = [] for field in params["field"]: spec = OnDemandMetricSpec( field=field, query=params["query"], environment=params.get("environment"), groupbys=groupbys, spec_type=MetricSpecType.DYNAMIC_QUERY, ) specs.append(spec) return specs def _make_on_demand_request( self, params: dict[str, Any], extra_features: dict[str, bool] | None = None ) -> Response: """Ensures that the required parameters for an on-demand request are included.""" # Expected parameters for this helper function params["dataset"] = "metricsEnhanced" params["useOnDemandMetrics"] = "true" params["onDemandType"] = "dynamic_query" _features = {**self.features, **(extra_features or {})} return self.do_request(params, features=_features) def _assert_on_demand_response( self, response: Response, expected_on_demand_query: bool | None = True, expected_dataset: str | None = "metricsEnhanced", ) -> None: """Basic assertions for an on-demand request.""" assert response.status_code == 200, response.content meta = response.data["meta"] assert meta.get("isMetricsExtractedData", False) is expected_on_demand_query assert meta["dataset"] == expected_dataset def test_is_metrics_extracted_data_is_included(self) -> None: params = {"field": ["count()"], "query": "transaction.duration:>=91", "yAxis": "count()"} specs = self._create_specs(params) for spec in specs: self.store_on_demand_metric(1, spec=spec) response = self._make_on_demand_request(params) self._assert_on_demand_response(response) def test_on_demand_user_misery(self) -> None: user_misery_field = "user_misery(300)" query = "transaction.duration:>=100" # We store data for both specs, however, when the query builders try to query # for the data it will not query on-demand data for spec_version in OnDemandMetricSpecVersioning.get_spec_versions(): spec = OnDemandMetricSpec( field=user_misery_field, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY, # We only allow querying the function in the latest spec version, # otherwise, the data returned by the endpoint would be 0.05 spec_version=spec_version, ) tags = {"satisfaction": "miserable"} self.store_on_demand_metric(1, spec=spec, additional_tags=tags, timestamp=self.min_ago) self.store_on_demand_metric(2, spec=spec, timestamp=self.min_ago) params = {"field": [user_misery_field], "project": self.project.id, "query": query} self._create_specs(params) # We expect it to be False because we're not using the extra feature flag response = self._make_on_demand_request(params) self._assert_on_demand_response(response, expected_on_demand_query=False) # Since we're using the extra feature flag we expect user_misery to be an on-demand metric response = self._make_on_demand_request(params, {SPEC_VERSION_TWO_FLAG: True}) self._assert_on_demand_response(response, expected_on_demand_query=True) assert response.data["data"] == [{user_misery_field: user_misery_formula(1, 2)}] def test_on_demand_user_misery_discover_split_with_widget_id_unsaved(self) -> None: user_misery_field = "user_misery(300)" query = "transaction.duration:>=100" _, widget, __ = create_widget(["count()"], "", self.project, discover_widget_split=None) # We store data for both specs, however, when the query builders try to query # for the data it will not query on-demand data for spec_version in OnDemandMetricSpecVersioning.get_spec_versions(): spec = OnDemandMetricSpec( field=user_misery_field, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY, # We only allow querying the function in the latest spec version, # otherwise, the data returned by the endpoint would be 0.05 spec_version=spec_version, ) tags = {"satisfaction": "miserable"} self.store_on_demand_metric(1, spec=spec, additional_tags=tags, timestamp=self.min_ago) self.store_on_demand_metric(2, spec=spec, timestamp=self.min_ago) params = {"field": [user_misery_field], "project": self.project.id, "query": query} self._create_specs(params) params["dashboardWidgetId"] = widget.id # Since we're using the extra feature flag we expect user_misery to be an on-demand metric with mock.patch.object(widget, "save") as mock_widget_save: response = self._make_on_demand_request(params, {SPEC_VERSION_TWO_FLAG: True}) assert bool(mock_widget_save.assert_called_once) self._assert_on_demand_response(response, expected_on_demand_query=True) assert response.data["data"] == [{user_misery_field: user_misery_formula(1, 2)}] def test_on_demand_user_misery_discover_split_with_widget_id_saved(self) -> None: user_misery_field = "user_misery(300)" query = "transaction.duration:>=100" _, widget, __ = create_widget( ["count()"], "", self.project, discover_widget_split=DashboardWidgetTypes.TRANSACTION_LIKE, # Transactions like uses on-demand ) # We store data for both specs, however, when the query builders try to query # for the data it will not query on-demand data for spec_version in OnDemandMetricSpecVersioning.get_spec_versions(): spec = OnDemandMetricSpec( field=user_misery_field, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY, # We only allow querying the function in the latest spec version, # otherwise, the data returned by the endpoint would be 0.05 spec_version=spec_version, ) tags = {"satisfaction": "miserable"} self.store_on_demand_metric(1, spec=spec, additional_tags=tags, timestamp=self.min_ago) self.store_on_demand_metric(2, spec=spec, timestamp=self.min_ago) params = {"field": [user_misery_field], "project": self.project.id, "query": query} self._create_specs(params) params["dashboardWidgetId"] = widget.id # Since we're using the extra feature flag we expect user_misery to be an on-demand metric with mock.patch.object(widget, "save") as mock_widget_save: response = self._make_on_demand_request(params, {SPEC_VERSION_TWO_FLAG: True}) assert bool(mock_widget_save.assert_not_called) self._assert_on_demand_response(response, expected_on_demand_query=True) assert response.data["data"] == [{user_misery_field: user_misery_formula(1, 2)}] def test_on_demand_count_unique(self) -> None: field = "count_unique(user)" query = "transaction.duration:>0" params = {"field": [field], "query": query} # We do not really have to create the metrics for both specs since # the first API call will not query any on-demand metric for spec_version in OnDemandMetricSpecVersioning.get_spec_versions(): spec = OnDemandMetricSpec( field=field, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY, spec_version=spec_version, ) self.store_on_demand_metric(1, spec=spec, timestamp=self.min_ago) self.store_on_demand_metric(2, spec=spec, timestamp=self.min_ago) # The first call will not be on-demand response = self._make_on_demand_request(params) self._assert_on_demand_response(response, expected_on_demand_query=False) # This second call will be on-demand response = self._make_on_demand_request( params, extra_features={SPEC_VERSION_TWO_FLAG: True} ) self._assert_on_demand_response(response, expected_on_demand_query=True) assert response.data["data"] == [{"count_unique(user)": 2}] def test_on_demand_for_metrics_deprecation(self) -> None: params = {"field": ["count()"], "query": "", "yAxis": "count()"} specs = self._create_specs(params) for spec in specs: self.store_on_demand_metric(1, spec=spec) with self.feature("organizations:on-demand-gen-metrics-deprecation-query-prefill"): response = self._make_on_demand_request(params) self._assert_on_demand_response(response) def test_split_decision_for_errors_widget(self) -> None: error_data = load_data("python", timestamp=before_now(minutes=1)) self.store_event( data={ **error_data, "exception": {"values": [{"type": "blah", "data": {"values": []}}]}, }, project_id=self.project.id, ) _, widget, __ = create_widget( ["count()", "error.type"], "error.type:blah", self.project, discover_widget_split=None ) response = self.do_request( { "field": ["count()", "error.type"], "query": "error.type:blah", "dataset": "metricsEnhanced", "per_page": 50, "dashboardWidgetId": widget.id, } ) assert response.status_code == 200, response.content assert response.data.get("meta").get( "discoverSplitDecision" ) is DashboardWidgetTypes.get_type_name(DashboardWidgetTypes.ERROR_EVENTS) widget.refresh_from_db() assert widget.discover_widget_split == DashboardWidgetTypes.ERROR_EVENTS assert widget.dataset_source == DatasetSourcesTypes.INFERRED.value def test_split_decision_for_transactions_widget(self) -> None: transaction_data = load_data("transaction", timestamp=before_now(minutes=1)) self.store_event( data={ **transaction_data, }, project_id=self.project.id, ) _, widget, __ = create_widget( ["count()", "transaction.name"], "", self.project, discover_widget_split=None ) assert widget.discover_widget_split is None response = self.do_request( { "field": ["count()", "transaction.name"], "query": "", "dataset": "metricsEnhanced", "per_page": 50, "dashboardWidgetId": widget.id, } ) assert response.status_code == 200, response.content assert response.data.get("meta").get( "discoverSplitDecision" ) is DashboardWidgetTypes.get_type_name(DashboardWidgetTypes.TRANSACTION_LIKE) widget.refresh_from_db() assert widget.discover_widget_split == DashboardWidgetTypes.TRANSACTION_LIKE assert widget.dataset_source == DatasetSourcesTypes.INFERRED.value def test_split_decision_for_ambiguous_widget_without_data(self) -> None: _, widget, __ = create_widget( ["count()", "transaction.name", "error.type"], "", self.project, discover_widget_split=None, ) assert widget.discover_widget_split is None response = self.do_request( { "field": ["count()", "transaction.op", "error.type"], "query": "", "dataset": "metricsEnhanced", "per_page": 50, "dashboardWidgetId": widget.id, }, ) assert response.status_code == 200, response.content assert response.data.get("meta").get( "discoverSplitDecision" ) == DashboardWidgetTypes.get_type_name(DashboardWidgetTypes.ERROR_EVENTS) widget.refresh_from_db() assert widget.discover_widget_split == DashboardWidgetTypes.ERROR_EVENTS assert widget.dataset_source == DatasetSourcesTypes.FORCED.value def test_split_decision_for_ambiguous_widget_with_data(self) -> None: # Store a transaction transaction_data = load_data("transaction", timestamp=before_now(minutes=1)) self.store_event( data={ **transaction_data, }, project_id=self.project.id, ) # Store an event error_data = load_data("python", timestamp=before_now(minutes=1)) self.store_event( data={ **error_data, "exception": {"values": [{"type": "blah", "data": {"values": []}}]}, }, project_id=self.project.id, ) _, widget, __ = create_widget( ["count()"], "", self.project, discover_widget_split=None, ) assert widget.discover_widget_split is None response = self.do_request( { "field": ["count()"], "query": "", "dataset": "metricsEnhanced", "per_page": 50, "dashboardWidgetId": widget.id, }, ) assert response.status_code == 200, response.content assert response.data.get("meta").get( "discoverSplitDecision" ) == DashboardWidgetTypes.get_type_name(DashboardWidgetTypes.ERROR_EVENTS) widget.refresh_from_db() assert widget.discover_widget_split == DashboardWidgetTypes.ERROR_EVENTS assert widget.dataset_source == DatasetSourcesTypes.FORCED.value @mock.patch("sentry.snuba.errors.query") def test_errors_request_made_for_saved_error_dashboard_widget_type( self, mock_errors_query: mock.MagicMock ) -> None: mock_errors_query.return_value = { "data": [], "meta": {}, } _, widget, __ = create_widget( ["count()"], "", self.project, discover_widget_split=DashboardWidgetTypes.ERROR_EVENTS ) response = self.do_request( { "field": [ "count()", ], "query": "", "dataset": "metricsEnhanced", "per_page": 50, "dashboardWidgetId": widget.id, } ) assert response.status_code == 200, response.content mock_errors_query.assert_called_once() @mock.patch("sentry.snuba.metrics_enhanced_performance.query") def test_metrics_enhanced_request_made_for_saved_transaction_like_dashboard_widget_type( self, mock_mep_query ): mock_mep_query.return_value = { "data": [], "meta": {}, } _, widget, __ = create_widget( ["count()"], "", self.project, discover_widget_split=DashboardWidgetTypes.TRANSACTION_LIKE, ) response = self.do_request( { "field": [ "count()", ], "query": "", "dataset": "metricsEnhanced", "per_page": 50, "dashboardWidgetId": widget.id, } ) assert response.status_code == 200, response.content mock_mep_query.assert_called_once()
OrganizationEventsMetricsEnhancedPerformanceEndpointTestWithOnDemandMetrics
python
haoel__leetcode
algorithms/python/firstMissingPositive/firstMissingPositive.py
{ "start": 552, "end": 1070 }
class ____: def firstMissingPositive(self, nums: [int]) -> int: for i in range(len(nums)): while nums[i]>0 and nums[i]<len(nums) and nums[i]-1!=i and nums[i]!=nums[nums[i]-1]: nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1] for i in range(len(nums)): if i + 1 != nums[i]: return i + 1 return len(nums) + 1 if __name__ == '__main__': number = Solution() print(number.firstMissingPositive([3,4,-1,1]))
Solution
python
vyperlang__vyper
vyper/exceptions.py
{ "start": 8371, "end": 8470 }
class ____(VyperException): """Assignment to a name that is already in use."""
NamespaceCollision
python
django__django
tests/serializers/tests.py
{ "start": 19322, "end": 20909 }
class ____: available_apps = ["serializers"] @skipUnlessDBFeature("supports_forward_references") def test_forward_refs(self): """ Objects ids can be referenced before they are defined in the serialization data. """ # The deserialization process needs to run in a transaction in order # to test forward reference handling. with transaction.atomic(): objs = serializers.deserialize(self.serializer_name, self.fwd_ref_str) with connection.constraint_checks_disabled(): for obj in objs: obj.save() for model_cls in (Category, Author, Article): self.assertEqual(model_cls.objects.count(), 1) art_obj = Article.objects.all()[0] self.assertEqual(art_obj.categories.count(), 1) self.assertEqual(art_obj.author.name, "Agnes") def register_tests(test_class, method_name, test_func, exclude=()): """ Dynamically create serializer tests to ensure that all registered serializers are automatically tested. """ for format_ in serializers.get_serializer_formats(): if format_ == "geojson" or format_ in exclude: continue decorated_func = skipIf( isinstance(serializers.get_serializer(format_), serializers.BadSerializer), "The Python library for the %s serializer is not installed." % format_, )(test_func) setattr( test_class, method_name % format_, partialmethod(decorated_func, format_) )
SerializersTransactionTestBase
python
numba__numba
numba/tests/test_dyn_array.py
{ "start": 26269, "end": 27804 }
class ____(object): def mutate_array(self, arr): try: arr.fill(42) except (TypeError, ValueError): # Try something else (e.g. Numpy 1.6 with structured dtypes) fill_value = b'x' * arr.dtype.itemsize arr.fill(fill_value) def check_like(self, pyfunc, dtype): def check_arr(arr): expected = pyfunc(arr) ret = cfunc(arr) self.assertEqual(ret.size, expected.size) self.assertEqual(ret.dtype, expected.dtype) self.assertStridesEqual(ret, expected) self.check_result_value(ret, expected) # test writability self.mutate_array(ret) self.mutate_array(expected) np.testing.assert_equal(ret, expected) orig = np.linspace(0, 5, 6).astype(dtype) cfunc = nrtjit(pyfunc) for shape in (6, (2, 3), (1, 2, 3), (3, 1, 2), ()): if shape == (): arr = orig[-1:].reshape(()) else: arr = orig.reshape(shape) check_arr(arr) # Non-contiguous array if arr.ndim > 0: check_arr(arr[::2]) # Check new array doesn't inherit readonly flag arr.flags['WRITEABLE'] = False # verify read-only with self.assertRaises(ValueError): arr[0] = 1 check_arr(arr) # Scalar argument => should produce a 0-d array check_arr(orig[0])
ConstructorLikeBaseTest
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-vllm/llama_index/embeddings/vllm/base.py
{ "start": 589, "end": 7600 }
class ____(MultiModalEmbedding): """ Vllm LLM. This class runs a vLLM embedding model locally. """ tensor_parallel_size: Optional[int] = Field( default=1, description="The number of GPUs to use for distributed execution with tensor parallelism.", ) trust_remote_code: Optional[bool] = Field( default=True, description="Trust remote code (e.g., from HuggingFace) when downloading the model and tokenizer.", ) dtype: str = Field( default="auto", description="The data type for the model weights and activations.", ) download_dir: Optional[str] = Field( default=None, description="Directory to download and load the weights. (Default to the default cache dir of huggingface)", ) vllm_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Holds any model parameters valid for `vllm.LLM` call not explicitly specified.", ) _client: Any = PrivateAttr() _image_token_id: Union[int, None] = PrivateAttr() def __init__( self, model_name: str = "facebook/opt-125m", embed_batch_size: int = DEFAULT_EMBED_BATCH_SIZE, tensor_parallel_size: int = 1, trust_remote_code: bool = False, dtype: str = "auto", download_dir: Optional[str] = None, vllm_kwargs: Dict[str, Any] = {}, callback_manager: Optional[CallbackManager] = None, ) -> None: callback_manager = callback_manager or CallbackManager([]) super().__init__( model_name=model_name, embed_batch_size=embed_batch_size, callback_manager=callback_manager, ) try: from vllm import LLM as VLLModel except ImportError: raise ImportError( "Could not import vllm python package. " "Please install it with `pip install vllm`." ) self._client = VLLModel( model=model_name, task="embed", max_num_seqs=embed_batch_size, tensor_parallel_size=tensor_parallel_size, trust_remote_code=trust_remote_code, dtype=dtype, download_dir=download_dir, **vllm_kwargs, ) try: self._image_token_id = ( self._client.llm_engine.model_config.hf_config.image_token_id ) except AttributeError: self._image_token_id = None @classmethod def class_name(cls) -> str: return "VllmEmbedding" @atexit.register def close(): import torch import gc if torch.cuda.is_available(): gc.collect() torch.cuda.empty_cache() torch.cuda.synchronize() @retry( stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10), reraise=True, ) def _embed_with_retry( self, inputs: List[Union[str, BytesIO]], embed_type: str = "text" ) -> List[List[float]]: """ Generates embeddings with retry mechanism. Args: inputs: List of texts or images to embed Returns: List of embedding vectors Raises: Exception: If embedding fails after retries """ try: if embed_type == "image": inputs = [ { "prompt_token_ids": [self._image_token_id], "multi_modal_data": {"image": x}, } for x in inputs ] emb = self._client.embed(inputs) return [x.outputs.embedding for x in emb] except Exception as e: logger.warning(f"Embedding attempt failed: {e!s}") raise def _embed( self, inputs: List[Union[str, BytesIO]], embed_type: str = "text" ) -> List[List[float]]: """ Generates Embeddings with input validation and retry mechanism. Args: sentences: Texts or Sentences to embed prompt_name: The name of the prompt to use for encoding Returns: List of embedding vectors Raises: ValueError: If any input text is invalid Exception: If embedding fails after retries """ if embed_type not in SUPPORT_EMBED_TYPES: raise (ValueError("Not Implemented")) return self._embed_with_retry(inputs, embed_type) def _get_query_embedding(self, query: str) -> List[float]: """ Generates Embeddings for Query. Args: query (str): Query text/sentence Returns: List[float]: numpy array of embeddings """ return self._embed([query])[0] async def _aget_query_embedding(self, query: str) -> List[float]: """ Generates Embeddings for Query Asynchronously. Args: query (str): Query text/sentence Returns: List[float]: numpy array of embeddings """ return self._get_query_embedding(query) async def _aget_text_embedding(self, text: str) -> List[float]: """ Generates Embeddings for text Asynchronously. Args: text (str): Text/Sentence Returns: List[float]: numpy array of embeddings """ return self._get_text_embedding(text) def _get_text_embedding(self, text: str) -> List[float]: """ Generates Embeddings for text. Args: text (str): Text/sentences Returns: List[float]: numpy array of embeddings """ return self._embed([text])[0] def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]: """ Generates Embeddings for text. Args: texts (List[str]): Texts / Sentences Returns: List[List[float]]: numpy array of embeddings """ return self._embed(texts) def _get_image_embedding(self, img_file_path: ImageType) -> List[float]: """Generate embedding for an image.""" image = Image.open(img_file_path) return self._embed([image], "image")[0] async def _aget_image_embedding(self, img_file_path: ImageType) -> List[float]: """Generate embedding for an image asynchronously.""" return self._get_image_embedding(img_file_path) def _get_image_embeddings( self, img_file_paths: List[ImageType] ) -> List[List[float]]: images = [Image.open(x) for x in img_file_paths] """Generate embeddings for multiple images.""" return self._embed(images, "image") async def _aget_image_embeddings( self, img_file_paths: List[ImageType] ) -> List[List[float]]: """Generate embeddings for multiple images asynchronously.""" return self._get_image_embeddings(img_file_paths)
VllmEmbedding
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py
{ "start": 43425, "end": 47358 }
class ____(PreTrainedConfig): """ This is the configuration class to store the configuration of a [`Qwen2_5OmniForConditionalGeneration`]. It is used to instantiate a Qwen2.5Omni model according to the specified sub-models configurations, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the [Qwen/Qwen2.5-Omni-7B](https://huggingface.co/Qwen/Qwen2.5-Omni-7B) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: thinker_config (`dict`, *optional*): Configuration of the underlying thinker sub-model. talker_config (`dict`, *optional*): Configuration of the underlying talker sub-model. token2wav_config (`dict`, *optional*): Configuration of the underlying codec sub-model. enable_audio_output (`bool`, *optional*, defaults to `True`): Whether enable audio output and load talker and token2wav module. Example: ```python >>> from transformers import ( ... Qwen2_5OmniThinkerConfig, ... Qwen2_5OmniTalkerConfig, ... Qwen2_5OmniToken2WavConfig, ... Qwen2_5OmniForConditionalGeneration, ... Qwen2_5OmniConfig, ... ) >>> # Initializing sub-modules configurations. >>> thinker_config = Qwen2_5OmniThinkerConfig() >>> talker_config = Qwen2_5OmniTalkerConfig() >>> token2wav_config = Qwen2_5OmniToken2WavConfig() >>> # Initializing a module style configuration >>> configuration = Qwen2_5OmniConfig( ... thinker_config, talker_config, token2wav_config ... ) >>> # Initializing a model (with random weights) >>> model = Qwen2_5OmniForConditionalGeneration(configuration) >>> # Accessing the model configuration >>> configuration = model.config ``` """ model_type = "qwen2_5_omni" sub_configs = { "thinker_config": Qwen2_5OmniThinkerConfig, "talker_config": Qwen2_5OmniTalkerConfig, "token2wav_config": Qwen2_5OmniToken2WavConfig, } def __init__( self, thinker_config=None, talker_config=None, token2wav_config=None, enable_audio_output: bool = True, **kwargs, ): if thinker_config is None: thinker_config = {} logger.info("thinker_config is None. Initializing thinker model with default values") if talker_config is None: talker_config = {} logger.info("talker_config is None. Initializing talker model with default values") if token2wav_config is None: token2wav_config = {} logger.info("token2wav_config is None. Initializing token2wav model with default values") self.thinker_config = Qwen2_5OmniThinkerConfig(**thinker_config) self.talker_config = Qwen2_5OmniTalkerConfig(**talker_config) self.token2wav_config = Qwen2_5OmniToken2WavConfig(**token2wav_config) self.enable_audio_output = enable_audio_output super().__init__(**kwargs) def get_text_config(self, *args, **kwargs): """ Returns the config that is meant to be used with text IO. On most models, it is the original config instance itself. On specific composite models, it is under a set of valid names. Args: decoder (`Optional[bool]`, *optional*, defaults to `False`): If set to `True`, then only search for decoder config names. """ # Overridden for deeply nested config like Qwen2-Omni. We don't have any omni model # except for Qwen yet. This has to be generalized if more deeply nested configs are # added. NOTE: currently method used only by vLLM return self.thinker_config.get_text_config(*args, **kwargs)
Qwen2_5OmniConfig
python
imageio__imageio
imageio/plugins/_freeimage.py
{ "start": 47466, "end": 51739 }
class ____(FIBaseBitmap): """Wrapper for the multipage FI bitmap object.""" def load_from_filename(self, filename=None): if filename is None: # pragma: no cover filename = self._filename # Prepare create_new = False read_only = True keep_cache_in_memory = False # Try opening with self._fi as lib: # Create bitmap multibitmap = lib.FreeImage_OpenMultiBitmap( self._ftype, efn(filename), create_new, read_only, keep_cache_in_memory, self._flags, ) multibitmap = ctypes.c_void_p(multibitmap) # Check if not multibitmap: # pragma: no cover err = self._fi._get_error_message() raise ValueError( 'Could not open file "%s" as multi-image: %s' % (self._filename, err) ) self._set_bitmap(multibitmap, (lib.FreeImage_CloseMultiBitmap, multibitmap)) # def load_from_bytes(self, bb): # with self._fi as lib: # # Create bitmap # fimemory = lib.FreeImage_OpenMemory( # ctypes.c_char_p(bb), len(bb)) # multibitmap = lib.FreeImage_LoadMultiBitmapFromMemory( # self._ftype, ctypes.c_void_p(fimemory), self._flags) # multibitmap = ctypes.c_void_p(multibitmap) # #lib.FreeImage_CloseMemory(ctypes.c_void_p(fimemory)) # self._mem = fimemory # self._bytes = bb # # Check # if not multibitmap: # raise ValueError('Could not load multibitmap "%s": %s' # % (self._filename, self._fi._get_error_message())) # else: # self._set_bitmap(multibitmap, # (lib.FreeImage_CloseMultiBitmap, multibitmap)) def save_to_filename(self, filename=None): if filename is None: # pragma: no cover filename = self._filename # Prepare create_new = True read_only = False keep_cache_in_memory = False # Open the file # todo: Set flags at close func with self._fi as lib: multibitmap = lib.FreeImage_OpenMultiBitmap( self._ftype, efn(filename), create_new, read_only, keep_cache_in_memory, 0, ) multibitmap = ctypes.c_void_p(multibitmap) # Check if not multibitmap: # pragma: no cover msg = 'Could not open file "%s" for writing multi-image: %s' % ( self._filename, self._fi._get_error_message(), ) raise ValueError(msg) self._set_bitmap(multibitmap, (lib.FreeImage_CloseMultiBitmap, multibitmap)) def __len__(self): with self._fi as lib: return lib.FreeImage_GetPageCount(self._bitmap) def get_page(self, index): """Return the sub-bitmap for the given page index. Please close the returned bitmap when done. """ with self._fi as lib: # Create low-level bitmap in freeimage bitmap = lib.FreeImage_LockPage(self._bitmap, index) bitmap = ctypes.c_void_p(bitmap) if not bitmap: # pragma: no cover raise ValueError( "Could not open sub-image %i in %r: %s" % (index, self._filename, self._fi._get_error_message()) ) # Get bitmap object to wrap this bitmap bm = FIBitmap(self._fi, self._filename, self._ftype, self._flags) bm._set_bitmap( bitmap, (lib.FreeImage_UnlockPage, self._bitmap, bitmap, False) ) return bm def append_bitmap(self, bitmap): """Add a sub-bitmap to the multi-page bitmap.""" with self._fi as lib: # no return value lib.FreeImage_AppendPage(self._bitmap, bitmap._bitmap) # Create instance fi = Freeimage()
FIMultipageBitmap
python
apache__airflow
airflow-core/src/airflow/callbacks/callback_requests.py
{ "start": 1777, "end": 2852 }
class ____(BaseCallbackRequest): """ Task callback status information. A Class with information about the success/failure TI callback to be executed. Currently, only failure callbacks when tasks are externally killed or experience heartbeat timeouts are run via DagFileProcessorProcess. """ ti: ti_datamodel.TaskInstance """Simplified Task Instance representation""" task_callback_type: TaskInstanceState | None = None """Whether on success, on failure, on retry""" context_from_server: ti_datamodel.TIRunContext | None = None """Task execution context from the Server""" type: Literal["TaskCallbackRequest"] = "TaskCallbackRequest" @property def is_failure_callback(self) -> bool: """Returns True if the callback is a failure callback.""" if self.task_callback_type is None: return True return self.task_callback_type in { TaskInstanceState.FAILED, TaskInstanceState.UP_FOR_RETRY, TaskInstanceState.UPSTREAM_FAILED, }
TaskCallbackRequest
python
django__django
tests/admin_views/admin.py
{ "start": 19197, "end": 19296 }
class ____(forms.ModelForm): class Meta: widgets = {"title": forms.HiddenInput}
StoryForm
python
getsentry__sentry
src/sentry/management/commands/generate_controlsilo_urls.py
{ "start": 1495, "end": 7526 }
class ____(BaseCommand): help = "Generate a list of URL patterns served by control silo endpoints" def add_arguments(self, parser): parser.add_argument( "--format", choices=["text", "js"], dest="format", default="text", help="The format of the file write to --output. Can either write data or JS code.", ) parser.add_argument( "--output", dest="output", action="store", default=None, help="The file to write the generated pattern list to.", ) parser.add_argument( "--urlconf", dest="urlconf", default="ROOT_URLCONF", help="The settings attribute with URL configuration.", ) def handle(self, **options): try: urlconf = importlib.import_module(getattr(settings, options["urlconf"])) except ImportError as e: self.stdout.write(f"Failed to load URL configuration {e}") raise CommandError("Could not load URL configuration") view_functions = self.extract_views_from_urlpatterns(urlconf.urlpatterns) url_patterns = [] for info in view_functions: func = info.callable if isinstance(func, functools.partial): func = func.func if hasattr(func, "view_class"): func = func.view_class if hasattr(func, "__name__"): func_name = func.__name__ elif hasattr(func, "__class__"): func_name = func.__class__.__name__ else: func_name = re.sub(r" at 0x[0-9a-f]+", "", repr(func)) module = f"{func.__module__}.{func_name}" try: import_module = importlib.import_module(func.__module__) view_func = getattr(import_module, func_name) except AttributeError: continue except ImportError as err: raise CommandError(f"Could not load view in {module}: {err}") if not hasattr(view_func, "silo_limit"): continue silo_limit = view_func.silo_limit if SiloMode.CONTROL not in silo_limit.modes: continue simple_pattern = simplify_regex(info.pattern) url_patterns.append(simple_pattern) contents = self.render(url_patterns, options["format"]) if not options["output"]: self.stdout.write(contents) else: self.stdout.write(f"Writing {options['output']} file..") with open(options["output"], "w") as fh: fh.write(contents) self.stdout.write("All done") def render(self, url_patterns: list[str], format: str) -> str: if format == "text": return "\n".join(url_patterns) if format == "js": js_regex = [f"new RegExp('{pattern}')," for pattern in url_patterns] pattern_code = "\n ".join(js_regex) ts_code = f"""// This is generated code. // To update it run `getsentry django generate_controlsilo_urls --format=js --output=/path/to/thisfile.ts` const patterns: RegExp[] = [ {pattern_code} ]; export default patterns; """ return ts_code raise TypeError(f"Invalid format chosen {format}") def extract_views_from_urlpatterns( self, urlpatterns, base: str = "", namespace: str | None = None ) -> list[PatternInfo]: # Inspired by # https://github.com/django-extensions/django-extensions/blob/main/django_extensions/management/commands/show_urls.py views = [] for pat in urlpatterns: if isinstance(pat, URLPattern): try: if not pat.name: name: str | None = pat.name elif namespace: name = f"{namespace}:{pat.name}" else: name = pat.name if name in IGNORED_PATTERN_NAMES: continue pattern = describe_pattern(pat) views.append( PatternInfo(callable=pat.callback, pattern=base + pattern, name=name) ) except ViewDoesNotExist: continue elif isinstance(pat, URLResolver): try: patterns = pat.url_patterns except ImportError: continue if namespace and pat.namespace: resolved_namespace = f"{namespace}:{pat.namespace}" else: resolved_namespace = pat.namespace or namespace or "" pattern = describe_pattern(pat) views.extend( self.extract_views_from_urlpatterns( patterns, base + pattern, namespace=resolved_namespace ) ) elif hasattr(pat, "_get_callback"): try: views.append( PatternInfo( callable=pat._get_callback(), pattern=base + describe_pattern(pat), name=pat.name, ) ) except ViewDoesNotExist: continue elif hasattr(pat, "url_patterns") or hasattr(pat, "_get_url_patterns"): try: patterns = pat.url_patterns except ImportError: continue views.extend( self.extract_views_from_urlpatterns( patterns, base=base + describe_pattern(pat), namespace=namespace ) ) else: raise TypeError(f"{pat} is not a urlpattern object.") return views
Command
python
tqdm__tqdm
tests/tests_contrib_logging.py
{ "start": 964, "end": 2123 }
class ____: def test_should_call_tqdm_write(self): CustomTqdm.messages = [] logger = logging.Logger('test') logger.handlers = [TqdmLoggingHandler(CustomTqdm)] logger.info('test') assert CustomTqdm.messages == ['test'] def test_should_call_handle_error_if_exception_was_thrown(self): patch = importorskip('unittest.mock').patch logger = logging.Logger('test') ErrorRaisingTqdm.exception_class = RuntimeError handler = TqdmLoggingHandler(ErrorRaisingTqdm) logger.handlers = [handler] with patch.object(handler, 'handleError') as mock: logger.info('test') assert mock.called @pytest.mark.parametrize('exception_class', [ KeyboardInterrupt, SystemExit ]) def test_should_not_swallow_certain_exceptions(self, exception_class): logger = logging.Logger('test') ErrorRaisingTqdm.exception_class = exception_class handler = TqdmLoggingHandler(ErrorRaisingTqdm) logger.handlers = [handler] with pytest.raises(exception_class): logger.info('test')
TestTqdmLoggingHandler
python
Textualize__textual
src/textual/renderables/text_opacity.py
{ "start": 1068, "end": 3674 }
class ____: """Blend foreground into background.""" def __init__(self, renderable: RenderableType, opacity: float = 1.0) -> None: """Wrap a renderable to blend foreground color into the background color. Args: renderable: The RenderableType to manipulate. opacity: The opacity as a float. A value of 1.0 means text is fully visible. """ self.renderable = renderable self.opacity = opacity @classmethod def process_segments( cls, segments: Iterable[Segment], opacity: float, ansi_theme: TerminalTheme, ) -> Iterable[Segment]: """Apply opacity to segments. Args: segments: Incoming segments. opacity: Opacity to apply. ansi_theme: Terminal theme. background: Color of background. Returns: Segments with applied opacity. """ _Segment = Segment _from_color = Style.from_color if opacity == 0: for text, style, _control in cast( # use Tuple rather than tuple so Python 3.7 doesn't complain Iterable[Tuple[str, Style, object]], segments, ): invisible_style = _from_color(bgcolor=style.bgcolor) yield _Segment(cell_len(text) * " ", invisible_style) elif opacity == 1: yield from segments else: filter = ANSIToTruecolor(ansi_theme) for segment in filter.apply(list(segments), TRANSPARENT): # use Tuple rather than tuple so Python 3.7 doesn't complain text, style, control = cast(Tuple[str, Style, object], segment) if not style: yield segment continue color = style.color bgcolor = style.bgcolor if color and color.triplet and bgcolor and bgcolor.triplet: color_style = _get_blended_style_cached(bgcolor, color, opacity) yield _Segment(text, style + color_style) else: yield segment def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: try: app = active_app.get() except LookupError: ansi_theme = DEFAULT_TERMINAL_THEME else: ansi_theme = app.ansi_theme segments = console.render(self.renderable, options) return self.process_segments(segments, self.opacity, ansi_theme)
TextOpacity
python
great-expectations__great_expectations
great_expectations/expectations/metrics/column_aggregate_metrics/column_sum.py
{ "start": 580, "end": 1140 }
class ____(ColumnAggregateMetricProvider): metric_name = "column.sum" @column_aggregate_value(engine=PandasExecutionEngine) def _pandas(cls, column, **kwargs): convert_pandas_series_decimal_to_float_dtype(data=column, inplace=True) return column.sum() @column_aggregate_partial(engine=SqlAlchemyExecutionEngine) def _sqlalchemy(cls, column, **kwargs): return sa.func.sum(column) @column_aggregate_partial(engine=SparkDFExecutionEngine) def _spark(cls, column, **kwargs): return F.sum(column)
ColumnSum
python
realpython__materials
django-vue-graphql/source_code_final/back_end/blog/schema.py
{ "start": 462, "end": 1860 }
class ____(graphene.ObjectType): all_posts = graphene.List(PostType) author_by_username = graphene.Field(AuthorType, username=graphene.String()) post_by_slug = graphene.Field(PostType, slug=graphene.String()) posts_by_author = graphene.List(PostType, username=graphene.String()) posts_by_tag = graphene.List(PostType, tag=graphene.String()) def resolve_all_posts(root, info): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .all() ) def resolve_author_by_username(root, info, username): return models.Profile.objects.select_related("user").get( user__username=username ) def resolve_post_by_slug(root, info, slug): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .get(slug=slug) ) def resolve_posts_by_author(root, info, username): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .filter(author__user__username=username) ) def resolve_posts_by_tag(root, info, tag): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .filter(tags__name__iexact=tag) ) schema = graphene.Schema(query=Query)
Query
python
getsentry__sentry
tests/sentry/tasks/test_post_process.py
{ "start": 7376, "end": 13795 }
class ____(BasePostProgressGroupMixin): def _create_event( self, data: dict[str, Any], project_id: int | None = None, ) -> Event: data.setdefault("platform", "javascript") return self.store_event(data=data, project_id=project_id or self.project.id) def _generate_node_data(self, filename: str) -> dict[str, Any]: return { "stacktrace": {"frames": [{"filename": f"src/{filename}.py", "in_app": True}]}, "platform": "python", } def _call_post_process_group(self, event: Event) -> None: self.call_post_process_group( is_new=True, is_regression=False, is_new_group_environment=True, event=event, ) @patch("sentry.tasks.auto_source_code_config.auto_source_code_config") def test_derive_invalid_platform(self, mock_derive_code_mappings: MagicMock) -> None: event = self._create_event({"platform": "elixir"}) self._call_post_process_group(event) assert mock_derive_code_mappings.delay.call_count == 0 @patch("sentry.tasks.auto_source_code_config.auto_source_code_config") def test_derive_supported_languages(self, mock_derive_code_mappings: MagicMock) -> None: for platform in get_supported_platforms(): event = self._create_event(self._generate_node_data("foo")) self._call_post_process_group(event) assert mock_derive_code_mappings.delay.call_count == 1 @patch("sentry.tasks.auto_source_code_config.auto_source_code_config") def test_only_maps_a_given_project_once_per_hour( self, mock_derive_code_mappings: MagicMock ) -> None: dogs_project = self.create_project() maisey_event = self._create_event(self._generate_node_data("themaiseydog"), dogs_project.id) charlie_event = self._create_event(self._generate_node_data("charliebear"), dogs_project.id) cory_event = self._create_event(self._generate_node_data("thenudge"), dogs_project.id) bodhi_event = self._create_event(self._generate_node_data("escapeartist"), dogs_project.id) self._call_post_process_group(maisey_event) assert mock_derive_code_mappings.delay.call_count == 1 # second event from project should bail (no increase in call count) self._call_post_process_group(charlie_event) assert mock_derive_code_mappings.delay.call_count == 1 # advance the clock 59 minutes, and it should still bail with patch("time.time", return_value=time.time() + 60 * 59): self._call_post_process_group(cory_event) assert mock_derive_code_mappings.delay.call_count == 1 # now advance the clock 61 minutes, and this time it should go through with patch("time.time", return_value=time.time() + 60 * 61): self._call_post_process_group(bodhi_event) assert mock_derive_code_mappings.delay.call_count == 2 @patch("sentry.tasks.auto_source_code_config.auto_source_code_config") def test_only_maps_a_given_issue_once_per_day( self, mock_derive_code_mappings: MagicMock ) -> None: dogs_project = self.create_project() data = { "stacktrace": {"frames": [{"filename": "src/app/example.py", "in_app": True}]}, "platform": "python", } maisey_event1 = self._create_event(data, dogs_project.id) maisey_event2 = self._create_event(data, dogs_project.id) maisey_event3 = self._create_event(data, dogs_project.id) maisey_event4 = self._create_event(data, dogs_project.id) # because of the fingerprint, the events should always end up in the same group, # but the rest of the test is bogus if they aren't, so let's be sure assert maisey_event1.group_id == maisey_event2.group_id assert maisey_event2.group_id == maisey_event3.group_id assert maisey_event3.group_id == maisey_event4.group_id self._call_post_process_group(maisey_event1) assert mock_derive_code_mappings.delay.call_count == 1 # second event from group should bail (no increase in call count) self._call_post_process_group(maisey_event2) assert mock_derive_code_mappings.delay.call_count == 1 # advance the clock 23 hours and 59 minutes, and it should still bail with patch("time.time", return_value=time.time() + (60 * 60 * 23) + (60 * 59)): self._call_post_process_group(maisey_event3) assert mock_derive_code_mappings.delay.call_count == 1 # now advance the clock 24 hours and 1 minute, and this time it should go through with patch("time.time", return_value=time.time() + (60 * 60 * 24) + (60 * 1)): self._call_post_process_group(maisey_event4) assert mock_derive_code_mappings.delay.call_count == 2 @patch("sentry.tasks.auto_source_code_config.auto_source_code_config") def test_skipping_an_issue_doesnt_mark_it_processed( self, mock_derive_code_mappings: MagicMock ) -> None: dogs_project = self.create_project() maisey_event = self._create_event(self._generate_node_data("themaiseydog"), dogs_project.id) charlie_event1 = self._create_event( self._generate_node_data("charliebear"), dogs_project.id ) charlie_event2 = self._create_event( self._generate_node_data("charliebear"), dogs_project.id ) # because of the fingerprint, the two Charlie events should always end up in the same group, # but the rest of the test is bogus if they aren't, so let's be sure assert charlie_event1.group_id == charlie_event2.group_id self._call_post_process_group(maisey_event) assert mock_derive_code_mappings.delay.call_count == 1 # second event from project should bail (no increase in call count) self._call_post_process_group(charlie_event1) assert mock_derive_code_mappings.delay.call_count == 1 # now advance the clock 61 minutes (so the project should clear the cache), and another # event from the Charlie group should go through with patch("time.time", return_value=time.time() + 60 * 61): self._call_post_process_group(charlie_event2) assert mock_derive_code_mappings.delay.call_count == 2
DeriveCodeMappingsProcessGroupTestMixin
python
weaviate__weaviate-python-client
weaviate/collections/classes/config_vector_index.py
{ "start": 3901, "end": 4317 }
class ____(_VectorIndexConfigUpdate): dynamicEfMin: Optional[int] dynamicEfMax: Optional[int] dynamicEfFactor: Optional[int] ef: Optional[int] filterStrategy: Optional[VectorFilterStrategy] flatSearchCutoff: Optional[int] vectorCacheMaxObjects: Optional[int] @staticmethod def vector_index_type() -> VectorIndexType: return VectorIndexType.HNSW
_VectorIndexConfigHNSWUpdate
python
huggingface__transformers
src/transformers/modeling_gguf_pytorch_utils.py
{ "start": 1659, "end": 1748 }
class ____(NamedTuple): weights: np.ndarray name: str metadata: dict
GGUFTensor
python
pytorch__pytorch
test/inductor/test_torchinductor.py
{ "start": 484566, "end": 549111 }
class ____: suffixes: tuple[str, ...] is_skip: bool = False __test__: bool = False def copy_tests(my_cls, other_cls, suffix, test_failures=None, xfail_prop=None): # noqa: B902 for name, value in my_cls.__dict__.items(): if name.startswith("test_"): # You cannot copy functions in Python, so we use closures here to # create objects with different ids. Otherwise, unittest.skip # would modify all methods sharing the same object id. Also, by # using a default argument, we create a copy instead of a # reference. Otherwise, we would lose access to the value. @functools.wraps(value) def new_test(self, value=value): return value(self) # Copy __dict__ which may contain test metadata new_test.__dict__ = copy.deepcopy(value.__dict__) if xfail_prop is not None and hasattr(value, xfail_prop): new_test = unittest.expectedFailure(new_test) tf = test_failures and test_failures.get(name) if tf and suffix in tf.suffixes: skip_func = ( unittest.skip("Skipped!") if tf.is_skip else unittest.expectedFailure ) new_test = skip_func(new_test) setattr(other_cls, f"{name}_{suffix}", new_test) # Special case convenience routine if hasattr(my_cls, "is_dtype_supported"): other_cls.is_dtype_supported = my_cls.is_dtype_supported def add_test_failures( test_failures: dict[str, TestFailure], added_test_failures: dict[str, TestFailure] ): """ In-place modifies the given dictionary of `test_failures` to add the contents of `added_test_failures` by unioning the test_failure.suffixes, and or-ing the is_skip value. """ for name, new_failure in added_test_failures.items(): if name in test_failures: orig_failure = test_failures[name] orig_failure.suffixes = tuple( set(orig_failure.suffixes).union(set(new_failure.suffixes)) ) orig_failure.is_skip = orig_failure.is_skip or new_failure.is_skip else: test_failures[name] = new_failure if RUN_CPU: class SweepInputsCpuTest(SweepInputs2, TestCase): gen = InputGen(10, "cpu") SweepInputsCpuTest.populate() class CpuTests(TestCase): common = check_model device = "cpu" copy_tests(CommonTemplate, CpuTests, "cpu") if RUN_GPU or HAS_MPS: class SweepInputsGPUTest(SweepInputs2, TestCase): gen = InputGen(10, GPU_TYPE) SweepInputsGPUTest.populate() class GPUTests(TestCase): common = check_model_gpu device = GPU_TYPE copy_tests(CommonTemplate, GPUTests, GPU_TYPE) if RUN_GPU: @instantiate_parametrized_tests class TritonCodeGenTests(TestCase): from torch._inductor.runtime.triton_heuristics import CachingAutotuner device_type = GPU_TYPE device = GPU_TYPE class NoOpCompilerBackend: def __init__(self) -> None: self.example_args = None self.model = None def noop_backend( self, model_: torch.fx.GraphModule, example_inputs_: list[torch.Tensor], ): """ The Noop backend does not compile the fx graph it is given. Instead, it transforms the fx graph so that its functions are aten operations. It then saves this graph. """ from torch._inductor.decomposition import select_decomp_table from torch._subclasses import FakeTensorMode from torch.fx import Interpreter fake_mode = FakeTensorMode() def interpret(*args, **kwargs): return Interpreter(model_).run(*args[0:], **kwargs) fake_flat_tensor_args = [ fake_mode.from_tensor(x) for x in example_inputs_ ] fw_module = make_fx(interpret, select_decomp_table())( *fake_flat_tensor_args ) self.model = fw_module self.example_args = fake_flat_tensor_args return lambda x: example_inputs_ def get_kernels(self, fn, args) -> list[CachingAutotuner]: from torch._inductor.debug import DebugContext from torch._inductor.graph import GraphLowering from torch._inductor.virtualized import V cxt = TritonCodeGenTests.NoOpCompilerBackend() torch.compile(fn, backend=cxt.noop_backend)(*args) graph = GraphLowering(cxt.model) kernels = [] with V.set_graph_handler(graph), V.set_debug_handler(DebugContext()): graph.run(*(cxt.example_args)) mod = graph.compile_to_module() for val in mod.__dict__.values(): if isinstance( val, torch._inductor.runtime.triton_heuristics.CachingAutotuner ): kernels.append(val) return kernels def test_divisible_by_16_covers_numel_args(self): torch._dynamo.reset() def fn(a: torch.Tensor) -> torch.Tensor: return torch.sum(a) kernels = self.get_kernels(fn, [torch.randn([256, 256], device=GPU_TYPE)]) expected_divisible = { # kernel0 reduces from 256 to (xnumel=8, rnumel=8192), which means it reduces 256 by 256 into an array of # size 8 by accumulating 8192 elements at once note that rnumel is equal to 512 * 16, so rnumel which is # at slot 3 should be in the divisible by 16 descriptor 0: (0, 1, 3), # kernel1 reduces from 8 elements to a single scalar. # Since multi-kernel generate 2 variants for each kernel. The second # persistent-reduction has index 2. 1: (0, 1), } if config.triton.multi_kernel: self.assertEqual(len(kernels), 4) expected_divisible[2] = expected_divisible.pop(1) elif config.triton.cooperative_reductions: self.assertEqual(len(kernels), 1) expected_divisible = { # one kernel, with extra workspace/semaphore args 0: (0, 1, 2, 3, 5), } else: self.assertEqual(len(kernels), 2) for kernel_id, expected in expected_divisible.items(): divisible_by_16 = get_divisible_by_16( kernels[kernel_id].triton_meta["configs"][0] ) self.assertEqual(divisible_by_16, expected) torch._dynamo.reset() @config.patch(assume_aligned_inputs=False) def test_codegen_config_option_dont_assume_alignment(self): def fn(x: torch.Tensor) -> torch.Tensor: return x.sin() + x.cos() # We want code that assumes alignment if the initial input is 16-byte aligned for offset in (0, 1, 2, 3, 4): base = torch.randn(64 * 64 + 64, dtype=torch.float32, device=GPU_TYPE) inps = torch.as_strided(base, (64, 64), (64, 1), offset) torch._dynamo.reset() kernels = self.get_kernels(fn, [inps]) arguments_that_are_divisible_by_16 = get_divisible_by_16( kernels[0].triton_meta["configs"][0] ) # NO_ALIGN ALIGN ALIGN # def triton_(in_ptr0, out_ptr0, xnumel, XBLOCK : tl.constexpr) if offset % 4 == 0: expected_aligned = (0, 1, 2) else: expected_aligned = (1, 2) self.assertEqual(arguments_that_are_divisible_by_16, expected_aligned) # If input isn't a view, storage offset != , inductor will assume alignment. torch._dynamo.reset() inp = torch.randn((64, 64), device=GPU_TYPE) kernels = self.get_kernels(fn, [inp]) arguments_that_are_divisible_by_16 = get_divisible_by_16( kernels[0].triton_meta["configs"][0] ) self.assertEqual(arguments_that_are_divisible_by_16, (0, 1, 2)) def test_optimize_indexing_dtype(self): def fn(x: torch.Tensor) -> torch.Tensor: return aten.upsample_bilinear2d.vec(x, None, True, [2.0, 2.0]) fn_opt = torch.compile(fn, backend="inductor") inps = [torch.randn(2, 4, 16, 16, device=GPU_TYPE)] code = run_and_get_triton_code(fn_opt, *inps) self.assertTrue("to(tl.int32)" in code) self.assertFalse("to(tl.int64)" in code) self.assertEqual(fn_opt(*inps), fn(*inps)) @config.patch({"fx_graph_remote_cache": False}) def test_optimize_indexing_dtype_with_constraint(self): def fn1(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: x = torch.arange(0, b.shape[0], device=GPU_TYPE) y = ((x + x) / 3).int() return a[y.to(torch.int64)] def fn2(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: torch._check(b.shape[0] >= 2) torch._check(b.shape[0] <= 100) return fn1(a, b) fn1_opt = torch.compile(fn1, backend="inductor") fn2_opt = torch.compile(fn2, backend="inductor") a = torch.rand([100, 100], device=GPU_TYPE) b1 = torch.rand([102], device=GPU_TYPE) b2 = torch.rand([100], device=GPU_TYPE) torch._dynamo.mark_dynamic(b1, 0) torch._dynamo.mark_dynamic(b2, 0) inps1 = [a, b1] inps2 = [a, b2] # Run fn2 first since it has more restrictive bounds -- to avoid cache hit code2 = run_and_get_triton_code(fn2_opt, *inps2) code1 = run_and_get_triton_code(fn1_opt, *inps1) # The function with the constrained tensor should be optimized, but # the other should not: self.assertTrue("to(tl.int64)" in code1) self.assertTrue("to(tl.int32)" in code2) self.assertFalse("to(tl.int64)" in code2) self.assertEqual(fn1_opt(*inps1), fn1(*inps1)) self.assertEqual(fn2_opt(*inps2), fn1(*inps2)) def test_constant_folding_deallocation(self): import torch._inductor def fn(): li = [] for i in range(10): x = torch.full([100], i) x = x + 1 li.append(x) return li mod = make_fx(fn)() live_tensors = WeakTensorKeyDictionary() max_live_tensors = 0 class LiveTensors(TorchDispatchMode): def __torch_dispatch__(self, func, types, args=(), kwargs=None): nonlocal live_tensors nonlocal max_live_tensors kwargs = kwargs if kwargs else {} for arg in pytree.arg_tree_leaves(*args, **kwargs): if isinstance(arg, torch.Tensor): live_tensors[arg] = True out = func(*args, **kwargs) if not isinstance(out, torch.Tensor): return out live_tensors[out] = True max_live_tensors = max(max_live_tensors, len(live_tensors)) return out mode = LiveTensors() from torch._inductor.fx_passes.joint_graph import UniformValueConstantFolder with mode: UniformValueConstantFolder(mod).run() # there are a couple extra tensors created in `insertable_tensor_check` self.assertTrue(max_live_tensors == 3) # See https://github.com/pytorch/pytorch/issues/100348 @parametrize("backend", ["aot_eager", "inductor"]) def test_inductor_detach_view(self, backend): def fn(x: torch.Tensor) -> torch.Tensor: a = x * 2 return a, a.detach() fn_opt = torch.compile(fn, backend=backend) inp = torch.ones(2, 2, requires_grad=True, device=GPU_TYPE) inp_ref = inp.detach().clone().requires_grad_(True) out_ref = fn(inp_ref) out_ref[0].sum().backward() out = fn_opt(inp) out[0].sum().backward() self.assertEqual(inp.grad, inp_ref.grad) @requires_gpu() @unittest.skipIf( not PLATFORM_SUPPORTS_MEM_EFF_ATTENTION, "Does not support mem_eff_attention", ) def test_sdpa_inference_mode_aot_compile(self): class TestSDPA(torch.nn.Module): def __init__(self) -> None: super().__init__() def forward( self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, attn_mask: torch.Tensor, ): return torch.nn.functional.scaled_dot_product_attention( q, k, v, attn_mask=attn_mask, dropout_p=0.0, is_causal=False ) q = torch.rand([10, 4, 128, 64], device=GPU_TYPE, dtype=torch.bfloat16) k = torch.rand([10, 4, 128, 64], device=GPU_TYPE, dtype=torch.bfloat16) v = torch.rand([10, 4, 128, 64], device=GPU_TYPE, dtype=torch.bfloat16) attn_mask = ( torch.rand([10, 4, 128, 128], device=GPU_TYPE, dtype=torch.bfloat16) < 0.9 ) inputs = (q, k, v, attn_mask) import torch.export._trace as export_trace with torch.inference_mode(): traced = export_trace._export_to_torch_ir( TestSDPA(), inputs, disable_constraint_solver=True, restore_fqn=False, ) torch._inductor.aot_compile(traced, inputs) @skipCUDAIf(not SM90OrLater, "Requires sm90") @requires_cuda_and_triton @unittest.skipIf(TEST_WITH_ROCM, "no grouped_mm support") @config.patch(implicit_fallbacks=True) def test_grouped_mm(self): @torch.compile(fullgraph=True) def f(a, b, offs, out_dtype): return F.grouped_mm( a, b.transpose(-2, -1), offs=offs, out_dtype=out_dtype ) device = "cuda" dtype = torch.bfloat16 m, n, k, n_groups = 16, 32, 16, 4 a_ref = torch.randn(m * n_groups, k, device=device, dtype=dtype)[:, :k] b_ref = torch.randn( n_groups, n, k, device=device, dtype=dtype, )[::1, :, :k] offs = torch.arange( m, n_groups * m + 1, m, device=device, dtype=torch.int32 ) a_ref.requires_grad_(True) b_ref.requires_grad_(True) a_test = a_ref.clone().detach().requires_grad_() b_test = b_ref.clone().detach().requires_grad_() out_ref = f(a_ref, b_ref, offs, out_dtype=torch.bfloat16) out_ref.sum().backward() out_test = f(a_test, b_test, offs=offs, out_dtype=torch.bfloat16) out_test.sum().backward() self.assertEqual(out_ref, out_test) self.assertEqual(a_ref.grad, a_test.grad) self.assertEqual(b_ref.grad, b_test.grad) def test_optimize_indexing_assert(self): def has_indirect(code, tl_fn: str): self.assertTrue( tl_fn in code, msg=f"{tl_fn} not present:\n{code}", ) for line in code.split("\n"): if tl_fn in line: stmt = line.split(tl_fn)[-1] # indirect indexing involves a `tmp` variable self.assertTrue( "tmp" in stmt, msg=f"Indirect indexing not present in code:\n{line}", ) def has_assert(code, lower: bool, upper: bool): self.assertIn( "device_assert", code, msg=f"No device assert found:\n{code}" ) for line in code.split("\n"): if "device_assert" in line: self.assertTrue( ("0 <= " in line) is lower, msg=f"Lower bound {'' if lower else 'not '}elided:{line}", ) self.assertTrue( (" < " in line) is upper, msg=f"Upper bound {'' if upper else 'not '}elided:{line}", ) def fn(x: torch.Tensor) -> torch.Tensor: s = 1.0 * torch.arange(x.shape[0], device=x.device) return x[s.long()] # aten.index for dynamic in (False, True): fn_opt = torch.compile(fn, dynamic=dynamic) x = torch.randn(8, device=GPU_TYPE) code = run_and_get_triton_code(fn_opt, x) self.assertEqual(fn_opt(x), fn(x), msg=f"{dynamic=}") # Check that there's indirect indexing... has_indirect(code, tl_fn="tl.load") if not dynamic: # We elide the assert for static shapes self.assertNotIn("device_assert", code) else: # ...but we generate an upper bound for dynamic shapes has_assert(code, lower=False, upper=True) def fn(a, z, b, idx0, idx1): idx2 = torch.arange(a.shape[-1], device=a.device) a.index_put_((z, idx0, idx1, idx2), b, accumulate=True) return a # aten.index_put for dynamic in (False, True): fn_opt = torch.compile(fn, dynamic=dynamic) a = torch.randn(1, 32, 32, 4, device=GPU_TYPE) z = torch.zeros((), dtype=torch.int64, device=GPU_TYPE) b = torch.randn(33, 1, device=GPU_TYPE) idx0 = torch.randint(32, (33,), device=GPU_TYPE).view(33, 1, 1) idx1 = torch.randint(32, (33,), device=GPU_TYPE).view(33, 1) inps = (a.clone(), z, b, idx0, idx1) code = run_and_get_triton_code(fn_opt, *inps) # Correctness out_opt = fn_opt(a.clone(), z, b, idx0, idx1) out = fn(a.clone(), z, b, idx0, idx1) self.assertEqual(out_opt, out, msg=f"{dynamic=}") # We have an indirect store via atomic_add has_indirect(code, tl_fn="tl.atomic_add") # We cannot elide he assert in this case has_assert(code, lower=True, upper=True) def test_not_materialize_pointwise_reduction(self): def fn(a, b): return (a - b).sum(dim=-1).amax(dim=-1) N = 16 K = 7 fn_opt = torch.compile(fn, backend="inductor") inps = [ torch.randn(N, 1, K, device=GPU_TYPE), torch.randn(1, N, K, device=GPU_TYPE), ] code = run_and_get_triton_code(fn_opt, *inps) self.assertEqual( code.count("tl.store"), 2 if config.triton.multi_kernel else 1 ) self.assertTrue("out_ptr1" in code) self.assertFalse("out_ptr0" in code) self.assertEqual(fn_opt(*inps), fn(*inps)) def test_numpy_on_gpu(self): x = np.arange(10, dtype=np.float32) @torch.compile def fn(x): return np.sin(x) def fn_gpu(x): with torch.device(GPU_TYPE): return fn(x) r = fn_gpu(x) code = run_and_get_triton_code(fn_gpu, x) self.assertIn("tl_math.sin", code) self.assertEqual(type(r), np.ndarray) self.assertEqual(r, np.sin(x)) @config.patch(expand_dimension_for_pointwise_nodes=True) def test_rope_fusion(self): batch_size, seq_length, hidden_dim = 8, 16, 128 num_q_heads, num_kv_heads = 32, 8 def prepare_input(batch_size, seq_length): q = torch.randn( (batch_size, num_q_heads, seq_length, hidden_dim), device=GPU_TYPE ) k = torch.randn( (batch_size, num_kv_heads, seq_length, hidden_dim), device=GPU_TYPE, ) pos_ids = torch.arange( seq_length, device=GPU_TYPE, dtype=torch.long ).unsqueeze(0) # dummy cos and sin cos, sin = ( torch.randn((1, seq_length, hidden_dim), device=GPU_TYPE), torch.randn((1, seq_length, hidden_dim), device=GPU_TYPE), ) return q, k, cos, sin, pos_ids def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1) def apply_rotary_pos_emb( q, k, cos, sin, position_ids=None, unsqueeze_dim=1 ): cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed q, k, cos, sin, pos_ids = prepare_input(batch_size, seq_length) compiled_fn = torch.compile(apply_rotary_pos_emb) compiled_out = compiled_fn(q, k, cos, sin, pos_ids) eager_out = apply_rotary_pos_emb(q, k, cos, sin, pos_ids) self.assertEqual(compiled_out, eager_out) # make sure that rope is fused into 1 kernel code = run_and_get_triton_code(compiled_fn, q, k, cos, sin, pos_ids) self.assertEqual(code.count(".run("), 1) def test_numpy_autograd(self): def my_torch(x): y = torch.cat([torch.sin(x) ** 2, torch.max(x)[None]]) return y.sum() def my_np(x): y = np.concatenate([np.sin(x) ** 2, np.max(x)[None]]) return np.sum(y) @torch.compile def wrapper(x): return torch.compiler.wrap_numpy(my_np)(x) @torch.compile def wrapper2(x): x = x.numpy() y = my_np(x) return torch.from_numpy(y) x_np = torch.arange(8, dtype=torch.float32, requires_grad=True) x = torch.arange(8, dtype=torch.float32, requires_grad=True) out_np = wrapper(x_np) out = my_torch(x) self.assertEqual(out, out_np) x2_np = torch.arange(8, dtype=torch.float32, requires_grad=True) out2_np = wrapper2(x2_np) self.assertEqual(out, out2_np) out_np.backward() out.backward() self.assertEqual(x.grad, x_np.grad) out2_np.backward() self.assertEqual(x.grad, x2_np.grad) # Disable constant propagation, so we isolate value range analysis @patch.object(config, "constant_and_index_propagation", False) @patch.object(config, "joint_graph_constant_folding", False) def test_cant_optimize_compute(self): def ones(): return torch.ones([4], device=GPU_TYPE) def suffix(inp): return (inp.to(torch.int64) + 1).to(torch.float64) ten = torch.rand([4], device=GPU_TYPE) for foo in ( lambda x: x + 2147483657, lambda x: torch.where(x < 0, ones(), ones() - 2) * (-(2 ** (40))), lambda x: x + ten, lambda x: x + ten.sum(), ): def fn(): return suffix(foo(ones())) fn_opt = torch.compile(fn, backend="inductor") code = run_and_get_triton_code(fn_opt) # this cannot be optimized away, value too large self.assertTrue("to(tl.int64)" in code) self.assertEqual(fn_opt(), fn()) # Disable constant propagation, so we isolate value range analysis @patch.object(config, "constant_and_index_propagation", False) @patch.object(config, "joint_graph_constant_folding", False) def test_optimize_compute(self): def ones(): return torch.ones([4], device=GPU_TYPE) def suffix(inp): return (inp.to(torch.int64) + 1).to(torch.float64) for foo in ( lambda x: x + 500, lambda x: torch.where(x < 0, ones(), ones() - 2) * (-(2 ** (20))), lambda x: x / 30, ): def fn(): return suffix(foo(ones())) fn_opt = torch.compile(fn, backend="inductor") code = run_and_get_triton_code(fn_opt) # this can be optimized away, value too large self.assertTrue("to(tl.int64)" not in code) self.assertTrue("to(tl.int32)" in code) self.assertEqual(fn_opt(), fn()) # https://github.com/pytorch/pytorch/issues/130335 def test_ctr_not_moved_to_cuda_when_used_in_index_put(self): @torch.compile def f(x, mask): x[:, mask] = -math.inf return x x_tmp = torch.randn(512, 19, device=GPU_TYPE) x = x_tmp.permute(1, 0).view(-1, 128, 4)[:, :, 1:] mask_tmp = torch.ones(128, 3, dtype=torch.int32, device=GPU_TYPE) mask = mask_tmp == mask_tmp f(x, mask) code = run_and_get_triton_code(f, x, mask) # What we are testing here: # inductor has a pass to move tensor constructors on cpu to cuda # (the -math.inf will become a scalar-tensor input to index_put_()) # we are asserting that when inductor allocates this tensor, # it does not move the tensor constructor to cuda and keeps it on CPU. self.assertFalse("empty_strided_cuda(()" in code) # only uncoalesced without this :) @config.patch("triton.coalesce_tiling_analysis", False) @config.patch("triton.use_block_ptr", False) def test_evict_last_non_coalesced_loads(self): @torch.compile def f(a, b): return (a * b).sum(dim=-1) N = 512 inps = ( torch.randn(N, N, N, device=GPU_TYPE).permute(2, 1, 0), torch.randn(N, N, N, device=GPU_TYPE).permute(1, 2, 0), ) code = run_and_get_triton_code(f, *inps) lines = [line for line in code.split("\n") if "tl.load" in line] if config.triton.multi_kernel: # the first 2 lines are generated for the persistent reduction # variant. self.assertExpectedInline( "\n".join(lines), """\ tmp0 = tl.load(in_ptr0 + (x1 + (512*x0) + (262144*r2)), rmask, eviction_policy='evict_last', other=0.0) tmp1 = tl.load(in_ptr1 + (x3 + (262144*r2)), rmask, other=0.0) tmp0 = tl.load(in_ptr0 + (x1 + (512*x0) + (262144*r2)), rmask, eviction_policy='evict_last', other=0.0) tmp1 = tl.load(in_ptr1 + (x3 + (262144*r2)), rmask, eviction_policy='evict_first', other=0.0)""", ) else: self.assertExpectedInline( "\n".join(lines), """\ tmp0 = tl.load(in_ptr0 + (x1 + 512*x0 + 262144*r0_2), r0_mask, eviction_policy='evict_last', other=0.0) tmp1 = tl.load(in_ptr1 + (x3 + 262144*r0_2), r0_mask, eviction_policy='evict_first', other=0.0)""", ) @config.patch("triton.skip_l1_cache", True) def test_skip_l1_cache(self): @torch.compile def f(a, b): return a + b N = 512 inps = (torch.randn(N, device=GPU_TYPE), torch.randn(N, device=GPU_TYPE)) code = run_and_get_triton_code(f, *inps) lines = [line for line in code.split("\n") if "tl.load" in line] self.assertExpectedInline( "\n".join(lines), """\ tmp0 = tl.load(in_ptr0 + (x0), xmask, cache_modifier='.cg') tmp1 = tl.load(in_ptr1 + (x0), xmask, cache_modifier='.cg')""", ) @config.patch("triton.use_block_ptr", True) @config.patch("triton.coalesce_tiling_analysis", False) def test_evict_last_non_coalesced_loads_block_ptr(self): @torch.compile def f(a, b): return (a * b).sum(dim=-1) N = 512 inps = ( torch.randn(N, N, N, device=GPU_TYPE).permute(2, 1, 0), torch.randn(N, N, N, device=GPU_TYPE).permute(1, 2, 0), ) code = run_and_get_triton_code(f, *inps) lines = [line for line in code.split("\n") if "tl.load" in line] if config.triton.multi_kernel: # the first 2 lines are generated for the persistent reduction # variant. self.assertExpectedInline( "\n".join(lines), """\ tmp0 = tl.load(in_ptr0 + (x1 + (512*x0) + (262144*r0_2)), rmask, eviction_policy='evict_last', other=0.0) tmp1 = tl.load(tl.make_block_ptr(in_ptr1, shape=[262144, 512], strides=[1, 262144], block_shape=[XBLOCK, R0_BLOCK], order=[0, 1], offsets=[xoffset, roffset]), boundary_check=[1], padding_option='zero') tmp0 = tl.load(in_ptr0 + (x1 + (512*x0) + (262144*r0_2)), rmask, eviction_policy='evict_last', other=0.0) tmp1 = tl.load(block_ptr0, boundary_check=[1], padding_option='zero', eviction_policy='evict_first')""", # noqa: B950 line too long ) else: self.assertExpectedInline( "\n".join(lines), """\ tmp0 = tl.reshape(tl.load(block_ptr0, boundary_check=[2], padding_option='zero', eviction_policy='evict_last'), [XBLOCK, R0_BLOCK]) tmp1 = tl.load(block_ptr1, boundary_check=[1], padding_option='zero', eviction_policy='evict_first')""", # noqa: B950 line too long ) # Disable index propagation, so the indirect indexing isn't optimized away @patch.object(config, "constant_and_index_propagation", False) def test_computed_indirect_mask(self): def fn(x, n): tmp = torch.arange(n, device=x.device) return x[tmp] + 1 x = torch.randn(8, device=GPU_TYPE) fn_opt = torch.compile(fn) code = run_and_get_triton_code(fn_opt, x, 8) # load should be masked self.assertTrue( "tl.load(in_ptr0 + (tmp0), xmask" in code or "tl.load(in_ptr0 + (tmp0), (xmask).to(tl.int1)" in code ) self.assertEqual(fn(x, 8), fn_opt(x, 8)) @config.patch("triton.prefer_nd_tiling", True) @config.patch("triton.max_tiles", 3) @parametrize( "block_multiple, ynumel_exceed_ygrid_size", [ # xdim has constant mask, ydim does not [True, True], # xdim, ydim both have a constant mask [True, False], # if numel not a block multiple, no constant mask [False, False], # TODO: test zdim too ], ) def test_has_constant_mask(self, block_multiple, ynumel_exceed_ygrid_size): from torch._inductor.runtime.hints import TRITON_MAX_BLOCK from torch._inductor.runtime.runtime_utils import get_max_y_grid shape = [TRITON_MAX_BLOCK["Y"], TRITON_MAX_BLOCK["X"]] if not block_multiple: shape = [s + 1 for s in shape] if ynumel_exceed_ygrid_size: shape[0] = ( shape[0] * (math.ceil(get_max_y_grid() / shape[0])) + shape[0] ) a = torch.zeros(shape, device=GPU_TYPE, dtype=torch.bool) b = torch.zeros((shape[0], 1), device=GPU_TYPE, dtype=torch.bool) opt_fn = torch.compile(torch.add) code = run_and_get_triton_code(opt_fn, a, b) if block_multiple: self.assertTrue("xmask = tl.full" in code) if ynumel_exceed_ygrid_size: self.assertTrue("ymask = yindex < ynumel" in code) else: self.assertTrue("ymask = tl.full" in code) else: self.assertTrue("ymask = yindex < ynumel" in code) self.assertTrue("xmask = xindex < xnumel" in code) @config.patch("triton.native_matmul", False) def test_kernel_names_descriptive(self): @torch.compile(backend="inductor") def fn1(x): return x.cos().sin() @torch.compile(backend="inductor") def fn2(x): x = torch.mm(x, x) x = torch.softmax(x, dim=1) return x mod = nn.Sequential( nn.Linear(4, 4), nn.LayerNorm(4), nn.ReLU(), ).to(device=GPU_TYPE) @torch.compile(backend="inductor") def fn3(x): return mod(x) func_and_kernel_aten = [ (fn1, "triton_poi_fused_cos_sin", (torch.randn(8, device=GPU_TYPE),)), ( fn2, "triton_poi_fused__softmax", (torch.randn(4, 4, device=GPU_TYPE),), ), ( fn3, "triton_poi_fused_native_layer_norm_relu", (torch.randn(4, 4, device=GPU_TYPE),), ), ] func_and_kernel_torch = [ (fn1, "triton_poi_fused_cos_sin", (torch.randn(8, device=GPU_TYPE),)), ( fn2, "triton_poi_fused_softmax", (torch.randn(4, 4, device=GPU_TYPE),), ), ( fn3, "triton_poi_fused_LayerNorm_ReLU", (torch.randn(4, 4, device=GPU_TYPE),), ), ] def test_funcs(func_and_kernel): with torch.no_grad(): for fn, kernel_name, inps in func_and_kernel: code = run_and_get_triton_code(fn, *inps) if kernel_name not in code: print(code) self.assertTrue(kernel_name in code) test_funcs(func_and_kernel_aten) patch.object(config.triton, "descriptive_names", "torch")(test_funcs)( func_and_kernel_torch ) @patch.object(config, "profile_bandwidth", True) def test_bandwidth_profiler(self): @torch.compile(backend="inductor") def fn(x): x = x.cos() x = x.cos() x = torch.mm(x, x) x = x.sin() x = x.relu() return x inp = torch.randn(4, 4, device=GPU_TYPE) code = run_and_get_triton_code(fn, inp) fn(inp) self.assertTrue("start_graph" in code) self.assertTrue("end_graph" in code) def test_comment_graph_fragment(self): @torch.compile(backend="inductor") def fn(x): x = x.sin() x = x.relu() return x inp = torch.randn(4, 4, device=GPU_TYPE) code = run_and_get_triton_code(fn, inp) fn(inp) if config.cpp_wrapper: self.assertTrue("fused_relu_sin" in code) else: self.assertTrue("Graph fragment" in code) self.assertTrue( f'%sin : Tensor "f32[4, 4][4, 1]{GPU_TYPE}:0"[num_users=1] = call_function[target=torch.ops.aten.sin.default]' in code ) self.assertTrue( f'%relu : Tensor "f32[4, 4][4, 1]{GPU_TYPE}:0"[num_users=1] = call_function[target=torch.ops.aten.relu.default]' in code ) def test_split_op_with_sym(self): def fn(x: torch.Tensor) -> torch.Tensor: # split(tensor, sympy.Integer), split(tensor, sympy.Expr) return torch.split(x, x.shape[0]), torch.split(x, x.shape[0] // 2) for dynamic_shapes in [True, False]: with torch._dynamo.config.patch(dynamic_shapes=dynamic_shapes): torch._dynamo.reset() fn_opt = torch.compile( fn, backend="inductor", dynamic=dynamic_shapes ) inps = torch.randn([5, 5]) fn_opt(inps) @skipIfRocm @unittest.skipIf(IS_FBCODE, "fbcode system python does not provide torch") def test_indirect_device_assert(self): dir_path = os.path.dirname(os.path.realpath(__file__)) test_path = os.path.join(dir_path, "indirect_assert_helper.py") fns = ("first_arg", "store", "second_arg", "same_pm_one", "same_pp_one") def test(fn, ndims, dyn_shape, one_size=False): proc = subprocess.Popen( [ sys.executable, test_path, fn, str(ndims), str(dyn_shape), str(one_size), ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={**os.environ, "MKL_THREADING_LAYER": "GNU"}, ) stderr = proc.communicate()[1] self.assertTrue( any( "out of bounds" in err.decode("utf-8") for err in stderr.splitlines() ), f"{fn}, {ndims}, {dyn_shape}, {one_size}", ) for fn, ndims, dyn_shape in itertools.product(fns, (2, 3), (True, False)): test(fn, ndims, dyn_shape) test("first_arg", 2, False, True) for fn, dyn_shape in itertools.product( ("upper1", "upper2", "lower1", "lower2"), (True, False) ): test(fn, 2, dyn_shape) @patch("torch._inductor.config.comment_origin", True) @patch("torch._functorch.config.max_dist_from_bw", 0) def test_inductor_sequence_nr(self): class Model(torch.nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = torch.nn.Conv2d( in_channels=16, out_channels=16, kernel_size=(1, 1), stride=1, padding="same", bias=True, ) self.bn1 = torch.nn.BatchNorm2d(num_features=16) self.relu1 = torch.nn.ReLU() self.loss_fn = torch.nn.L1Loss() def forward(self, x, target): y = x x = self.conv1(x) x = self.bn1(x) x = self.relu1(x) x = x + y x = torch.flatten(x) output = self.loss_fn(x, target) return (output,) def get_triton_codegen(optimized_module, args): def run_with_backward(): result = optimized_module(*args) result[0].backward() return result res, (fwd_code, bwd_code) = run_and_get_code(run_with_backward) return fwd_code, bwd_code x = torch.rand(100, 16, 32, 32, requires_grad=True, device=GPU_TYPE) target = torch.rand(1, device=GPU_TYPE) args = [x, target] model = Model().to(device=GPU_TYPE) opt_model = torch.compile(model) fwd_code, bwd_code = get_triton_codegen(opt_model, args) bwd_seq_nr_set = set() fwd_seq_nr_set = set() for idx, code in enumerate([fwd_code, bwd_code]): seq_nr_set = bwd_seq_nr_set if idx > 0 else fwd_seq_nr_set prefix = "BWD" if idx > 0 else "FWD" for line in code.split("\n"): if "seq_nr" in line: res = re.search(r"seq_nr:(\d+)", line) if res: seq_nr_set.add(int(res.group(1))) self.assertTrue(bwd_seq_nr_set.issubset(fwd_seq_nr_set)) @config.patch( { "coordinate_descent_tuning": True, "triton.unique_kernel_names": True, "benchmark_kernel": True, } ) @skipIfRocm @expectedFailureXPU @unittest.skipIf( torch.cuda.is_available() and torch.cuda.get_device_capability() < (9, 0), "Triton does not support fp8 on A100", ) def test_red_followed_by_transposed_pointwise(self): bs = 26624 dim = 1024 @torch.compile(dynamic=False) def f(in1, in2, a, b, scale_a, scale_b): out = torch.nn.functional.silu(in1) * in2 out_row = (out / out.amax(dim=1, keepdim=True)).to(torch.float8_e4m3fn) out_col = (out / out.amax(dim=0, keepdim=True)).to(torch.float8_e4m3fn) # setup strides for _scaled_mm out_row = out_row.contiguous() out_col = out_col.t().contiguous().t() return ( torch._scaled_mm( out_row, a, scale_a, scale_b, out_dtype=torch.bfloat16 ), torch._scaled_mm( b, out_col, scale_a, scale_b, out_dtype=torch.bfloat16 ), ) in1 = torch.randn((bs, dim), dtype=torch.bfloat16, device=GPU_TYPE) in2 = torch.randn((bs, dim), dtype=torch.bfloat16, device=GPU_TYPE) a = ( torch.randn((dim, dim), dtype=torch.bfloat16, device=GPU_TYPE) .t() .to(torch.float8_e4m3fn) ) b = torch.randn((dim, bs), dtype=torch.bfloat16, device=GPU_TYPE).to( torch.float8_e4m3fn ) # Scales scale_a = torch.tensor(1.0, device=GPU_TYPE) scale_b = torch.tensor(1.0, device=GPU_TYPE) # warmup _, (wrapper,) = run_and_get_code(f, in1, in2, a, b, scale_a, scale_b) # Previously indcutor decide reduction hint for a reduction kernel without considering # the pointwise nodes. That will cause the third reduction kernel in this wrapper to be a # persistent inner reduction and cause bad perf. # # We fix that by making the third reduction a non-persistent reduction # and improve the perf by 4.14x (451us -> 109us) self.assertEqual(3, wrapper.count("def triton_red_")) self.assertEqual(0, wrapper.count("def triton_per_")) if DO_PERF_TEST: with torch.profiler.profile( activities=[torch.profiler.ProfilerActivity.CUDA] ) as p: for _ in range(1000): f(in1, in2, a, b, scale_a, scale_b) print(p.key_averages().table(max_name_column_width=200)) def test_non_blocking_copy_codegen(self): # Checks non_blocking arg is present in codegen # (see https://github.com/pytorch/pytorch/issues/136260) def fn(x): return x.to(device=self.device, non_blocking=True) inp = torch.randn(3, 4) _, (code,) = run_and_get_code(torch.compile(fn), inp) if config.cpp_wrapper: # cpp_wrapper passes "True" as "1" in this case, so check it more # explicitly. FileCheck().check("aoti_torch_copy_").check_same("1)").run(code) else: FileCheck().check("copy_").check_same("True").run(code) def test_layer_norm_inplaces_after_matmul(self): # https://github.com/pytorch/pytorch/issues/132826 batch_size = 32 seq_length = 50 hidden_size = 768 layer_norm = torch.nn.LayerNorm(hidden_size, device=GPU_TYPE) def fn(inp, weight): matmul_output = inp @ weight final_output = layer_norm(matmul_output) return final_output inps = [ torch.randn(batch_size, seq_length, hidden_size, device=GPU_TYPE), torch.randn(hidden_size, hidden_size, device=GPU_TYPE), ] fn_opt = torch.compile(fn) code = run_and_get_triton_code(fn_opt, *inps) self.assertTrue(len(re.findall(r"in_out_ptr\d+", code)) > 0) self.assertEqual(fn_opt(*inps), fn(*inps)) @torch._functorch.config.patch("donated_buffer", True) # The inplace updating does not happen after we fused the # layernorm backward @torch._inductor.config.patch("triton.mix_order_reduction", False) def test_donated_buffer_inplace(self): batch_size = 32 seq_length = 50 hidden_size = 256 inp = torch.randn( batch_size, seq_length, hidden_size, requires_grad=True, device=self.device, ) weight = torch.randn( hidden_size, hidden_size, requires_grad=True, device=self.device ) layer_norm = torch.nn.LayerNorm(hidden_size, device=self.device) def fn(inp, weight): matmul_output = inp @ weight final_output = layer_norm(matmul_output) return final_output fn_opt = torch.compile(fn) def wrapper(inp, weight): return fn_opt(inp, weight).sum().backward() _, code = run_and_get_code(wrapper, inp, weight) self.assertTrue("in_out_ptr" in code[1]) @torch._functorch.config.patch("donated_buffer", True) @torch._inductor.config.patch("force_shape_pad", True) def test_donated_buffer_inplace_gpt(self): # model implementation from llm.c: # https://github.com/karpathy/llm.c/blob/master/train_gpt2.py class NewGELU(nn.Module): def forward(self, input): return ( 0.5 * input * ( 1.0 + torch.tanh( math.sqrt(2.0 / math.pi) * (input + 0.044715 * torch.pow(input, 3.0)) ) ) ) class CausalSelfAttention(nn.Module): def __init__(self, config): super().__init__() assert config.n_embd % config.n_head == 0 # key, query, value projections for all heads, but in a batch self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd) # output projection self.c_proj = nn.Linear(config.n_embd, config.n_embd) self.c_proj.LLMC_RESIDUAL_SCALE_FLAG = 1 # regularization self.n_head = config.n_head self.n_embd = config.n_embd # not really a 'bias', more of a mask, but following the OpenAI/HF naming though self.register_buffer( "bias", torch.tril( torch.ones(config.block_size, config.block_size) ).view(1, 1, config.block_size, config.block_size), ) def forward(self, x): ( B, T, C, ) = x.size() # batch size, sequence length, embedding dimensionality (n_embd) # calculate query, key, values for all heads in batch and move head forward to be the batch dim qkv = self.c_attn(x) q, k, v = qkv.split(self.n_embd, dim=2) k = k.view(B, T, self.n_head, C // self.n_head).transpose( 1, 2 ) # (B, nh, T, hs) q = q.view(B, T, self.n_head, C // self.n_head).transpose( 1, 2 ) # (B, nh, T, hs) v = v.view(B, T, self.n_head, C // self.n_head).transpose( 1, 2 ) # (B, nh, T, hs) y = F.scaled_dot_product_attention(q, k, v, is_causal=True) y = ( y.transpose(1, 2).contiguous().view(B, T, C) ) # re-assemble all head outputs side by side # output projection y = self.c_proj(y) return y class MLP(nn.Module): def __init__(self, config): super().__init__() self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd) self.gelu = NewGELU() self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd) self.c_proj.LLMC_RESIDUAL_SCALE_FLAG = 1 def forward(self, x): x = self.c_fc(x) x = self.gelu(x) x = self.c_proj(x) return x class Block(nn.Module): def __init__(self, config): super().__init__() self.ln_1 = nn.LayerNorm(config.n_embd) self.attn = CausalSelfAttention(config) self.ln_2 = nn.LayerNorm(config.n_embd) self.mlp = MLP(config) def forward(self, x): x = x + self.attn(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return x class GPTConfig: block_size: int = 1024 vocab_size: int = 50257 n_layer: int = 1 n_head: int = 12 n_embd: int = 768 class GPT(nn.Module): def __init__(self, config): super().__init__() self.config = config self.transformer = nn.ModuleDict( dict( wte=nn.Embedding(config.vocab_size, config.n_embd), wpe=nn.Embedding(config.block_size, config.n_embd), h=nn.ModuleList( [Block(config) for _ in range(config.n_layer)] ), ln_f=nn.LayerNorm(config.n_embd), ) ) self.lm_head = nn.Linear( config.n_embd, config.vocab_size, bias=False ) self.lm_head.LLMC_SKIP_INIT = ( 1 # don't init this one, we will tie weights ) self.transformer.wte.weight = ( self.lm_head.weight ) # https://paperswithcode.com/method/weight-tying def forward(self, idx, targets): device = idx.device b, t = idx.size() assert t <= self.config.block_size, ( f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}" ) pos = torch.arange( 0, t, dtype=torch.long, device=device ) # shape (t) # forward the GPT model itself tok_emb = self.transformer.wte( idx ) # token embeddings of shape (b, t, n_embd) pos_emb = self.transformer.wpe( pos ) # position embeddings of shape (t, n_embd) x = tok_emb + pos_emb for block in self.transformer.h: x = block(x) x = self.transformer.ln_f(x) logits = self.lm_head(x) loss = F.cross_entropy( logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1, ) return loss B, T = 1, 1024 ctx = torch.amp.autocast(device_type=GPU_TYPE, dtype=torch.bfloat16) model = GPT(GPTConfig()) model.train() model.to(GPU_TYPE) model = torch.compile(model) x = torch.randint(0, 50257, (B, T), dtype=torch.int64, device=GPU_TYPE) y = torch.randint(0, 50257, (B, T), dtype=torch.int64, device=GPU_TYPE) def wrapper(x, y): with ctx: loss = model(x, y) loss.backward() _, code = run_and_get_code(wrapper, x, y) # The cpp_wrapper code is significantly more complex, so skip checking for exact # code lines. if not config.cpp_wrapper: FileCheck().check_regex( r"reinterpret_tensor\(.*, \(1024, 50257\).*# reuse" ).run(code[1]) @unittest.skipIf( not triton_version_uses_attrs_dict(), "Test only applies to newer triton versions", ) def test_triton_attrs_dict_constexpr_signature(self): def fn(x): return x.sin() fn_c = torch.compile(fn) x = torch.rand(16, device=GPU_TYPE) _, code = run_and_get_code(fn_c, x) FileCheck().check("triton_meta").check("'signature':").check( "'XBLOCK': 'constexpr'" ).run(code[0]) @unittest.skipIf(TEST_WITH_ROCM or not IS_SM90, "no scaled_grouped_mm support") def test_respect_scaled_grouped_mm_layout_tag(self): # scaled_grouped_mm needs `mat2` to be column-major M, K, N = 128, 64, 32 # K and N must be divisible by 16 num_groups = 2 E = num_groups # B_t batch size must match number of groups group_size = M // num_groups A = torch.randn( M, K, dtype=torch.bfloat16, device=GPU_TYPE ) # Row-major by default # Create B_t with proper column-major layout B_t_transposed = torch.randn( E, N, K, dtype=torch.bfloat16, device=GPU_TYPE ).contiguous() B_t = B_t_transposed.transpose(-2, -1) # (E, K, N) B_t = B_t.transpose(-2, -1).contiguous().transpose(-2, -1) # Verify column-major layout def _is_column_major(x: torch.Tensor) -> bool: """Check if tensor is column-major (stride(-2) == 1 and stride(-1) > 1)""" assert x.ndim == 2 or x.ndim == 3, "input tensor must be 2D or 3D" return x.stride(-2) == 1 and x.stride(-1) > 1 self.assertTrue(_is_column_major(B_t)) offs = torch.tensor([group_size, M], dtype=torch.int32, device=GPU_TYPE) out_dtype = torch.bfloat16 @torch.compile def fn(): A_scales = torch.ones(M, dtype=torch.float32, device=GPU_TYPE) A_scaled = A.to(torch.float32) * A_scales.unsqueeze(-1) A_fp8_row_major = A_scaled.to(torch.float8_e4m3fn) B_t_scales = torch.ones(E, N, dtype=torch.float32, device=GPU_TYPE) B_t_scaled = B_t.to(torch.float32) * B_t_scales.unsqueeze(1) B_t_fp8_col_major = B_t_scaled.to(torch.float8_e4m3fn) A_scales_reciprocal = A_scales.reciprocal() B_t_scales_reciprocal = B_t_scales.reciprocal() return torch.ops.aten._scaled_grouped_mm( A_fp8_row_major, B_t_fp8_col_major, A_scales_reciprocal, B_t_scales_reciprocal, offs, out_dtype=out_dtype, use_fast_accum=True, ) fn() @config.patch(implicit_fallbacks=True) @torch._inductor.config.patch("graph_partition", True) def test_graph_partition_default_device_context(self): @torch.library.custom_op( "mylib::cg_unsafe_op", mutates_args=[], schema="(Tensor x) -> Tensor", device_types=GPU_TYPE, tags=(torch._C.Tag.cudagraph_unsafe,), ) def cg_unsafe_op(x) -> torch.Tensor: return x + 1 @cg_unsafe_op.register_fake def _(x) -> torch.Tensor: return torch.empty_like(x) def f(x): x += 1 y = cg_unsafe_op(x) y += 1 return y f = torch.compile(f, mode="reduce-overhead") inp = torch.randn(2, device=GPU_TYPE) _, (code,) = run_and_get_code(f, inp) if config.cpp_wrapper: FileCheck().check_count( "AOTICudaGuard device_guard(0)", 1, exactly=True ).run(code) else: FileCheck().check_count( f"with torch.{GPU_TYPE}._DeviceGuard(0)", 1, exactly=True ).run(code) @skipCUDAIf( not SM90OrLater, "uses bfloat16 atomic add instrs which requires SM >= 90" ) def test_bf16_atomic_add(self): def fn(output, indices, values): output.index_put_([indices], values, accumulate=True) return output indices = torch.tensor([0, 1], device=GPU_TYPE) values = torch.randn(2, 768, dtype=torch.bfloat16, device=GPU_TYPE) output = torch.zeros(512, 768, dtype=torch.bfloat16, device=GPU_TYPE) result, code = run_and_get_code(torch.compile(fn), output, indices, values) self.assertTrue( "tl.atomic_add" in code[0], "bf16 should generate tl.atomic_add", ) expected = torch.zeros(512, 768, dtype=torch.bfloat16, device=GPU_TYPE) torch.testing.assert_close(result, fn(expected, indices, values)) class RNNTest(TestCase): device_type = GPU_TYPE class Model(torch.nn.Module): def __init__(self) -> None: super().__init__() self.gru = torch.nn.GRU(16, 16, batch_first=True) def forward(self, x): return self.gru(x) def test_rnn_compile_safe(self): device = torch.device(GPU_TYPE) model = RNNTest.Model().to(device) model = torch.compile(model, backend="inductor") x = torch.rand(1024, 20, 16).to(device) model(x) class NanCheckerTest(TestCase): @config.patch("nan_asserts", True) def test_nan_checker_pass(self): def f(x): return torch.softmax(x, dim=-1) x = torch.randn(2, 1024, device=GPU_TYPE) ref = f(x) actual, code = run_and_get_code(torch.compile(f), x) self.assertTrue(torch.allclose(ref, actual)) code = code[0] if config.cpp_wrapper: self.assertIn("aoti_torch_check_inf_and_nan", code) else: self.assertIn("# make sure graph inputs are not nan/inf", code) self.assertRegex(code, r"return_vars = (.*)") self.assertIn("for var in return_vars:", code) self.assertIn("if isinstance(var, torch.Tensor):", code) self.assertRegex(code, r"assert not .*\.isnan\(\)\.any\(\).item\(\)") self.assertRegex(code, r"assert not .*\.isinf\(\)\.any\(\).item\(\)") @config.patch("nan_asserts", True) def test_nan_checker_fail(self): def f(x): return torch.softmax(x, dim=-1) x = torch.randn(2, 1024, device=GPU_TYPE) x[0, 0] = float("nan") with self.assertRaises( AssertionError if not config.cpp_wrapper else RuntimeError ): torch.compile(f)(x) if RUN_CPU: class TestFull(TestCase): def test_full_dtype(self): pytypes = ( bool, int, float, # TODO: Triton's JITFunction._type_of has no support for complex # complex, ) dtypes = ( torch.bool, torch.int32, torch.int64, torch.float32, torch.float64, None, # torch.complex64, # torch.complex128, ) def fn(pytype, dtype): if pytype is bool: fill_value = True elif pytype is int: fill_value = 42 elif pytype is float: fill_value = 42.0 else: raise AssertionError(f"Unexpected Python type: {pytype}") return torch.full( (4, 6), fill_value, dtype=dtype, device=torch.device("cpu") ) fn_opt = torch.compile(fn, backend="inductor") for pytype, dtype in itertools.product(pytypes, dtypes): with enable_python_dispatcher(): with torch.no_grad(): ret_opt = fn_opt(pytype, dtype) self.assertEqual(ret_opt, fn(pytype, dtype)) def _strip_tmp_path(code: str) -> str: """ Canonicalize things that look like a tmp path so they can be compared. """ return re.sub('#include ".*?"', '#include "<tmppath>"', code) def _run_and_get_stripped_kernels( fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs ) -> tuple[_T, list[str]]: result, codes = run_and_get_kernels(fn, *args, **kwargs) return result, [_strip_tmp_path(code) for code in codes] if __name__ == "__main__": from torch._inductor.test_case import run_tests if RUN_CPU or RUN_GPU: run_tests(needs="filelock")
TestFailure
python
great-expectations__great_expectations
great_expectations/datasource/fluent/pandas_azure_blob_storage_datasource.py
{ "start": 1108, "end": 1199 }
class ____(PandasDatasourceError): pass @public_api
PandasAzureBlobStorageDatasourceError
python
numba__numba
numba/tests/test_object_mode.py
{ "start": 607, "end": 3257 }
class ____(TestCase): def test_complex_constant(self): pyfunc = complex_constant cfunc = jit((), forceobj=True)(pyfunc) self.assertPreciseEqual(pyfunc(12), cfunc(12)) def test_long_constant(self): pyfunc = long_constant cfunc = jit((), forceobj=True)(pyfunc) self.assertPreciseEqual(pyfunc(12), cfunc(12)) def test_loop_nest(self): """ Test bug that decref the iterator early. If the bug occurs, a segfault should occur """ pyfunc = loop_nest_3 cfunc = jit((), forceobj=True)(pyfunc) self.assertEqual(pyfunc(5, 5), cfunc(5, 5)) def bm_pyfunc(): pyfunc(5, 5) def bm_cfunc(): cfunc(5, 5) utils.benchmark(bm_pyfunc) utils.benchmark(bm_cfunc) def test_array_of_object(self): cfunc = jit(forceobj=True)(array_of_object) objarr = np.array([object()] * 10) self.assertIs(cfunc(objarr), objarr) def test_sequence_contains(self): """ Test handling of the `in` comparison """ @jit(forceobj=True) def foo(x, y): return x in y self.assertTrue(foo(1, [0, 1])) self.assertTrue(foo(0, [0, 1])) self.assertFalse(foo(2, [0, 1])) with self.assertRaises(TypeError) as raises: foo(None, None) # This tests 'None in None' with the python interpreter. The error # message has changed in 3.14. if PYVERSION in ((3, 14), ): expected_snippet = "is not a container or iterable" elif PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): expected_snippet = "is not iterable" else: raise NotImplementedError(PYVERSION) self.assertIn(expected_snippet, str(raises.exception)) def test_delitem(self): pyfunc = delitem_usecase cfunc = jit((), forceobj=True)(pyfunc) l = [3, 4, 5] cfunc(l) self.assertPreciseEqual(l, []) with self.assertRaises(TypeError): cfunc(42) def test_starargs_non_tuple(self): def consumer(*x): return x @jit(forceobj=True) def foo(x): return consumer(*x) arg = "ijo" got = foo(arg) expect = foo.py_func(arg) self.assertEqual(got, tuple(arg)) self.assertEqual(got, expect) def test_expr_undef(self): @jit(forceobj=True) def foo(): # In Py3.12, this will emit a Expr.undef. return [x for x in (1, 2)] self.assertEqual(foo(), foo.py_func())
TestObjectMode