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 | tensorflow__tensorflow | tensorflow/python/tpu/tpu_test.py | {
"start": 1624,
"end": 3136
} | class ____(test.TestCase):
def testIsInContext(self):
"""Test that control_flow_util can check that we're in a TPU context."""
with ops.Graph().as_default():
z1 = array_ops.identity(1)
pivot = control_flow_ops.no_op()
context = tpu_replication.TPUReplicateContext(
b"context", 1, pivot=pivot)
context.Enter()
z2 = array_ops.identity(1)
context.Exit()
self.assertFalse(control_flow_util.IsInXLAContext(z1.op))
self.assertTrue(control_flow_util.IsInXLAContext(z2.op))
def testHandlesNameCollision(self):
"""Test AddValue handles name collisions for ops from different graphs."""
with ops.Graph().as_default():
z = array_ops.zeros([2, 3], name="a")
assert z.name == "a:0", "Expected: a:0, Found: %s" % z.name
@def_function.function
def f():
pivot = control_flow_ops.no_op()
context = tpu_replication.TPUReplicateContext(
b"context", 1, pivot=pivot)
context.Enter()
array_ops.identity(z) # Capture z.
z1 = array_ops.zeros([3, 2], name="a")
assert z1.name == "a:0", "Expected: a:0, Found: %s" % z1.name
z2 = array_ops.zeros([3, 2], name="a")
# Prior to fixing b/166794533 this would fail with a shape mismatch
# because context.AddValue would have cached `z` by its name which
# collides with z1's name.
result = z1 + z2
context.Exit()
return result
f.get_concrete_function()
| TPUContextTest |
python | Textualize__textual | tests/test_command.py | {
"start": 791,
"end": 1886
} | class ____(App):
"""An app with a modal dialog."""
BINDINGS = [("q", "request_quit", "Quit")]
def __init__(self) -> None:
self.check_quit_called = False
super().__init__()
def get_system_commands(self, screen: Screen) -> Iterable[SystemCommand]:
yield from super().get_system_commands(screen)
yield SystemCommand(
"try a modal quit dialog", "this should work", self.action_request_quit
)
def action_request_quit(self) -> None:
"""Action to display the quit dialog."""
def check_quit(quit: bool | None) -> None:
"""Called when QuitScreen is dismissed."""
self.check_quit_called = True
self.push_screen(QuitScreen(), check_quit)
async def test_command_dismiss():
"""Regression test for https://github.com/Textualize/textual/issues/5512"""
app = ModalApp()
async with app.run_test() as pilot:
await pilot.press("ctrl+p", *"modal quit", "enter")
await pilot.pause()
await pilot.press("enter")
assert app.check_quit_called
| ModalApp |
python | getsentry__sentry | src/sentry/plugins/sentry_urls/apps.py | {
"start": 36,
"end": 250
} | class ____(AppConfig):
name = "sentry.plugins.sentry_urls"
def ready(self) -> None:
from sentry.plugins.base import register
from .models import UrlsPlugin
register(UrlsPlugin)
| Config |
python | pytorch__pytorch | torch/_dynamo/variables/builder.py | {
"start": 8901,
"end": 11782
} | class ____:
source: Source
# TODO: storing a SymInt here but not a FakeTensor is a pretty strange
# thing to do. Probably should have example (which stores an int) and
# fake_example
_example: Union[TensorWeakRef, torch.SymInt]
# When True, this indicates that this GraphArg is a Python quantity (e.g.,
# a float or int) which we pass to the FX graph as a Tensor. This
# controls how we codegen calls into the Dynamo graph: we will call
# torch.as_tensor on the quantity before passing it in.
#
# Note that we typically do not pass dynamic integers as tensors, because
# they will most frequently just be used for size computation. But this
# is a policy decision that we can change our mind on; in particular, when
# an int comes from a random number generator (e.g., random.randint), we
# DO pass it as a tensor.
#
# It's also worth noting that our current tracing rules for
# pass_arg_as_tensor as subtly broken: we just pun the variable as a
# 0d scalar Tensor and pray that the semantics are the same. Which they
# often are, but not necessarily. ezyang(May 2024) plans to fix this
# soon.
pass_arg_as_tensor: bool
fake_tensor: Optional[torch._subclasses.fake_tensor.FakeTensor]
# UnspecializedPythonVariable often masquerades as a tensor.
# We MUST NOT generate shape guard code
# that actually tries to access tensor properties on these values.
# is_tensor lets us tell if this graph arg actually is a tensor
# or not.
is_tensor: bool = True
# Sometimes, the Tensor we pass to example is freshly allocated (smh).
# Then we cannot only keep a weak reference to it. This lets you
# stash a strong reference too.
example_strong_ref: Optional[torch.Tensor] = None
def __setattr__(self, name, value):
# Use object.__setattr__ to bypass Dynamo's STORE_ATTR interception.
# This is needed because when PYTORCH_TEST_WITH_DYNAMO=1, even internal
# GraphArg creation can be traced, and with replay_side_effects=False,
# normal STORE_ATTR bytecode only records mutations without applying them.
object.__setattr__(self, name, value)
@property
def example(self):
if isinstance(self._example, TensorWeakRef):
r = self._example()
assert r is not None
return r
else:
return self._example
def __post_init__(self):
if isinstance(self._example, torch.Tensor):
self._example = TensorWeakRef(self._example)
assert is_fake(self.fake_tensor)
def reconstruct(self, codegen: "PyCodegen"):
codegen(self.source)
def erase(self):
self._example = None
self.example_strong_ref = None
def __eq__(self, other):
return self.source.name() == other.source.name()
| GraphArg |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 94407,
"end": 94525
} | class ____(BaseModel, extra="forbid"):
searches: List["QueryRequest"] = Field(..., description="")
| QueryRequestBatch |
python | pytorch__pytorch | torch/_export/serde/serialize.py | {
"start": 76861,
"end": 79442
} | class ____(metaclass=Final):
def __init__(
self,
opset_version: Optional[dict[str, int]] = None,
pickle_protocol: int = DEFAULT_PICKLE_PROTOCOL,
):
self.opset_version: dict[str, int] = {}
if opset_version:
self.opset_version.update(opset_version)
if "aten" not in self.opset_version:
self.opset_version["aten"] = torch._C._get_max_operator_version()
self.pickle_protocol = pickle_protocol
def serialize(self, exported_program: ep.ExportedProgram) -> _SerializedProgram:
"""
Args:
exported_program: Exported Program to serialize
"""
exported_program.validate()
gm_serializer = GraphModuleSerializer(
exported_program.graph_signature, exported_program.module_call_graph
)
serialized_graph_module = gm_serializer.serialize(exported_program.graph_module)
serialized_range_constraints = serialize_range_constraints(
exported_program.range_constraints
)
# TODO: Directly serialize exported_program.constants once
# CustomClassHolders get stored in the ExportedProgram rather than in
# the graph
constants: dict[str, Any] = gm_serializer.custom_objs.copy()
for n, t in exported_program.constants.items():
assert n not in constants
constants[n] = t
serialized_ep = ExportedProgram(
graph_module=serialized_graph_module,
opset_version=self.opset_version,
range_constraints=serialized_range_constraints,
schema_version=SchemaVersion(
major=SCHEMA_VERSION[0],
minor=SCHEMA_VERSION[1],
),
verifiers=[v.dialect for v in exported_program.verifiers],
torch_version=torch.__version__,
guards_code=exported_program._guards_code,
)
# Test canonical form is well defined.
canonicalize(serialized_ep, set(constants.keys()))
# Proxy cannot be dumped, so we remove them.
new_state_dict = remove_proxy_from_state_dict(
exported_program.state_dict, in_place=False
)
return _SerializedProgram(
serialized_ep,
serialize_torch_artifact(new_state_dict, self.pickle_protocol),
serialize_torch_artifact(constants, self.pickle_protocol),
serialize_torch_artifact(
exported_program.example_inputs, self.pickle_protocol
),
)
@final
| ExportedProgramSerializer |
python | pytorch__pytorch | torch/testing/_internal/distributed/rpc/examples/parameter_server_test.py | {
"start": 2350,
"end": 3764
} | class ____:
def __init__(self, ps_rref):
self.ps_rref = ps_rref
self.loss_fn = nn.L1Loss()
def get_next_batch(self):
for _ in range(num_batches):
inputs = torch.randn(batch_size, in_features)
labels = torch.zeros(batch_size, out_features)
yield inputs, labels
def train(self):
name = rpc.get_worker_info().name
m = self.ps_rref.rpc_sync().get_model()
for inputs, labels in self.get_next_batch():
timed_log(f"{name} processing one batch")
self.loss_fn(m(inputs), labels).backward()
timed_log(f"{name} reporting grads")
m = rpc.rpc_sync(
self.ps_rref.owner(),
BatchUpdateParameterServer.update_and_fetch_model,
args=(self.ps_rref, [p.grad for p in m.cpu().parameters()]),
)
timed_log(f"{name} got updated model")
def run_trainer(ps_rref):
trainer = Trainer(ps_rref)
trainer.train()
def run_ps(trainers):
timed_log("Start training")
start = perf_counter()
ps_rref = rpc.RRef(BatchUpdateParameterServer(len(trainers)))
futs = [
rpc.rpc_async(trainer, run_trainer, args=(ps_rref,)) for trainer in trainers
]
torch.futures.wait_all(futs)
stop = perf_counter()
timed_log("Finish training")
timed_log(f"Time spent training: {stop - start}s")
| Trainer |
python | PyCQA__pylint | tests/functional/r/regression/regression_infer_call_result_3690.py | {
"start": 107,
"end": 209
} | class ____:
@property
@classmethod
def func(cls):
pass
if Class.func:
pass
| Class |
python | python__mypy | mypy/types.py | {
"start": 21960,
"end": 25875
} | class ____(TypeVarLikeType):
"""Type that refers to a type variable."""
__slots__ = ("values", "variance")
values: list[Type] # Value restriction, empty list if no restriction
variance: int
def __init__(
self,
name: str,
fullname: str,
id: TypeVarId,
values: list[Type],
upper_bound: Type,
default: Type,
variance: int = INVARIANT,
line: int = -1,
column: int = -1,
) -> None:
super().__init__(name, fullname, id, upper_bound, default, line, column)
assert values is not None, "No restrictions must be represented by empty list"
self.values = values
self.variance = variance
def copy_modified(
self,
*,
values: Bogus[list[Type]] = _dummy,
upper_bound: Bogus[Type] = _dummy,
default: Bogus[Type] = _dummy,
id: Bogus[TypeVarId] = _dummy,
line: int = _dummy_int,
column: int = _dummy_int,
**kwargs: Any,
) -> TypeVarType:
return TypeVarType(
name=self.name,
fullname=self.fullname,
id=self.id if id is _dummy else id,
values=self.values if values is _dummy else values,
upper_bound=self.upper_bound if upper_bound is _dummy else upper_bound,
default=self.default if default is _dummy else default,
variance=self.variance,
line=self.line if line == _dummy_int else line,
column=self.column if column == _dummy_int else column,
)
def accept(self, visitor: TypeVisitor[T]) -> T:
return visitor.visit_type_var(self)
def __hash__(self) -> int:
return hash((self.id, self.upper_bound, tuple(self.values)))
def __eq__(self, other: object) -> bool:
if not isinstance(other, TypeVarType):
return NotImplemented
return (
self.id == other.id
and self.upper_bound == other.upper_bound
and self.values == other.values
)
def serialize(self) -> JsonDict:
assert not self.id.is_meta_var()
return {
".class": "TypeVarType",
"name": self.name,
"fullname": self.fullname,
"id": self.id.raw_id,
"namespace": self.id.namespace,
"values": [v.serialize() for v in self.values],
"upper_bound": self.upper_bound.serialize(),
"default": self.default.serialize(),
"variance": self.variance,
}
@classmethod
def deserialize(cls, data: JsonDict) -> TypeVarType:
assert data[".class"] == "TypeVarType"
return TypeVarType(
name=data["name"],
fullname=data["fullname"],
id=TypeVarId(data["id"], namespace=data["namespace"]),
values=[deserialize_type(v) for v in data["values"]],
upper_bound=deserialize_type(data["upper_bound"]),
default=deserialize_type(data["default"]),
variance=data["variance"],
)
def write(self, data: WriteBuffer) -> None:
write_tag(data, TYPE_VAR_TYPE)
write_str(data, self.name)
write_str(data, self.fullname)
write_int(data, self.id.raw_id)
write_str(data, self.id.namespace)
write_type_list(data, self.values)
self.upper_bound.write(data)
self.default.write(data)
write_int(data, self.variance)
write_tag(data, END_TAG)
@classmethod
def read(cls, data: ReadBuffer) -> TypeVarType:
ret = TypeVarType(
read_str(data),
read_str(data),
TypeVarId(read_int(data), namespace=read_str(data)),
read_type_list(data),
read_type(data),
read_type(data),
read_int(data),
)
assert read_tag(data) == END_TAG
return ret
| TypeVarType |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-wordlift/llama_index/vector_stores/wordlift/base.py | {
"start": 1801,
"end": 8877
} | class ____(BasePydanticVectorStore):
stores_text: bool = True
_account: Optional[AccountInfo] = PrivateAttr(default=None)
_configuration: Configuration = PrivateAttr()
_fields: Optional[List[str]] = PrivateAttr()
def __init__(
self,
key: Optional[str] = None,
configuration: Optional[Configuration] = None,
fields: Optional[List[str]] = None,
):
super().__init__(use_async=True)
try:
nest_asyncio.apply()
except ValueError:
# We may not be in asyncio
pass
if configuration is None:
self._configuration = _make_configuration(key=key)
else:
self._configuration = configuration
if fields is None:
self._fields = ["schema:url", "schema:name"]
else:
self._fields = fields
@property
def account(self) -> AccountInfo:
if self._account is None:
self._account = asyncio.get_event_loop().run_until_complete(
self._get_account()
)
return self._account
async def _get_account(self):
"""
Get the account data for the provided key.
:return:
"""
async with wordlift_client.ApiClient(self._configuration) as api_client:
api_instance = wordlift_client.AccountApi(api_client)
try:
return await api_instance.get_me()
except ApiException as e:
raise RuntimeError(
"Failed to get account info, check the provided key"
) from e
@property
def client(self) -> Any:
return self.account
def add(self, nodes: List[BaseNode], **add_kwargs: Any) -> List[str]:
return asyncio.get_event_loop().run_until_complete(
self.async_add(nodes, **add_kwargs)
)
async def async_add(
self,
nodes: List[BaseNode],
**kwargs: Any,
) -> List[str]:
# Empty nodes, return empty list
if not nodes:
return []
log.debug(f"{len(nodes)} node(s) received\n")
requests = []
for node in nodes:
node_dict = node.dict()
# metadata: Dict[str, Any] = node_dict.get("metadata", {})
metadata = _make_metadata_as_node_request_metadata_value(
node_dict.get("metadata", {})
)
# Get or generate an ID
entity_id = metadata.get("entity_id", None)
if entity_id is None:
entity_id = _generate_id(self.account, node.id_)
entry = NodeRequest(
entity_id=entity_id,
node_id=node.node_id,
embeddings=node.get_embedding(),
text=node.get_content(metadata_mode=MetadataMode.NONE) or "",
metadata=metadata,
)
requests.append(entry)
async with wordlift_client.ApiClient(self._configuration) as api_client:
api_instance = wordlift_client.VectorSearchNodesApi(api_client)
try:
await api_instance.update_nodes_collection(node_request=requests)
except ApiException as e:
raise RuntimeError("Error creating entities") from e
return [node.node_id for node in nodes]
def delete(self, ref_doc_id: str, **delete_kwargs: Any) -> None:
return asyncio.get_event_loop().run_until_complete(
self.adelete(ref_doc_id, **delete_kwargs)
)
async def adelete(self, ref_doc_id: str, **delete_kwargs: Any) -> None:
await self.adelete_nodes([ref_doc_id], **delete_kwargs)
def delete_nodes(
self,
node_ids: Optional[List[str]] = None,
filters: Optional[MetadataFilters] = None,
**delete_kwargs: Any,
) -> None:
return asyncio.get_event_loop().run_until_complete(
self.adelete_nodes(node_ids, filters, **delete_kwargs)
)
async def adelete_nodes(
self,
node_ids: Optional[List[str]] = None,
filters: Optional[MetadataFilters] = None,
**delete_kwargs: Any,
) -> None:
# Bail out if the list is not provided.
if node_ids is None:
return
# Create the IDs.
ids = []
for node_id in node_ids:
ids.append(_generate_id(self.account, node_id))
async with wordlift_client.ApiClient(self._configuration) as api_client:
api_instance = wordlift_client.EntitiesApi(api_client)
try:
await api_instance.delete_entities(id=ids)
except ApiException as e:
raise RuntimeError("Error deleting entities") from e
def query(self, query: VectorStoreQuery, **kwargs: Any) -> VectorStoreQueryResult:
return asyncio.get_event_loop().run_until_complete(self.aquery(query, **kwargs))
async def aquery(
self, query: VectorStoreQuery, **kwargs: Any
) -> VectorStoreQueryResult:
filters = MetadataFiltersToFilters.metadata_filters_to_filters(
query.filters if query.filters else []
)
if query.query_str:
request = VectorSearchQueryRequest(
query_string=query.query_str,
similarity_top_k=query.similarity_top_k,
fields=self._fields,
filters=filters,
)
else:
request = VectorSearchQueryRequest(
query_embedding=query.query_embedding,
similarity_top_k=query.similarity_top_k,
fields=self._fields,
filters=filters,
)
async with wordlift_client.ApiClient(self._configuration) as api_client:
api_instance = wordlift_client.VectorSearchQueriesApi(api_client)
try:
page = await api_instance.create_query(
vector_search_query_request=request,
)
except ApiException as e:
log.error(
f"Error querying for entities with the following request: {json.dumps(api_client.sanitize_for_serialization(request))}",
exc_info=True,
)
nodes: List[TextNode] = []
similarities: List[float] = []
ids: List[str] = []
for item in page.items:
metadata = item.metadata if item.metadata else {}
fields = item.fields if item.fields else {}
metadata = {**metadata, **fields}
nodes.append(
TextNode(
text=item.text if item.text else "",
id_=item.node_id if item.node_id else "",
embedding=(item.embeddings if "embeddings" in item else None),
metadata=metadata,
)
)
similarities.append(item.score)
ids.append(item.node_id)
return VectorStoreQueryResult(nodes=nodes, similarities=similarities, ids=ids)
| WordliftVectorStore |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_glue_catalog_partition.py | {
"start": 1130,
"end": 5967
} | class ____:
task_id = "test_glue_catalog_partition_sensor"
@mock_aws
@mock.patch.object(GlueCatalogHook, "check_for_partition")
def test_poke(self, mock_check_for_partition):
mock_check_for_partition.return_value = True
op = GlueCatalogPartitionSensor(task_id=self.task_id, table_name="tbl")
assert op.poke({})
@mock_aws
@mock.patch.object(GlueCatalogHook, "check_for_partition")
def test_poke_false(self, mock_check_for_partition):
mock_check_for_partition.return_value = False
op = GlueCatalogPartitionSensor(task_id=self.task_id, table_name="tbl")
assert not op.poke({})
@mock_aws
@mock.patch.object(GlueCatalogHook, "check_for_partition")
def test_poke_default_args(self, mock_check_for_partition):
table_name = "test_glue_catalog_partition_sensor_tbl"
op = GlueCatalogPartitionSensor(task_id=self.task_id, table_name=table_name)
op.poke({})
assert op.hook.region_name is None
assert op.hook.aws_conn_id == "aws_default"
mock_check_for_partition.assert_called_once_with("default", table_name, "ds='{{ ds }}'")
@mock_aws
@mock.patch.object(GlueCatalogHook, "check_for_partition")
def test_poke_nondefault_args(self, mock_check_for_partition):
table_name = "my_table"
expression = "col=val"
aws_conn_id = "my_aws_conn_id"
region_name = "us-west-2"
database_name = "my_db"
poke_interval = 2
timeout = 3
op = GlueCatalogPartitionSensor(
task_id=self.task_id,
table_name=table_name,
expression=expression,
aws_conn_id=aws_conn_id,
region_name=region_name,
database_name=database_name,
poke_interval=poke_interval,
timeout=timeout,
)
# We're mocking all actual AWS calls and don't need a connection. This
# avoids an Airflow warning about connection cannot be found.
op.hook.get_connection = lambda _: None
op.poke({})
assert op.hook.region_name == region_name
assert op.hook.aws_conn_id == aws_conn_id
assert op.poke_interval == poke_interval
assert op.timeout == timeout
mock_check_for_partition.assert_called_once_with(database_name, table_name, expression)
@mock_aws
@mock.patch.object(GlueCatalogHook, "check_for_partition")
def test_dot_notation(self, mock_check_for_partition):
db_table = "my_db.my_tbl"
op = GlueCatalogPartitionSensor(task_id=self.task_id, table_name=db_table)
op.poke({})
mock_check_for_partition.assert_called_once_with("my_db", "my_tbl", "ds='{{ ds }}'")
def test_deferrable_mode_raises_task_deferred(self):
op = GlueCatalogPartitionSensor(task_id=self.task_id, table_name="tbl", deferrable=True)
with pytest.raises(TaskDeferred):
op.execute({})
def test_execute_complete_fails_if_status_is_not_success(self):
op = GlueCatalogPartitionSensor(task_id=self.task_id, table_name="tbl", deferrable=True)
event = {"status": "FAILED"}
with pytest.raises(AirflowException):
op.execute_complete(context={}, event=event)
def test_execute_complete_succeeds_if_status_is_success(self, caplog):
op = GlueCatalogPartitionSensor(task_id=self.task_id, table_name="tbl", deferrable=True)
event = {"status": "success"}
op.execute_complete(context={}, event=event)
assert "Partition exists in the Glue Catalog" in caplog.messages
def test_fail_execute_complete(self):
op = GlueCatalogPartitionSensor(task_id=self.task_id, table_name="tbl", deferrable=True)
event = {"status": "Failed"}
message = f"Trigger error: event is {event}"
with pytest.raises(AirflowException, match=message):
op.execute_complete(context={}, event=event)
def test_init(self):
default_op_kwargs = {
"task_id": "test_task",
"table_name": "test_table",
}
sensor = GlueCatalogPartitionSensor(**default_op_kwargs)
assert sensor.hook.aws_conn_id == "aws_default"
assert sensor.hook._region_name is None
assert sensor.hook._verify is None
assert sensor.hook._config is None
sensor = GlueCatalogPartitionSensor(
**default_op_kwargs,
aws_conn_id=None,
region_name="eu-west-2",
verify=True,
botocore_config={"read_timeout": 42},
)
assert sensor.hook.aws_conn_id is None
assert sensor.hook._region_name == "eu-west-2"
assert sensor.hook._verify is True
assert sensor.hook._config is not None
assert sensor.hook._config.read_timeout == 42
| TestGlueCatalogPartitionSensor |
python | doocs__leetcode | solution/2100-2199/2172.Maximum AND Sum of Array/Solution.py | {
"start": 0,
"end": 443
} | class ____:
def maximumANDSum(self, nums: List[int], numSlots: int) -> int:
n = len(nums)
m = numSlots << 1
f = [0] * (1 << m)
for i in range(1 << m):
cnt = i.bit_count()
if cnt > n:
continue
for j in range(m):
if i >> j & 1:
f[i] = max(f[i], f[i ^ (1 << j)] + (nums[cnt - 1] & (j // 2 + 1)))
return max(f)
| Solution |
python | getsentry__sentry | src/sentry/relay/types/rule_condition.py | {
"start": 609,
"end": 776
} | class ____(TypedDict):
"""Equality condition"""
op: Literal["eq"]
name: str
value: Value | None
options: NotRequired[EqConditionOptions]
| EqCondition |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-alephalpha/llama_index/embeddings/alephalpha/base.py | {
"start": 718,
"end": 8614
} | class ____(BaseEmbedding):
"""AlephAlphaEmbedding uses the Aleph Alpha API to generate embeddings for text."""
model: str = Field(
default=DEFAULT_ALEPHALPHA_MODEL, description="The Aleph Alpha model to use."
)
token: str = Field(default=None, description="The Aleph Alpha API token.")
representation: Optional[str] = Field(
default=SemanticRepresentation.Query,
description="The representation type to use for generating embeddings.",
)
compress_to_size: Optional[int] = Field(
default=None,
description="The size to compress the embeddings to.",
gt=0,
)
base_url: Optional[str] = Field(
default=DEFAULT_ALEPHALPHA_HOST, description="The hostname of the API base_url."
)
timeout: Optional[float] = Field(
default=None, description="The timeout to use in seconds.", ge=0
)
max_retries: int = Field(
default=10, description="The maximum number of API retries.", ge=0
)
normalize: Optional[bool] = Field(
default=False, description="Return normalized embeddings."
)
hosting: Optional[str] = Field(default=None, description="The hosting to use.")
nice: bool = Field(default=False, description="Whether to be nice to the API.")
verify_ssl: bool = Field(default=True, description="Whether to verify SSL.")
additional_kwargs: Dict[str, Any] = Field(
default_factory=dict, description="Additional kwargs for the Aleph Alpha API."
)
# Instance variables initialized via Pydantic's mechanism
_client: Any = PrivateAttr()
_aclient: Any = PrivateAttr()
def __init__(
self,
model: str = DEFAULT_ALEPHALPHA_MODEL,
token: Optional[str] = None,
representation: Optional[str] = None,
base_url: Optional[str] = DEFAULT_ALEPHALPHA_HOST,
hosting: Optional[str] = None,
timeout: Optional[float] = None,
max_retries: int = 10,
nice: bool = False,
verify_ssl: bool = True,
additional_kwargs: Optional[Dict[str, Any]] = None,
):
"""
A class representation for generating embeddings using the AlephAlpha API.
Args:
token: The token to use for the AlephAlpha API.
model: The model to use for generating embeddings.
base_url: The base URL of the AlephAlpha API.
nice: Whether to use the "nice" mode for the AlephAlpha API.
additional_kwargs: Additional kwargs for the AlephAlpha API.
"""
additional_kwargs = additional_kwargs or {}
super().__init__(
model=model,
representation=representation,
base_url=base_url,
token=token,
nice=nice,
additional_kwargs=additional_kwargs,
)
self.token = get_from_param_or_env("aa_token", token, "AA_TOKEN", "")
if representation is not None and isinstance(representation, str):
try:
representation_enum = SemanticRepresentation[
representation.capitalize()
]
except KeyError:
raise ValueError(
f"{representation} is not a valid representation type. Available types are: {list(SemanticRepresentation.__members__.keys())}"
)
self.representation = representation_enum
else:
self.representation = representation
self._client = None
self._aclient = None
@classmethod
def class_name(cls) -> str:
return "AlephAlphaEmbedding"
def _get_credential_kwargs(self) -> Dict[str, Any]:
return {
"token": self.token,
"host": self.base_url,
"hosting": self.hosting,
"request_timeout_seconds": self.timeout,
"total_retries": self.max_retries,
"nice": self.nice,
"verify_ssl": self.verify_ssl,
}
def _get_client(self) -> Client:
if self._client is None:
self._client = Client(**self._get_credential_kwargs())
return self._client
def _get_aclient(self) -> AsyncClient:
if self._aclient is None:
self._aclient = AsyncClient(**self._get_credential_kwargs())
return self._aclient
def _get_embedding(self, text: str, representation: str) -> List[float]:
"""Embed sentence using AlephAlpha."""
client = self._get_client()
request = SemanticEmbeddingRequest(
prompt=Prompt.from_text(text),
representation=representation or self.representation,
compress_to_size=self.compress_to_size,
normalize=self.normalize,
)
result = client.semantic_embed(request=request, model=self.model)
return result.embedding
async def _aget_embedding(self, text: str, representation: str) -> List[float]:
"""Get embedding async."""
aclient = self._get_aclient()
request = SemanticEmbeddingRequest(
prompt=Prompt.from_text(text),
representation=representation or self.representation,
compress_to_size=self.compress_to_size,
normalize=self.normalize,
)
result = await aclient.semantic_embed(request=request, model=self.model)
return result.embedding
def _get_embeddings(
self, texts: List[str], representation: str
) -> List[List[float]]:
"""Embed sentences using AlephAlpha."""
client = self._get_client()
request = BatchSemanticEmbeddingRequest(
prompts=[Prompt.from_text(text) for text in texts],
representation=representation or self.representation,
compress_to_size=self.compress_to_size,
normalize=self.normalize,
)
result: BatchSemanticEmbeddingResponse = client.batch_semantic_embed(
request=request, model=self.model
)
return result.embeddings
async def _aget_embeddings(
self, texts: List[str], representation: str
) -> List[List[float]]:
"""Get embeddings async."""
aclient = self._get_aclient()
request = BatchSemanticEmbeddingRequest(
prompts=[Prompt.from_text(text) for text in texts],
representation=representation or self.representation,
compress_to_size=self.compress_to_size,
normalize=self.normalize,
)
result: BatchSemanticEmbeddingResponse = await aclient.batch_semantic_embed(
request=request, model=self.model
)
return result.embeddings
def _get_query_embedding(self, query: str) -> List[float]:
"""Get query embedding. For query embeddings, representation='query'."""
return self._get_embedding(query, SemanticRepresentation.Query)
async def _aget_query_embedding(self, query: str) -> List[float]:
"""Get query embedding async. For query embeddings, representation='query'."""
return self._aget_embedding(query, SemanticRepresentation.Query)
def _get_text_embedding(self, text: str) -> List[float]:
"""Get text embedding. For text embeddings, representation='document'."""
return self._get_embedding(text, SemanticRepresentation.Document)
async def _aget_text_embedding(self, text: str) -> List[float]:
"""Get text embedding async."""
return self._aget_embedding(text, SemanticRepresentation.Document)
def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]:
"""Get text embeddings."""
return self._get_embeddings(texts, SemanticRepresentation.Document)
async def _aget_text_embeddings(self, texts: List[str]) -> List[List[float]]:
"""Get text embeddings async."""
return self._aget_embeddings(texts, SemanticRepresentation.Document)
| AlephAlphaEmbedding |
python | PrefectHQ__prefect | src/prefect/logging/formatters.py | {
"start": 2203,
"end": 4167
} | class ____(logging.Formatter):
def __init__(
self,
format: str | None = None,
datefmt: str | None = None,
style: Literal["%", "{", "$"] = "%",
validate: bool = True,
*,
defaults: dict[str, Any] | None = None,
task_run_fmt: str | None = None,
flow_run_fmt: Optional[str] = None,
) -> None:
"""
Implementation of the standard Python formatter with support for multiple
message formats.
"""
# See https://github.com/python/cpython/blob/c8c6113398ee9a7867fe9b08bc539cceb61e2aaa/Lib/logging/__init__.py#L546
# for implementation details
init_kwargs: dict[str, Any] = {}
style_kwargs: dict[str, Any] = {}
# defaults added in 3.10
if sys.version_info >= (3, 10):
init_kwargs["defaults"] = defaults
style_kwargs["defaults"] = defaults
init_kwargs["validate"] = validate
super().__init__(format, datefmt, style, **init_kwargs)
self.flow_run_fmt = flow_run_fmt
self.task_run_fmt = task_run_fmt
# Retrieve the style class from the base class to avoid importing private
# `_STYLES` mapping
style_class = type(self._style)
self._flow_run_style = (
style_class(flow_run_fmt, **style_kwargs) if flow_run_fmt else self._style
)
self._task_run_style = (
style_class(task_run_fmt, **style_kwargs) if task_run_fmt else self._style
)
if validate:
self._flow_run_style.validate()
self._task_run_style.validate()
def formatMessage(self, record: logging.LogRecord) -> str:
if record.name == "prefect.flow_runs":
style = self._flow_run_style
elif record.name == "prefect.task_runs":
style = self._task_run_style
else:
style = self._style
return style.format(record)
| PrefectFormatter |
python | django__django | tests/lookup/models.py | {
"start": 148,
"end": 325
} | class ____(models.Model):
desc = models.CharField(max_length=100)
time = models.TimeField()
def __str__(self):
return "%s (%s)" % (self.time, self.desc)
| Alarm |
python | numba__numba | numba/tests/test_listobject.py | {
"start": 25252,
"end": 26128
} | class ____(MemoryLeakMixin, TestCase):
"""Test list count. """
def test_list_count_empty(self):
@njit
def foo(i):
l = listobject.new_list(int32)
return l.count(i)
self.assertEqual(foo(10), 0)
def test_list_count_singleton(self):
@njit
def foo(i):
l = listobject.new_list(int32)
l.append(10)
return l.count(i)
self.assertEqual(foo(1), 0)
self.assertEqual(foo(10), 1)
def test_list_count_mutiple(self):
@njit
def foo(i):
l = listobject.new_list(int32)
for j in [11, 12, 12, 13, 13, 13]:
l.append(j)
return l.count(i)
self.assertEqual(foo(10), 0)
self.assertEqual(foo(11), 1)
self.assertEqual(foo(12), 2)
self.assertEqual(foo(13), 3)
| TestCount |
python | nedbat__coveragepy | coverage/misc.py | {
"start": 1760,
"end": 4481
} | class ____:
"""Saves the contents of sys.modules, and removes new modules later."""
def __init__(self) -> None:
self.old_modules = set(sys.modules)
def restore(self) -> None:
"""Remove any modules imported since this object started."""
new_modules = set(sys.modules) - self.old_modules
for m in new_modules:
del sys.modules[m]
@contextlib.contextmanager
def sys_modules_saved() -> Iterator[None]:
"""A context manager to remove any modules imported during a block."""
saver = SysModuleSaver()
try:
yield
finally:
saver.restore()
def import_third_party(modname: str) -> tuple[ModuleType, bool]:
"""Import a third-party module we need, but might not be installed.
This also cleans out the module after the import, so that coverage won't
appear to have imported it. This lets the third party use coverage for
their own tests.
Arguments:
modname (str): the name of the module to import.
Returns:
The imported module, and a boolean indicating if the module could be imported.
If the boolean is False, the module returned is not the one you want: don't use it.
"""
with sys_modules_saved():
try:
return importlib.import_module(modname), True
except ImportError:
return sys, False
def nice_pair(pair: TArc) -> str:
"""Make a nice string representation of a pair of numbers.
If the numbers are equal, just return the number, otherwise return the pair
with a dash between them, indicating the range.
"""
start, end = pair
if start == end:
return f"{start}"
else:
return f"{start}-{end}"
def bool_or_none(b: Any) -> bool | None:
"""Return bool(b), but preserve None."""
if b is None:
return None
else:
return bool(b)
def join_regex(regexes: Iterable[str]) -> str:
"""Combine a series of regex strings into one that matches any of them."""
regexes = list(regexes)
if len(regexes) == 1:
return regexes[0]
else:
return "|".join(f"(?:{r})" for r in regexes)
def file_be_gone(path: str) -> None:
"""Remove a file, and don't get annoyed if it doesn't exist."""
try:
os.remove(path)
except OSError as e:
if e.errno != errno.ENOENT:
raise
def ensure_dir(directory: str) -> None:
"""Make sure the directory exists.
If `directory` is None or empty, do nothing.
"""
if directory:
os.makedirs(directory, exist_ok=True)
def ensure_dir_for_file(path: str) -> None:
"""Make sure the directory for the path exists."""
ensure_dir(os.path.dirname(path))
| SysModuleSaver |
python | ray-project__ray | rllib/examples/algorithms/bc/benchmark_rlunplugged_atari_pong_bc.py | {
"start": 1112,
"end": 12653
} | class ____(ConnectorV2):
def __init__(
self,
input_observation_space: Optional[gym.Space] = None,
input_action_space: Optional[gym.Space] = None,
*,
multi_agent: bool = False,
as_learner_connector: bool = True,
**kwargs,
):
"""Decodes observation from PNG to numpy array.
Note, `rl_unplugged`'s stored observations are framestacked with
four frames per observation. This connector returns therefore
decoded observations of shape `(64, 64, 4)`.
Args:
multi_agent: Whether this is a connector operating on a multi-agent
observation space mapping AgentIDs to individual agents' observations.
as_learner_connector: Whether this connector is part of a Learner connector
pipeline, as opposed to an env-to-module pipeline.
"""
super().__init__(
input_observation_space=input_observation_space,
input_action_space=input_action_space,
**kwargs,
)
self._multi_agent = multi_agent
self._as_learner_connector = as_learner_connector
@override(ConnectorV2)
def recompute_output_observation_space(
self, input_observation_space, input_action_space
):
return gym.spaces.Box(
-1.0, 1.0, (64, 64, 4), float
) # <- to keep it simple hardcoded to a fixed space
@override(ConnectorV2)
def __call__(
self,
*,
rl_module,
data,
episodes,
explore=None,
shared_data=None,
**kwargs,
):
for sa_episode in self.single_agent_episode_iterator(
episodes, agents_that_stepped_only=False
):
# Map encoded PNGs into arrays of shape (64, 64, 4).
def _map_fn(s):
# Preallocate the result array with shape (64, 64, 4)
result = np.empty((64, 64, 4), dtype=np.uint8)
for i in range(4):
# Convert byte data to a numpy array of uint8
nparr = np.frombuffer(s[i], np.uint8)
# Decode the image as grayscale
img = cv2.imdecode(nparr, cv2.IMREAD_GRAYSCALE)
# Resize the image to 64x64 using an efficient interpolation method
resized = cv2.resize(img, (64, 64), interpolation=cv2.INTER_AREA)
result[:, :, i] = resized
return (result.astype(np.float32) / 128.0) - 1.0
# Add the observations for t.
self.add_n_batch_items(
batch=data,
column=Columns.OBS,
# Ensure, we pass in a list, otherwise it is considered
# an already batched array.
items_to_add=[
_map_fn(
sa_episode.get_observations(slice(0, len(sa_episode)))[0],
)
],
num_items=len(sa_episode),
single_agent_episode=sa_episode,
)
# Add the observations for t+1.
self.add_n_batch_items(
batch=data,
column=Columns.NEXT_OBS,
items_to_add=[
_map_fn(
sa_episode.get_observations(slice(1, len(sa_episode) + 1))[0],
)
],
num_items=len(sa_episode),
single_agent_episode=sa_episode,
)
return data
# Make the learner connector.
def _make_learner_connector(observation_space, action_space):
return DecodeObservations()
# Use `parser` to add your own custom command line options to this script
# and (if needed) use their values toset up `config` below.
parser = add_rllib_example_script_args(
default_reward=21.0,
default_timesteps=3000000000,
default_iters=100000000000,
)
args = parser.parse_args()
# If multiple learners are requested define a scheduling
# strategy with best data locality.
if args.num_learners and args.num_learners > 1:
import ray
ray.init()
# Check, if we have a multi-node cluster.
nodes = ray.nodes()
ray.shutdown()
print(f"Number of nodes in cluster: {len(nodes)}")
# If we have a multi-node cluster spread learners.
if len(nodes) > 1:
os.environ["TRAIN_ENABLE_WORKER_SPREAD_ENV"] = "1"
print(
"Multi-node cluster and multi-learner setup. "
"Using a 'SPREAD' scheduling strategy for learners"
"to support data locality."
)
# Otherwise pack the learners on the single node.
else:
print(
"Single-node cluster and multi-learner setup. "
"Using a 'PACK' scheduling strategy for learners"
"to support data locality."
)
# Wrap the environment used in evalaution into `RLlib`'s Atari Wrapper
# that automatically stacks frames and converts to the dimension used
# in the collection of the `rl_unplugged` data.
def _env_creator(cfg):
return wrap_atari_for_new_api_stack(
gym.make("ale_py:ALE/Pong-v5", **cfg),
framestack=4,
dim=64,
)
# Register the wrapped environment to `tune`. Note, environment registration
# to Ray Tune must happen after checking the number of nodes, otherwise the
# registration is removed.
tune.register_env("WrappedALE/Pong-v5", _env_creator)
# Anyscale RLUnplugged storage bucket. The bucket contains from the
# original `RLUnplugged` bucket only the first `atari/Pong` run.
# TODO (simon, artur): Create an extra bucket for the data and do not
# use the `ANYSCALE_ARTIFACT_STORAGE`.
anyscale_storage_bucket = os.environ["ANYSCALE_ARTIFACT_STORAGE"]
anyscale_rlunplugged_atari_path = anyscale_storage_bucket + "/rllib/rl_unplugged/atari"
# We only use the Atari game `Pong` here. Users can choose other Atari
# games and set here the name.
game = "Pong"
# Path to the directory with all runs from Atari Pong.
anyscale_rlunplugged_atari_pong_path = anyscale_rlunplugged_atari_path + f"/{game}"
print(
"Streaming RLUnplugged Atari Pong data from path: "
f"{anyscale_rlunplugged_atari_pong_path}"
)
# As we can not run with `Ray Tune` we use the `UnifiedLogger`.
def default_logger_creator(config):
"""Creates a Unified logger with the default prefix."""
timestr = time.strftime("%Y-%m-%d_%H:%M:%S")
return UnifiedLogger(
config,
# TODO (simon): Change to a default one.
f"/home/ray/default/repos/ray_results/single_learner_gpu_all_data_{timestr}",
loggers=None,
)
# Define the config for Behavior Cloning.
config = (
BCConfig()
.environment(
env="WrappedALE/Pong-v5",
clip_rewards=True,
env_config={
# Make analogous to old v4 + NoFrameskip.
"frameskip": 4,
"full_action_space": False,
"repeat_action_probability": 0.0,
},
)
# Use the new API stack that makes directly use of `ray.data`.
.api_stack(
enable_rl_module_and_learner=True,
enable_env_runner_and_connector_v2=True,
)
# Evaluate in the actual environment online.
.evaluation(
evaluation_interval=1,
evaluation_num_env_runners=1,
evaluation_duration=5,
evaluation_parallel_to_training=True,
evaluation_config=BCConfig.overrides(exploration=False),
)
.learners(
num_learners=args.num_learners,
num_gpus_per_learner=args.num_gpus_per_learner,
)
# Note, the `input_` argument is the major argument for the
# new offline API. Via the `input_read_method_kwargs` the
# arguments for the `ray.data.Dataset` read method can be
# configured. The read method needs at least as many blocks
# as remote learners.
.offline_data(
input_=[anyscale_rlunplugged_atari_pong_path],
# `rl_unplugged`'s data schema is different from the one used
# internally in `RLlib`. Define the schema here so it can be used
# when transforming column data to episodes.
input_read_schema={
Columns.EPS_ID: "episode_id",
Columns.OBS: "o_t",
Columns.ACTIONS: "a_t",
Columns.REWARDS: "r_t",
Columns.NEXT_OBS: "o_tp1",
Columns.TERMINATEDS: "d_t",
},
# Do not materialize data, instead stream the data from Anyscale's
# S3 bucket (note, streaming data is an Anyscale-platform-only feature).
materialize_data=False,
materialize_mapped_data=False,
# Increase the parallelism in transforming batches, such that while
# training, new batches are transformed while others are used in updating.
map_batches_kwargs={
"concurrency": 40 * (max(args.num_learners, 1) or 1),
"num_cpus": 1,
},
# When iterating over batches in the dataset, prefetch at least 4
# batches per learner.
iter_batches_kwargs={
"prefetch_batches": 10,
},
# Iterate over 200 batches per RLlib iteration if multiple learners
# are used.
dataset_num_iters_per_learner=200,
)
.training(
# To increase learning speed with multiple learners,
# increase the learning rate correspondingly.
lr=0.0001
* max(
1,
(args.num_learners if args.num_learners and args.num_learners > 1 else 1)
** 0.5,
),
train_batch_size_per_learner=2048,
# Use the defined learner connector above, to decode observations.
learner_connector=_make_learner_connector,
)
.rl_module(
model_config=DefaultModelConfig(
conv_filters=[[16, 4, 2], [32, 4, 2], [64, 4, 2], [128, 4, 2]],
conv_activation="relu",
head_fcnet_hiddens=[256],
),
)
.debugging(
logger_creator=default_logger_creator,
log_level="ERROR",
)
)
# Stop, if either the maximum point in Pong is reached (21.0) or 10 million steps
# were trained.
stop = {
f"{EVALUATION_RESULTS} / {ENV_RUNNER_RESULTS} / {EPISODE_RETURN_MEAN}": args.stop_reward,
f"{LEARNER_RESULTS} / {ALL_MODULES} / {NUM_ENV_STEPS_TRAINED_LIFETIME}": args.stop_timesteps,
}
# Build the algorithm.
algo = config.build()
# Shall we use wandb for logging results?
if args.wandb_key:
# Login to wandb.
wandb.login(
key=args.wandb_key,
verify=True,
relogin=True,
force=True,
)
# Initialize wandb.
wandb.init(project=args.wandb_project)
# Clean results to log seemlessly to wandb.
from ray.air.integrations.wandb import _clean_log
i = 0
while True:
print("---------------------------------------------------------------")
print(f"Iteration {i + 1}")
results = algo.train()
print(results)
if args.wandb_key:
# Log results to wandb.
wandb.log(data=_clean_log(results), step=i)
if stop:
if should_stop(stop, results):
algo.cleanup()
break
i += 1
print("------------------------------------------------")
print()
print("Training finished:\n")
print(
f"Mean Episode Return in Evaluation: {results[EVALUATION_RESULTS][ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN]}"
)
print(
f"Number of Environment Steps trained: {results[LEARNER_RESULTS][ALL_MODULES][NUM_ENV_STEPS_TRAINED_LIFETIME]}"
)
print("================================================")
| DecodeObservations |
python | mahmoud__boltons | boltons/tbutils.py | {
"start": 20872,
"end": 25012
} | class ____(ExceptionInfo):
"""The ContextualTracebackInfo type is a :class:`TracebackInfo`
subtype that uses the :class:`ContextualCallpoint` as its
frame-representing primitive.
It carries with it most of the exception information required to
recreate the widely recognizable "500" page for debugging Django
applications.
"""
tb_info_type = ContextualTracebackInfo
# TODO: clean up & reimplement -- specifically for syntax errors
def format_exception_only(etype, value):
"""Format the exception part of a traceback.
The arguments are the exception type and value such as given by
sys.last_type and sys.last_value. The return value is a list of
strings, each ending in a newline.
Normally, the list contains a single string; however, for
SyntaxError exceptions, it contains several lines that (when
printed) display detailed information about where the syntax
error occurred.
The message indicating which exception occurred is always the last
string in the list.
"""
# Gracefully handle (the way Python 2.4 and earlier did) the case of
# being called with (None, None).
if etype is None:
return [_format_final_exc_line(etype, value)]
stype = etype.__name__
smod = etype.__module__
if smod not in ("__main__", "builtins", "exceptions"):
stype = smod + '.' + stype
if not issubclass(etype, SyntaxError):
return [_format_final_exc_line(stype, value)]
# It was a syntax error; show exactly where the problem was found.
lines = []
filename = value.filename or "<string>"
lineno = str(value.lineno) or '?'
lines.append(f' File "{filename}", line {lineno}\n')
badline = value.text
offset = value.offset
if badline is not None:
lines.append(' %s\n' % badline.strip())
if offset is not None:
caretspace = badline.rstrip('\n')[:offset].lstrip()
# non-space whitespace (likes tabs) must be kept for alignment
caretspace = ((c.isspace() and c or ' ') for c in caretspace)
# only three spaces to account for offset1 == pos 0
lines.append(' %s^\n' % ''.join(caretspace))
msg = value.msg or "<no detail available>"
lines.append(f"{stype}: {msg}\n")
return lines
# TODO: use asciify, improved if necessary
def _some_str(value):
try:
return str(value)
except Exception:
pass
return '<unprintable %s object>' % type(value).__name__
def _format_final_exc_line(etype, value):
valuestr = _some_str(value)
if value is None or not valuestr:
line = "%s\n" % etype
else:
line = f"{etype}: {valuestr}\n"
return line
def print_exception(etype, value, tb, limit=None, file=None):
"""Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
This differs from print_tb() in the following ways: (1) if
traceback is not None, it prints a header "Traceback (most recent
call last):"; (2) it prints the exception type and value after the
stack trace; (3) if type is SyntaxError and value has the
appropriate format, it prints the line where the syntax error
occurred with a caret on the next line indicating the approximate
position of the error.
"""
if file is None:
file = sys.stderr
if tb:
tbi = TracebackInfo.from_traceback(tb, limit)
print(str(tbi), end='', file=file)
for line in format_exception_only(etype, value):
print(line, end='', file=file)
def fix_print_exception():
"""
Sets the default exception hook :func:`sys.excepthook` to the
:func:`tbutils.print_exception` that uses all the ``tbutils``
facilities to provide a consistent output behavior.
"""
sys.excepthook = print_exception
_frame_re = re.compile(r'^File "(?P<filepath>.+)", line (?P<lineno>\d+)'
r', in (?P<funcname>.+)$')
_se_frame_re = re.compile(r'^File "(?P<filepath>.+)", line (?P<lineno>\d+)')
_underline_re = re.compile(r'^[~^ ]*$')
# TODO: ParsedException generator over large bodies of text
| ContextualExceptionInfo |
python | keras-team__keras | keras/src/quantizers/quantizers_test.py | {
"start": 638,
"end": 23369
} | class ____(testing.TestCase):
def test_get_method(self):
quantizer = quantizers.get("abs_max_quantizer", axis=-1)
self.assertTrue(quantizer, quantizers.AbsMaxQuantizer)
quantizer = quantizers.get(None)
self.assertEqual(quantizer, None)
with self.assertRaises(ValueError):
quantizers.get("typo")
def test_abs_max_quantizer(self):
values = random.uniform([3, 4, 5], minval=-1, maxval=1, dtype="float32")
quantizer = quantizers.AbsMaxQuantizer(axis=-1)
# Test quantizing
quantized_values, scale = quantizer(values)
self.assertDType(quantized_values, "int8")
self.assertDType(scale, "float32")
self.assertEqual(tuple(quantized_values.shape), (3, 4, 5))
self.assertEqual(tuple(scale.shape), (3, 4, 1))
self.assertLessEqual(ops.max(quantized_values), 127)
self.assertGreaterEqual(ops.min(quantized_values), -127)
# Test dequantizing
dequantized_values = ops.divide(quantized_values, scale)
rmse = ops.sqrt(
ops.mean(ops.square(ops.subtract(values, dequantized_values)))
)
self.assertLess(rmse, 1e-1) # loose assertion
# Test serialization
self.run_class_serialization_test(quantizer)
# Test bfloat16 & float16 dtype
values = random.uniform(
[3, 4, 5], minval=-1, maxval=1, dtype="bfloat16"
)
quantized_values, scale = quantizer(values)
self.assertDType(quantized_values, "int8")
self.assertDType(scale, "bfloat16")
values = random.uniform([3, 4, 5], minval=-1, maxval=1, dtype="float16")
quantized_values, scale = quantizer(values)
self.assertDType(quantized_values, "int8")
self.assertDType(scale, "float16")
def test_abs_max_quantizer_to_numpy(self):
values = random.uniform([3, 4, 5], minval=-1, maxval=1, dtype="float32")
quantized_values, scale = quantizers.abs_max_quantize(
values, axis=-1, to_numpy=True
)
ref_quantized_values, ref_scale = quantizers.abs_max_quantize(
values, axis=-1
)
self.assertAllClose(quantized_values, ref_quantized_values)
self.assertAllClose(scale, ref_scale)
def test_compute_float8_scale(self):
amax = 3.0
scale = 4.0
dtype_max = 448.0 # float8_e4m3fn
# The algorithm for computing the new scale is sourced from
# https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/api/jax.html#transformer_engine.jax.update_fp8_metas
expected_scale = 1.0 / (dtype_max / amax) / (2**0)
computed_scale = quantizers.compute_float8_scale(amax, scale, dtype_max)
self.assertAllClose(computed_scale, expected_scale)
def test_compute_float8_amax_history(self):
values = random.uniform([3, 4, 5], minval=-1, maxval=1)
amax_history = random.uniform([123])
amax_from_values = ops.max(ops.abs(values))
computed_amax_history = quantizers.compute_float8_amax_history(
values, amax_history
)
self.assertAllClose(computed_amax_history[0], amax_from_values)
# Shift to left with 1 step
self.assertAllClose(
computed_amax_history[1:], ops.roll(amax_history, -1)[1:]
)
def test_quantize_and_dequantize(self):
scale = 1.0 / 100.0
values = random.uniform([3, 4, 5], minval=-1, maxval=1)
qdq_values = quantizers.quantize_and_dequantize(
values, scale, "float8_e4m3fn", "float32"
)
# A loose assertion due to an expected quantization error
self.assertAllClose(qdq_values, values, atol=1e-1)
qdq_values = quantizers.quantize_and_dequantize(
values, scale, "float8_e5m2", "float32"
)
# A loose assertion due to an expected quantization error
self.assertAllClose(qdq_values, values, atol=5e-1)
SHAPE_AXIS_SCENARIOS = [
# 1. 2D Tensors
# Covers the unpack fast path (rank=2, axis=0) for both parities
{"testcase_name": "2d_axis0_odd", "shape": (5, 8), "axis": 0},
{"testcase_name": "2d_axis0_even", "shape": (4, 8), "axis": 0},
# Covers the general path and a negative axis for 2D tensors
{"testcase_name": "2d_axis1_odd", "shape": (8, 7), "axis": 1},
{"testcase_name": "2d_axis_neg1_even", "shape": (8, 6), "axis": -1},
# 2. Higher-Rank Tensors
# Covers a middle axis for a complex shape with both parities
{"testcase_name": "4d_axis1_odd", "shape": (2, 5, 4, 6), "axis": 1},
{"testcase_name": "4d_axis2_even", "shape": (2, 4, 8, 6), "axis": 2},
# Covers the last axis of a complex shape with a negative index
{
"testcase_name": "4d_axis_neg1_odd",
"shape": (2, 4, 6, 7),
"axis": -1,
},
]
DTYPE_PARAMS = [
{"testcase_name": "int8", "dtype": "int8", "minval": -8, "maxval": 8},
{"testcase_name": "uint8", "dtype": "uint8", "minval": 0, "maxval": 16},
]
@parameterized.named_parameters(
named_product(SHAPE_AXIS_SCENARIOS, DTYPE_PARAMS)
)
def test_pack_unpack_int4(self, shape, axis, dtype, minval, maxval):
# Create a random tensor with int4 values in the specified range and
# dtype
arr = ops.cast(
ops.floor(random.uniform(shape, minval=minval, maxval=maxval)),
dtype,
)
# Pack the tensor using the specified dtype
packed, packed_shape, orig_len = quantizers.pack_int4(
arr, axis=axis, dtype=dtype
)
# Unpack the tensor using the specified dtype
unpacked = quantizers.unpack_int4(
packed, orig_len, axis=axis, dtype=dtype
)
# Verify that the packed tensor has the correct dtype
self.assertDType(packed, dtype)
# Verify that the unpacked tensor has the correct dtype
self.assertDType(unpacked, dtype)
# The unpacked tensor should be the same as the original tensor
self.assertAllClose(unpacked, arr)
# Test the packed shape
expected_packed_shape = list(shape)
expected_packed_shape[axis] = (expected_packed_shape[axis] + 1) // 2
self.assertEqual(
list(ops.convert_to_numpy(packed_shape)), expected_packed_shape
)
@parameterized.named_parameters(
("per_tensor", None),
("per_channel", -1),
)
def test_fake_quant_with_min_max_vars_symbolic(self, axis):
x = backend.KerasTensor((2, 3, 4))
y = quantizers.fake_quant_with_min_max_vars(x, -3.0, 3.0, axis=axis)
self.assertIsInstance(y, backend.KerasTensor)
self.assertEqual(y.shape, (2, 3, 4))
@parameterized.named_parameters(
[
{
"testcase_name": "wide_8bits_input_mins_0.0_input_maxs_255.0",
"narrow_range": False,
"input_mins": [0.0],
"input_maxs": [255.0],
"num_bits": 8,
"expected_nudged_input_mins": [0.0],
"expected_nudged_input_maxs": [255.0],
"expected_steps": [1.0],
"axis": None,
},
{
"testcase_name": "wide_8bits_input_mins_0.5_input_maxs_128.0",
"narrow_range": False,
"input_mins": [0.5],
"input_maxs": [128.0],
"num_bits": 8,
"expected_nudged_input_mins": [0.0],
"expected_nudged_input_maxs": [127.5],
"expected_steps": [0.5],
"axis": None,
},
{
"testcase_name": "wide_8bits_input_mins_-128.0_input_maxs_-0.5",
"narrow_range": False,
"input_mins": [-128.0],
"input_maxs": [-0.5],
"num_bits": 8,
"expected_nudged_input_mins": [-127.5],
"expected_nudged_input_maxs": [0.0],
"expected_steps": [0.5],
"axis": None,
},
{
"testcase_name": "wide_8bits_input_mins_-0.1_input_maxs_127.4",
"narrow_range": False,
"input_mins": [-0.1],
"input_maxs": [127.4],
"num_bits": 8,
"expected_nudged_input_mins": [0.0],
"expected_nudged_input_maxs": [127.5],
"expected_steps": [0.5],
"axis": None,
},
{
"testcase_name": "narrow_8bits_input_mins_0.0_input_maxs_254.0",
"narrow_range": True,
"input_mins": [0.0],
"input_maxs": [254.0],
"num_bits": 8,
"expected_nudged_input_mins": [0.0],
"expected_nudged_input_maxs": [254.0],
"expected_steps": [1.0],
"axis": None,
},
{
"testcase_name": "narrow_8bits_input_mins_0.1_input_maxs_127.1",
"narrow_range": True,
"input_mins": [0.1],
"input_maxs": [127.1],
"num_bits": 8,
"expected_nudged_input_mins": [0.0],
"expected_nudged_input_maxs": [127.0],
"expected_steps": [0.5],
"axis": None,
},
{
"testcase_name": (
"narrow_8bits_input_mins_-127.1_input_maxs_-0.1"
),
"narrow_range": True,
"input_mins": [-127.1],
"input_maxs": [-0.1],
"num_bits": 8,
"expected_nudged_input_mins": [-127.0],
"expected_nudged_input_maxs": [0.0],
"expected_steps": [0.5],
"axis": None,
},
{
"testcase_name": (
"narrow_8bits_input_mins_-0.1_input_maxs_126.9"
),
"narrow_range": True,
"input_mins": [-0.1],
"input_maxs": [126.9],
"num_bits": 8,
"expected_nudged_input_mins": [0.0],
"expected_nudged_input_maxs": [127.0],
"expected_steps": [0.5],
"axis": None,
},
{
"testcase_name": "wide_7bits_input_mins_0.0_input_maxs_127.0",
"narrow_range": False,
"input_mins": [0.0],
"input_maxs": [127.0],
"num_bits": 7,
"expected_nudged_input_mins": [0.0],
"expected_nudged_input_maxs": [127.0],
"expected_steps": [1.0],
"axis": None,
},
{
"testcase_name": "wide_7bits_input_mins_0.5_input_maxs_64.0",
"narrow_range": False,
"input_mins": [0.5],
"input_maxs": [64.0],
"num_bits": 7,
"expected_nudged_input_mins": [0.0],
"expected_nudged_input_maxs": [63.5],
"expected_steps": [0.5],
"axis": None,
},
{
"testcase_name": "wide_7bits_input_mins_-64.0_input_maxs_-0.5",
"narrow_range": False,
"input_mins": [-64.0],
"input_maxs": [-0.5],
"num_bits": 7,
"expected_nudged_input_mins": [-63.5],
"expected_nudged_input_maxs": [0.0],
"expected_steps": [0.5],
"axis": None,
},
{
"testcase_name": "wide_7bits_input_mins_-0.1_input_maxs_63.4",
"narrow_range": False,
"input_mins": [-0.1],
"input_maxs": [63.4],
"num_bits": 7,
"expected_nudged_input_mins": [0.0],
"expected_nudged_input_maxs": [63.5],
"expected_steps": [0.5],
"axis": None,
},
{
"testcase_name": "narrow_7bits_input_mins_0.0_input_maxs_126.0",
"narrow_range": True,
"input_mins": [0.0],
"input_maxs": [126.0],
"num_bits": 7,
"expected_nudged_input_mins": [0.0],
"expected_nudged_input_maxs": [126.0],
"expected_steps": [1.0],
"axis": None,
},
{
"testcase_name": "narrow_7bits_input_mins_0.1_input_maxs_63.1",
"narrow_range": True,
"input_mins": [0.1],
"input_maxs": [63.1],
"num_bits": 7,
"expected_nudged_input_mins": [0.0],
"expected_nudged_input_maxs": [63.0],
"expected_steps": [0.5],
"axis": None,
},
{
"testcase_name": (
"narrow_7bits_input_mins_-63.1_input_maxs_-0.1"
),
"narrow_range": True,
"input_mins": [-63.1],
"input_maxs": [-0.1],
"num_bits": 7,
"expected_nudged_input_mins": [-63.0],
"expected_nudged_input_maxs": [0.0],
"expected_steps": [0.5],
"axis": None,
},
{
"testcase_name": "narrow_7bits_input_mins_-0.1_input_maxs_62.9",
"narrow_range": True,
"input_mins": [-0.1],
"input_maxs": [62.9],
"num_bits": 7,
"expected_nudged_input_mins": [0.0],
"expected_nudged_input_maxs": [63.0],
"expected_steps": [0.5],
"axis": None,
},
{
"testcase_name": "wide_8bits_multi_channel",
"narrow_range": False,
"input_mins": [0.0, 0.5, -128.0, -0.1],
"input_maxs": [255.0, 128.0, -0.5, 127.4],
"num_bits": 8,
"expected_nudged_input_mins": [0.0, 0.0, -127.5, 0.0],
"expected_nudged_input_maxs": [255.0, 127.5, 0.0, 127.5],
"expected_steps": [1.0, 0.5, 0.5, 0.5],
"axis": 1,
},
{
"testcase_name": "narrow_8bits_multi_channel",
"narrow_range": True,
"input_mins": [0.0, 0.1, -127.1, -0.1],
"input_maxs": [254.0, 127.1, -0.1, 126.9],
"num_bits": 8,
"expected_nudged_input_mins": [0.0, 0.0, -127.0, 0.0],
"expected_nudged_input_maxs": [254.0, 127.0, 0.0, 127.0],
"expected_steps": [1.0, 0.5, 0.5, 0.5],
"axis": 1,
},
{
"testcase_name": "wide_7bits_multi_channel",
"narrow_range": False,
"input_mins": [0.0, 0.5, -64.0, -0.1],
"input_maxs": [127.0, 64.0, -0.5, 63.4],
"num_bits": 7,
"expected_nudged_input_mins": [0.0, 0.0, -63.5, 0.0],
"expected_nudged_input_maxs": [127.0, 63.5, 0.0, 63.5],
"expected_steps": [1.0, 0.5, 0.5, 0.5],
"axis": 1,
},
{
"testcase_name": "narrow_7bits_multi_channel",
"narrow_range": True,
"input_mins": [0.0, 0.1, -63.1, -0.1],
"input_maxs": [126.0, 63.1, -0.1, 62.9],
"num_bits": 7,
"expected_nudged_input_mins": [0.0, 0.0, -63.0, 0.0],
"expected_nudged_input_maxs": [126.0, 63.0, 0.0, 63.0],
"expected_steps": [1.0, 0.5, 0.5, 0.5],
"axis": 1,
},
]
)
@pytest.mark.skipif(
backend.backend() not in ("tensorflow", "jax", "torch"),
reason=f"{backend.backend()} doesn't support `custom_gradient`.",
)
def test_fake_quant_with_min_max_vars(
self,
input_mins,
input_maxs,
num_bits,
narrow_range,
axis,
expected_nudged_input_mins,
expected_nudged_input_maxs,
expected_steps,
):
num_channels = len(input_mins)
inputs_list = []
expected_list = []
initial_gradients_list = []
expected_backprops_wrt_input_list = []
for i in range(num_channels):
expected_nudged_input_min = expected_nudged_input_mins[i]
expected_nudged_input_max = expected_nudged_input_maxs[i]
expected_step = expected_steps[i]
inputs_list.append(
[
expected_nudged_input_min - expected_step,
expected_nudged_input_min - 0.01,
expected_nudged_input_min,
expected_nudged_input_min + 0.01,
expected_nudged_input_min + expected_step - 0.01,
expected_nudged_input_min + expected_step,
expected_nudged_input_min + expected_step + 0.01,
expected_nudged_input_max - 0.01,
expected_nudged_input_max,
expected_nudged_input_max + 0.01,
expected_nudged_input_max + expected_step,
]
)
expected_list.append(
[
expected_nudged_input_min,
expected_nudged_input_min,
expected_nudged_input_min,
expected_nudged_input_min,
expected_nudged_input_min + expected_step,
expected_nudged_input_min + expected_step,
expected_nudged_input_min + expected_step,
expected_nudged_input_max,
expected_nudged_input_max,
expected_nudged_input_max,
expected_nudged_input_max,
]
)
initial_gradients_list.append(
list(range(1, len(inputs_list[-1]) + 1))
)
expected_backprops_wrt_input_list.append(
[0.0, 0.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.0, 0.0]
)
inputs = ops.transpose(ops.array(inputs_list, dtype="float32"))
expected = ops.transpose(ops.array(expected_list, dtype="float32"))
expected_backprops_wrt_input = ops.transpose(
ops.array(expected_backprops_wrt_input_list, dtype="float32")
)
input_min = ops.array(input_mins, dtype="float32")
input_max = ops.array(input_maxs, dtype="float32")
initial_gradients = ops.transpose(
ops.array(initial_gradients_list, dtype="float32")
)
# Test gradients.
if backend.backend() == "tensorflow":
import tensorflow as tf
@tf.function(jit_compile=True)
def test_op(
inputs, input_mins, input_maxs, num_bits, narrow_range, axis
):
with tf.GradientTape() as tape:
tape.watch(inputs)
result = quantizers.fake_quant_with_min_max_vars(
inputs,
input_mins,
input_maxs,
num_bits,
narrow_range,
axis,
)
return initial_gradients * tape.gradient(result, inputs)
if backend.backend() == "torch":
import torch
def test_op(
inputs, input_mins, input_maxs, num_bits, narrow_range, axis
):
# Create tensor and enable gradient tracking
inputs = torch.tensor(
inputs, dtype=torch.float32, requires_grad=True
)
# Apply the quantization operation
result = quantizers.fake_quant_with_min_max_vars(
inputs, input_mins, input_maxs, num_bits, narrow_range, axis
)
# Compute gradients
result.backward(torch.ones_like(result))
return initial_gradients * inputs.grad
if backend.backend() == "jax":
import jax
def test_op(
inputs, input_mins, input_maxs, num_bits, narrow_range, axis
):
# Define the function to compute gradients for
def quantize_fn(x):
return quantizers.fake_quant_with_min_max_vars(
x, input_mins, input_maxs, num_bits, narrow_range, axis
)
_, f_vjp = jax.vjp(quantize_fn, inputs)
if getattr(jax.config, "jax_vjp3", False):
input_gradients = f_vjp.opaque_residuals[0]
elif sys.version_info >= (3, 10):
input_gradients = f_vjp.args[0].args[0][0]
else:
input_gradients = f_vjp.args[0].args[0][1]
return ops.multiply(initial_gradients, input_gradients)
gradients = test_op(
inputs, input_min, input_max, num_bits, narrow_range, axis
)
if backend.backend() != "jax" or not testing.jax_uses_gpu():
# JAX GPU produces less precise numbers, causing the CI to fail.
# For example, 127.5 / 255.0 results in 0.49999997 instead of 0.5.
self.assertAllClose(gradients, expected_backprops_wrt_input)
# Test outputs.
outputs = quantizers.fake_quant_with_min_max_vars(
inputs,
input_min,
input_max,
num_bits=num_bits,
narrow_range=narrow_range,
axis=axis,
)
self.assertAllClose(outputs, expected)
# Test bfloat16 & float16 dtype
outputs = quantizers.fake_quant_with_min_max_vars(
ops.cast(inputs, "bfloat16"),
input_min,
input_max,
num_bits=num_bits,
narrow_range=narrow_range,
axis=axis,
)
self.assertDType(outputs, "bfloat16")
self.assertAllClose(outputs, expected)
outputs = quantizers.fake_quant_with_min_max_vars(
ops.cast(inputs, "float16"),
input_min,
input_max,
num_bits=num_bits,
narrow_range=narrow_range,
axis=axis,
)
self.assertDType(outputs, "float16")
self.assertAllClose(outputs, expected)
| QuantizersTest |
python | pypa__setuptools | setuptools/_vendor/backports/tarfile/__init__.py | {
"start": 23763,
"end": 23802
} | class ____(TarError):
pass
| FilterError |
python | apache__airflow | dev/breeze/src/airflow_breeze/params/shell_params.py | {
"start": 5023,
"end": 38577
} | class ____:
"""
Shell parameters. Those parameters are used to determine command issued to run shell command.
"""
airflow_branch: str = AIRFLOW_BRANCH
airflow_constraints_location: str = ""
airflow_constraints_mode: str = ALLOWED_CONSTRAINTS_MODES_CI[0]
airflow_constraints_reference: str = ""
airflow_extras: str = ""
allow_pre_releases: bool = False
auth_manager: str = ALLOWED_AUTH_MANAGERS[0]
backend: str = ALLOWED_BACKENDS[0]
base_branch: str = "main"
builder: str = "autodetect"
celery_broker: str = DEFAULT_CELERY_BROKER
celery_flower: bool = False
clean_airflow_installation: bool = False
collect_only: bool = False
create_all_roles: bool = False
debug_components: tuple[str, ...] = ()
debugger: str = "debugpy"
db_reset: bool = False
default_constraints_branch: str = DEFAULT_AIRFLOW_CONSTRAINTS_BRANCH
dev_mode: bool = False
docker_host: str | None = os.environ.get("DOCKER_HOST")
downgrade_sqlalchemy: bool = False
downgrade_pendulum: bool = False
dry_run: bool = False
enable_coverage: bool = False
excluded_providers: str = ""
executor: str = START_AIRFLOW_DEFAULT_ALLOWED_EXECUTOR
extra_args: tuple = ()
force_build: bool = False
force_sa_warnings: bool = True
force_lowest_dependencies: bool = False
forward_credentials: bool = False
forward_ports: bool = True
github_actions: str = os.environ.get("GITHUB_ACTIONS", "false")
github_repository: str = APACHE_AIRFLOW_GITHUB_REPOSITORY
github_token: str = os.environ.get("GITHUB_TOKEN", "")
include_mypy_volume: bool = False
install_airflow_version: str = ""
install_airflow_python_client: bool = False
install_airflow_with_constraints: bool = False
install_selected_providers: str | None = None
integration: tuple[str, ...] = ()
issue_id: str = ""
keep_env_variables: bool = False
load_default_connections: bool = False
load_example_dags: bool = False
mount_sources: str = MOUNT_SELECTED
mysql_version: str = ALLOWED_MYSQL_VERSIONS[0]
no_db_cleanup: bool = False
num_runs: str = ""
only_min_version_update: bool = False
distribution_format: str = ALLOWED_INSTALLATION_DISTRIBUTION_FORMATS[0]
parallel_test_types_list: list[str] = field(default_factory=list)
parallelism: int = 0
platform: str = DOCKER_DEFAULT_PLATFORM
postgres_version: str = DEFAULT_POSTGRES_VERSION
project_name: str = ALLOWED_DOCKER_COMPOSE_PROJECTS[0]
providers_constraints_location: str = ""
providers_constraints_mode: str = ALLOWED_CONSTRAINTS_MODES_CI[0]
providers_constraints_reference: str = ""
providers_skip_constraints: bool = False
python: str = ALLOWED_PYTHON_MAJOR_MINOR_VERSIONS[0]
quiet: bool = False
regenerate_missing_docs: bool = False
restart: bool = False
run_db_tests_only: bool = False
run_tests: bool = False
skip_db_tests: bool = False
skip_environment_initialization: bool = False
skip_image_upgrade_check: bool = False
skip_provider_dependencies_check: bool = False
skip_ssh_setup: bool = os.environ.get("SKIP_SSH_SETUP", "false") == "true"
standalone_dag_processor: bool = False
start_airflow: bool = False
test_type: str | None = None
start_api_server_with_examples: bool = False
test_group: GroupOfTests | None = None
tty: str = "auto"
upgrade_boto: bool = False
upgrade_sqlalchemy: bool = False
use_airflow_version: str | None = None
use_distributions_from_dist: bool = False
use_mprocs: bool = False
use_uv: bool = False
use_xdist: bool = False
uv_http_timeout: int = DEFAULT_UV_HTTP_TIMEOUT
verbose: bool = False
verbose_commands: bool = False
version_suffix: str = ""
warn_image_upgrade_needed: bool = False
def clone_with_test(self, test_type: str) -> ShellParams:
new_params = deepcopy(self)
new_params.test_type = test_type
return new_params
@cached_property
def host_user_id(self) -> str:
return get_host_group_id()
@cached_property
def host_group_id(self) -> str:
return get_host_group_id()
@cached_property
def host_os(self) -> str:
return get_host_os()
@cached_property
def airflow_version(self):
return get_airflow_version()
@cached_property
def airflow_version_for_production_image(self):
cmd = ["docker", "run", "--entrypoint", "/bin/bash", f"{self.airflow_image_name}"]
cmd.extend(["-c", 'echo "${AIRFLOW_VERSION}"'])
output = run_command(cmd, capture_output=True, text=True)
return output.stdout.strip() if output.stdout else "UNKNOWN_VERSION"
@cached_property
def airflow_base_image_name(self) -> str:
image = f"ghcr.io/{self.github_repository.lower()}"
return image
@cached_property
def airflow_image_name(self) -> str:
"""Construct CI image link"""
image = f"{self.airflow_base_image_name}/{self.airflow_branch}/ci/python{self.python}"
return image
@cached_property
def airflow_image_kubernetes(self) -> str:
image = f"{self.airflow_base_image_name}/{self.airflow_branch}/kubernetes/python{self.python}"
return image
@cached_property
def airflow_sources(self):
return AIRFLOW_ROOT_PATH
@cached_property
def auth_manager_path(self):
auth_manager_paths = {
SIMPLE_AUTH_MANAGER: "airflow.api_fastapi.auth.managers.simple.simple_auth_manager.SimpleAuthManager",
FAB_AUTH_MANAGER: "airflow.providers.fab.auth_manager.fab_auth_manager.FabAuthManager",
}
return auth_manager_paths[self.auth_manager]
@cached_property
def image_type(self) -> str:
return "CI"
@cached_property
def md5sum_cache_dir(self) -> Path:
cache_dir = Path(BUILD_CACHE_PATH, self.airflow_branch, self.python, self.image_type)
return cache_dir
@cached_property
def backend_version(self) -> str:
version = ""
if self.backend == "postgres":
version = self.postgres_version
if self.backend == "mysql":
version = self.mysql_version
return version
@cached_property
def sqlite_url(self) -> str:
return "sqlite:////root/airflow/sqlite/airflow.db"
def print_badge_info(self):
if get_verbose():
get_console().print(f"[info]Use {self.image_type} image[/]")
get_console().print(f"[info]Branch Name: {self.airflow_branch}[/]")
get_console().print(f"[info]Docker Image: {self.airflow_image_name}[/]")
get_console().print(f"[info]Airflow source version:{self.airflow_version}[/]")
get_console().print(f"[info]Python Version: {self.python}[/]")
get_console().print(f"[info]Backend: {self.backend} {self.backend_version}[/]")
get_console().print(f"[info]Airflow used at runtime: {self.use_airflow_version}[/]")
def get_backend_compose_files(self, backend: str) -> list[Path]:
if backend == "sqlite" and self.project_name != "breeze":
# When running scripts, we do not want to mount the volume to make sure that the
# sqlite database is not persisted between runs of the script and that the
# breeze database is not cleaned accidentally
backend_docker_compose_file = SCRIPTS_CI_DOCKER_COMPOSE_PATH / f"backend-{backend}-no-volume.yml"
else:
backend_docker_compose_file = SCRIPTS_CI_DOCKER_COMPOSE_PATH / f"backend-{backend}.yml"
if backend in ("sqlite", "none") or not self.forward_ports:
return [backend_docker_compose_file]
if self.project_name == "prek":
# do not forward ports for prek - to not clash with running containers from breeze
return [backend_docker_compose_file]
return [backend_docker_compose_file, SCRIPTS_CI_DOCKER_COMPOSE_PATH / f"backend-{backend}-port.yml"]
@cached_property
def compose_file(self) -> str:
compose_file_list: list[Path] = []
backend_files: list[Path] = []
if self.backend != "all":
backend_files = self.get_backend_compose_files(self.backend)
else:
for backend in ALLOWED_BACKENDS:
backend_files.extend(self.get_backend_compose_files(backend))
if self.executor == CELERY_EXECUTOR:
compose_file_list.append(SCRIPTS_CI_DOCKER_COMPOSE_INTEGRATION_CELERY_PATH)
if self.use_airflow_version:
current_extras = self.airflow_extras
if "celery" not in current_extras.split(","):
get_console().print(
"[warning]Adding `celery` extras as it is implicitly needed by celery executor"
)
self.airflow_extras = (
",".join(current_extras.split(",") + ["celery"]) if current_extras else "celery"
)
if self.auth_manager == FAB_AUTH_MANAGER:
if self.use_airflow_version:
current_extras = self.airflow_extras
if "fab" not in current_extras.split(","):
get_console().print(
"[warning]Adding `fab` extras as it is implicitly needed by FAB auth manager"
)
self.airflow_extras = (
",".join(current_extras.split(",") + ["fab"]) if current_extras else "fab"
)
compose_file_list.append(SCRIPTS_CI_DOCKER_COMPOSE_BASE_PATH)
self.add_docker_in_docker(compose_file_list)
compose_file_list.extend(backend_files)
compose_file_list.append(SCRIPTS_CI_DOCKER_COMPOSE_FILES_PATH)
if os.environ.get("CI", "false") == "true":
compose_file_list.append(SCRIPTS_CI_DOCKER_COMPOSE_CI_TESTS_PATH)
if self.use_airflow_version is not None and self.mount_sources not in USE_AIRFLOW_MOUNT_SOURCES:
get_console().print(
"\n[warning]Forcing --mount-sources to `remove` since we are not installing airflow "
f"from sources but from {self.use_airflow_version} since you attempt"
f" to use {self.mount_sources} (but you can use any of "
f"{USE_AIRFLOW_MOUNT_SOURCES} in such case[/]\n"
)
self.mount_sources = MOUNT_REMOVE
if self.mount_sources in USE_AIRFLOW_MOUNT_SOURCES and self.use_airflow_version is None:
get_console().print(
"[error]You need to specify `--use-airflow-version wheel | sdist` when using one of the"
f"{USE_AIRFLOW_MOUNT_SOURCES} mount sources[/]"
)
sys.exit(1)
if self.forward_ports and not self.project_name == "prek":
compose_file_list.append(SCRIPTS_CI_DOCKER_COMPOSE_BASE_PORTS_PATH)
if self.debug_components and not self.project_name == "prek":
compose_file_list.append(SCRIPTS_CI_DOCKER_COMPOSE_DEBUG_PORTS_PATH)
if self.mount_sources == MOUNT_SELECTED:
compose_file_list.append(SCRIPTS_CI_DOCKER_COMPOSE_LOCAL_YAML_PATH)
elif self.mount_sources == MOUNT_ALL:
compose_file_list.append(SCRIPTS_CI_DOCKER_COMPOSE_LOCAL_ALL_SOURCES_PATH)
elif self.mount_sources == MOUNT_TESTS:
compose_file_list.append(SCRIPTS_CI_DOCKER_COMPOSE_TESTS_SOURCES_PATH)
elif self.mount_sources == MOUNT_PROVIDERS_AND_TESTS:
compose_file_list.append(SCRIPTS_CI_DOCKER_COMPOSE_PROVIDERS_AND_TESTS_SOURCES_PATH)
elif self.mount_sources == MOUNT_REMOVE:
compose_file_list.append(SCRIPTS_CI_DOCKER_COMPOSE_REMOVE_SOURCES_PATH)
if self.forward_credentials:
compose_file_list.append(SCRIPTS_CI_DOCKER_COMPOSE_FORWARD_CREDENTIALS_PATH)
if self.include_mypy_volume:
compose_file_list.append(SCRIPTS_CI_DOCKER_COMPOSE_MYPY_PATH)
if self.tty == "enabled":
compose_file_list.append(SCRIPTS_CI_DOCKER_COMPOSE_ENABLE_TTY_PATH)
if "all-testable" in self.integration:
if self.test_group == GroupOfTests.INTEGRATION_CORE:
integrations = TESTABLE_CORE_INTEGRATIONS
elif self.test_group == GroupOfTests.INTEGRATION_PROVIDERS:
integrations = TESTABLE_PROVIDERS_INTEGRATIONS
else:
get_console().print(
"[error]You can only use `integration-core` or `integration-providers` test "
"group with `all-testable` integration."
)
sys.exit(1)
elif "all" in self.integration:
if self.test_group == GroupOfTests.CORE:
integrations = ALL_CORE_INTEGRATIONS
elif self.test_group == GroupOfTests.PROVIDERS:
integrations = ALL_PROVIDERS_INTEGRATIONS
else:
get_console().print(
"[error]You can only use `core` or `providers` test group with `all` integration."
)
sys.exit(1)
else:
integrations = self.integration
for integration in integrations:
get_console().print(f"[info]Adding integration compose file for {integration}[/]")
compose_file_list.append(SCRIPTS_CI_DOCKER_COMPOSE_PATH / f"integration-{integration}.yml")
if "trino" in integrations and "kerberos" not in integrations:
get_console().print(
"[warning]Adding `kerberos` integration as it is implicitly needed by trino",
)
compose_file_list.append(SCRIPTS_CI_DOCKER_COMPOSE_INTEGRATION_KERBEROS_PATH)
return os.pathsep.join([os.fspath(f) for f in compose_file_list])
@cached_property
def command_passed(self):
return str(self.extra_args[0]) if self.extra_args else None
@cached_property
def airflow_celery_broker_url(self) -> str:
if not self.celery_broker:
return ""
broker_url = CELERY_BROKER_URLS_MAP.get(self.celery_broker)
if not broker_url:
get_console().print(
f"[warning]The broker {self.celery_broker} should be one of {CELERY_BROKER_URLS_MAP.keys()}"
)
return ""
# Map from short form (rabbitmq/redis) to actual urls
return broker_url
@cached_property
def suspended_providers_folders(self):
from airflow_breeze.utils.packages import get_suspended_provider_folders
return " ".join(get_suspended_provider_folders()).strip()
def add_docker_in_docker(self, compose_file_list: list[Path]):
generated_compose_file = SCRIPTS_CI_DOCKER_COMPOSE_PATH / "_generated_docker_in_docker.yml"
unix_prefix = "unix://"
if self.docker_host:
if self.docker_host.startswith(unix_prefix):
# Socket is locally available
socket_path = Path(self.docker_host[len(unix_prefix) :])
if (
get_host_os() == "darwin"
and socket_path.resolve() == (Path.home() / ".docker" / "run" / "docker.sock").resolve()
):
# We are running on MacOS and the socket is the default "user" bound one
# We need to pretend that we are running on Linux and use the default socket
# in the VM instead - see https://github.com/docker/for-mac/issues/6545
compose_file_list.append(SCRIPTS_CI_DOCKER_COMPOSE_DOCKER_SOCKET_PATH)
return
if socket_path.is_socket():
generated_compose_file.write_text(generated_socket_compose_file(socket_path.as_posix()))
compose_file_list.append(generated_compose_file)
else:
get_console().print(
f"[warning]The socket {socket_path} pointed at by DOCKER_HOST does not exist or is "
"not a socket. Cannot use it for docker-compose for docker-in-docker forwarding[/]\n"
"[info]If you know where your socket is, you can set DOCKER_HOST "
"environment variable to unix://path_to_docker.sock[/]\n"
)
else:
# Socket is something different (TCP?) just pass it through as DOCKER_HOST variable
generated_compose_file.write_text(generated_docker_host_environment())
compose_file_list.append(generated_compose_file)
elif self.rootless_docker:
xdg_runtime_dir = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{get_host_user_id()}"))
socket_path = xdg_runtime_dir / "docker.sock"
if socket_path.is_socket():
generated_compose_file.write_text(generated_socket_compose_file(socket_path.as_posix()))
compose_file_list.append(generated_compose_file)
else:
get_console().print(
f"[warning]The socket {socket_path} does not exist or is not a socket. "
"Cannot use it for docker-compose for docker-in-docker forwarding[/]\n"
"[info]If you know where your socket is, you can set DOCKER_HOST environment variable "
"to unix://path_to_docker.sock[/]\n"
)
else:
# We fall back to default docker socket when no host is defined including MacOS
# NOTE! Even if we are using "desktop-linux" context where "/var/run/docker.sock" is not used,
# Docker engine works fine because "/var/run/docker.sock" is mounted at the VM and there
# the /var/run/docker.sock is available. See https://github.com/docker/for-mac/issues/6545
compose_file_list.append(SCRIPTS_CI_DOCKER_COMPOSE_DOCKER_SOCKET_PATH)
@cached_property
def rootless_docker(self) -> bool:
return is_docker_rootless()
@property
def env_variables_for_docker_commands(self) -> dict[str, str]:
"""
Constructs environment variables needed by the docker-compose command, based on Shell parameters
passed to it. We cannot cache this property because it can be run few times after modifying shell
params - for example when we first run "pull" on images before tests anda then run tests - each
separately with different test types.
This is the only place where you need to add environment variables if you want to pass them to
docker or docker-compose.
:return: dictionary of env variables to use for docker-compose and docker command
"""
_env: dict[str, str] = {}
_set_var(_env, "AIRFLOW_CI_IMAGE", self.airflow_image_name)
_set_var(_env, "AIRFLOW_CONSTRAINTS_LOCATION", self.airflow_constraints_location)
_set_var(_env, "AIRFLOW_CONSTRAINTS_MODE", self.airflow_constraints_mode)
_set_var(_env, "AIRFLOW_CONSTRAINTS_REFERENCE", self.airflow_constraints_reference)
_set_var(_env, "AIRFLOW_ENV", "development")
_set_var(_env, "AIRFLOW_EXTRAS", self.airflow_extras)
_set_var(_env, "AIRFLOW_IMAGE_KUBERNETES", self.airflow_image_kubernetes)
_set_var(_env, "AIRFLOW_VERSION", self.airflow_version)
_set_var(_env, "AIRFLOW__API_AUTH__JWT_SECRET", b64encode(os.urandom(16)).decode("utf-8"))
_set_var(_env, "AIRFLOW__CELERY__BROKER_URL", self.airflow_celery_broker_url)
_set_var(_env, "AIRFLOW__CORE__AUTH_MANAGER", self.auth_manager_path)
_set_var(_env, "AIRFLOW__CORE__EXECUTOR", self.executor)
if self.auth_manager == SIMPLE_AUTH_MANAGER:
_set_var(
_env, "AIRFLOW__CORE__SIMPLE_AUTH_MANAGER_USERS", "admin:admin,viewer:viewer,user:user,op:op"
)
_set_var(
_env,
"AIRFLOW__CORE__SIMPLE_AUTH_MANAGER_PASSWORDS_FILE",
"/opt/airflow/dev/breeze/src/airflow_breeze/files/simple_auth_manager_passwords.json",
)
_set_var(_env, "AIRFLOW__API__SECRET_KEY", b64encode(os.urandom(16)).decode("utf-8"))
if self.executor == EDGE_EXECUTOR:
_set_var(
_env,
"AIRFLOW__CORE__EXECUTOR",
"airflow.providers.edge3.executors.edge_executor.EdgeExecutor",
)
_set_var(_env, "AIRFLOW__EDGE__API_ENABLED", "true")
_set_var(
_env, "AIRFLOW__CORE__INTERNAL_API_SECRET_KEY", b64encode(os.urandom(16)).decode("utf-8")
)
# For testing Edge Worker on Windows... Default Run ID is having a colon (":") from the time which is
# made into the log path template, which then fails to be used in Windows. So we replace it with a dash
_set_var(
_env,
"AIRFLOW__LOGGING__LOG_FILENAME_TEMPLATE",
"dag_id={{ ti.dag_id }}/run_id={{ ti.run_id|replace(':', '-') }}/task_id={{ ti.task_id }}/"
"{% if ti.map_index >= 0 %}map_index={{ ti.map_index }}/{% endif %}"
"attempt={{ try_number|default(ti.try_number) }}.log",
)
port = 8080
_set_var(_env, "AIRFLOW__EDGE__API_URL", f"http://localhost:{port}/edge_worker/v1/rpcapi")
_set_var(_env, "ANSWER", get_forced_answer() or "")
_set_var(_env, "ALLOW_PRE_RELEASES", self.allow_pre_releases)
_set_var(_env, "BACKEND", self.backend)
_set_var(_env, "BASE_BRANCH", self.base_branch, "main")
_set_var(_env, "BREEZE", "true")
_set_var(_env, "BREEZE_INIT_COMMAND", None, "")
_set_var(_env, "CELERY_BROKER_URLS_MAP", CELERY_BROKER_URLS_MAP)
_set_var(_env, "CELERY_FLOWER", self.celery_flower)
_set_var(_env, "CLEAN_AIRFLOW_INSTALLATION", self.clean_airflow_installation)
_set_var(_env, "CI", None, "false")
_set_var(_env, "CI_BUILD_ID", None, "0")
_set_var(_env, "CI_EVENT_TYPE", None, GithubEvents.PULL_REQUEST.value)
_set_var(_env, "CI_JOB_ID", None, "0")
_set_var(_env, "CI_TARGET_BRANCH", self.airflow_branch)
_set_var(_env, "CI_TARGET_REPO", self.github_repository)
_set_var(_env, "COLLECT_ONLY", self.collect_only)
_set_var(_env, "CREATE_ALL_ROLES", self.create_all_roles)
_set_var(_env, "COMMIT_SHA", None, commit_sha())
_set_var(_env, "COMPOSE_FILE", self.compose_file)
_set_var(_env, "DB_RESET", self.db_reset)
_set_var(_env, "DEFAULT_BRANCH", self.airflow_branch)
_set_var(_env, "DEFAULT_CONSTRAINTS_BRANCH", self.default_constraints_branch)
_set_var(_env, "DEV_MODE", self.dev_mode)
_set_var(_env, "DOCKER_IS_ROOTLESS", self.rootless_docker)
_set_var(_env, "DOWNGRADE_SQLALCHEMY", self.downgrade_sqlalchemy)
_set_var(_env, "DOWNGRADE_PENDULUM", self.downgrade_pendulum)
_set_var(_env, "DRILL_HOST_PORT", None, DRILL_HOST_PORT)
_set_var(_env, "ENABLE_COVERAGE", self.enable_coverage)
_set_var(_env, "FLOWER_HOST_PORT", None, FLOWER_HOST_PORT)
_set_var(_env, "GREMLIN_HOST_PORT", None, GREMLIN_HOST_PORT)
_set_var(_env, "EXCLUDED_PROVIDERS", self.excluded_providers)
_set_var(_env, "FORCE_LOWEST_DEPENDENCIES", self.force_lowest_dependencies)
_set_var(_env, "SQLALCHEMY_WARN_20", self.force_sa_warnings)
_set_var(_env, "GITHUB_ACTIONS", self.github_actions)
_set_var(_env, "GITHUB_TOKEN", self.github_token)
_set_var(_env, "HOST_GROUP_ID", self.host_group_id)
_set_var(_env, "HOST_OS", self.host_os)
_set_var(_env, "HOST_USER_ID", self.host_user_id)
_set_var(_env, "INIT_SCRIPT_FILE", None, "init.sh")
_set_var(_env, "INSTALL_AIRFLOW_WITH_CONSTRAINTS", self.install_airflow_with_constraints)
_set_var(_env, "INSTALL_AIRFLOW_PYTHON_CLIENT", self.install_airflow_python_client)
_set_var(_env, "INSTALL_AIRFLOW_VERSION", self.install_airflow_version)
_set_var(_env, "INSTALL_SELECTED_PROVIDERS", self.install_selected_providers)
_set_var(_env, "ISSUE_ID", self.issue_id)
_set_var(_env, "LOAD_DEFAULT_CONNECTIONS", self.load_default_connections)
_set_var(_env, "LOAD_EXAMPLES", self.load_example_dags)
_set_var(_env, "MSSQL_HOST_PORT", None, MSSQL_HOST_PORT)
_set_var(_env, "MYSQL_HOST_PORT", None, MYSQL_HOST_PORT)
_set_var(_env, "MYSQL_VERSION", self.mysql_version)
_set_var(_env, "MOUNT_SOURCES", self.mount_sources)
_set_var(_env, "NUM_RUNS", self.num_runs)
_set_var(_env, "ONLY_MIN_VERSION_UPDATE", self.only_min_version_update)
_set_var(_env, "DISTRIBUTION_FORMAT", self.distribution_format)
_set_var(_env, "POSTGRES_HOST_PORT", None, POSTGRES_HOST_PORT)
_set_var(_env, "POSTGRES_VERSION", self.postgres_version)
_set_var(_env, "PROVIDERS_CONSTRAINTS_LOCATION", self.providers_constraints_location)
_set_var(_env, "PROVIDERS_CONSTRAINTS_MODE", self.providers_constraints_mode)
_set_var(_env, "PROVIDERS_CONSTRAINTS_REFERENCE", self.providers_constraints_reference)
_set_var(_env, "PROVIDERS_SKIP_CONSTRAINTS", self.providers_skip_constraints)
_set_var(_env, "PYTHONDONTWRITEBYTECODE", "true")
_set_var(_env, "PYTHONWARNINGS", None, None)
_set_var(_env, "PYTHON_MAJOR_MINOR_VERSION", self.python)
_set_var(_env, "QUIET", self.quiet)
_set_var(_env, "REDIS_HOST_PORT", None, REDIS_HOST_PORT)
_set_var(_env, "RABBITMQ_HOST_PORT", None, RABBITMQ_HOST_PORT)
_set_var(_env, "REGENERATE_MISSING_DOCS", self.regenerate_missing_docs)
_set_var(_env, "RUN_TESTS", self.run_tests)
_set_var(_env, "SKIP_ENVIRONMENT_INITIALIZATION", self.skip_environment_initialization)
_set_var(_env, "SKIP_SSH_SETUP", self.skip_ssh_setup)
_set_var(_env, "SQLITE_URL", self.sqlite_url)
_set_var(_env, "SSH_PORT", None, SSH_PORT)
_set_var(_env, "STANDALONE_DAG_PROCESSOR", self.standalone_dag_processor)
_set_var(_env, "START_AIRFLOW", self.start_airflow)
_set_var(_env, "USE_MPROCS", self.use_mprocs)
_set_var(_env, "SUSPENDED_PROVIDERS_FOLDERS", self.suspended_providers_folders)
_set_var(
_env,
"START_API_SERVER_WITH_EXAMPLES",
self.start_api_server_with_examples,
)
_set_var(_env, "SYSTEM_TESTS_ENV_ID", None, "")
_set_var(_env, "TEST_TYPE", self.test_type, "")
_set_var(_env, "TEST_GROUP", str(self.test_group.value) if self.test_group else "")
_set_var(_env, "UPGRADE_BOTO", self.upgrade_boto)
_set_var(_env, "UPGRADE_SQLALCHEMY", self.upgrade_sqlalchemy)
_set_var(_env, "USE_AIRFLOW_VERSION", self.use_airflow_version, "")
_set_var(_env, "USE_DISTRIBUTIONS_FROM_DIST", self.use_distributions_from_dist)
_set_var(_env, "USE_UV", self.use_uv)
_set_var(_env, "USE_XDIST", self.use_xdist)
_set_var(_env, "VERBOSE", get_verbose())
_set_var(_env, "VERBOSE_COMMANDS", self.verbose_commands)
_set_var(_env, "VERSION_SUFFIX", self.version_suffix)
_set_var(_env, "WEB_HOST_PORT", None, WEB_HOST_PORT)
_set_var(_env, "_AIRFLOW_RUN_DB_TESTS_ONLY", self.run_db_tests_only)
_set_var(_env, "_AIRFLOW_SKIP_DB_TESTS", self.skip_db_tests)
self._set_debug_variables(_env)
self._generate_env_for_docker_compose_file_if_needed(_env)
_target_env: dict[str, str] = os.environ.copy()
_target_env.update(_env)
return _target_env
def _set_debug_variables(self, env) -> None:
"""Set debug environment variables based on selected debug components."""
if self.debugger == "pydevd-pycharm":
print("Pycharm-pydevd debugger is under development and not yet supported in Breeze.")
return
if not self.debug_components:
return
_set_var(env, "BREEZE_DEBUG_SCHEDULER_PORT", None, BREEZE_DEBUG_SCHEDULER_PORT)
_set_var(env, "BREEZE_DEBUG_DAG_PROCESSOR_PORT", None, BREEZE_DEBUG_DAG_PROCESSOR_PORT)
_set_var(env, "BREEZE_DEBUG_TRIGGERER_PORT", None, BREEZE_DEBUG_TRIGGERER_PORT)
_set_var(env, "BREEZE_DEBUG_APISERVER_PORT", None, BREEZE_DEBUG_APISERVER_PORT)
_set_var(env, "BREEZE_DEBUG_CELERY_WORKER_PORT", None, BREEZE_DEBUG_CELERY_WORKER_PORT)
_set_var(env, "BREEZE_DEBUG_EDGE_PORT", None, BREEZE_DEBUG_EDGE_PORT)
_set_var(env, "BREEZE_DEBUG_WEBSERVER_PORT", None, BREEZE_DEBUG_WEBSERVER_PORT)
_set_var(env, "BREEZE_DEBUGGER", None, self.debugger)
component_mappings = {
"scheduler": "BREEZE_DEBUG_SCHEDULER",
"triggerer": "BREEZE_DEBUG_TRIGGERER",
"api-server": "BREEZE_DEBUG_APISERVER",
"dag-processor": "BREEZE_DEBUG_DAG_PROCESSOR",
"edge-worker": "BREEZE_DEBUG_EDGE",
"celery-worker": "BREEZE_DEBUG_CELERY_WORKER",
}
for component in self.debug_components:
env_var = component_mappings[component]
_set_var(env, env_var, None, "true")
@staticmethod
def _generate_env_for_docker_compose_file_if_needed(env: dict[str, str]):
"""
Generates docker-compose env file if needed.
:param env: dictionary of env variables to use for docker-compose and docker env files.
Writes env files for docker and docker compose to make sure the envs will be passed
to docker-compose/docker when running commands.
The list of variables might change over time, and we want to keep the list updated only in
one place (above env_variables_for_docker_commands method). So we need to regenerate the env
files automatically when new variable is added to the list or removed.
Docker-Compose based tests can start in parallel, so we want to make sure we generate it once
per invocation of breeze command otherwise there could be nasty race condition that
the file would be empty while another compose tries to use it when starting.
Also, it means that we need to pass the values through environment rather than writing
them to the file directly, because they might differ between different parallel runs
of compose or docker.
Unfortunately docker and docker-compose do not share the same env files any more as of Compose V2
format for passing variables from the environment, so we need to generate both files.
Documentation is a bit vague about this.
The docker file contain simply list of all variables that should be passed to docker.
See https://docs.docker.com/engine/reference/commandline/run/#env
> When running the command, the Docker CLI client checks the value the variable has in
> your local environment and passes it to the container. If no = is provided and that
> variable is not exported in your local environment, the variable isn't set in the container.
The docker-compose file should instead contain VARIABLE=${VARIABLE} for each variable
that should be passed to docker compose.
From https://docs.docker.com/compose/compose-file/05-services/#env_file
> VAL may be omitted, in such cases the variable value is an empty string. =VAL may be omitted,
> in such cases the variable is unset.
"""
from filelock import FileLock
with FileLock(GENERATED_DOCKER_LOCK_PATH):
if GENERATED_DOCKER_ENV_PATH.exists():
generated_keys = GENERATED_DOCKER_ENV_PATH.read_text().splitlines()
if set(env.keys()) == set(generated_keys):
# we check if the set of env variables had not changed since last run
# if so - cool, we do not need to do anything else
return
if get_verbose():
get_console().print(
f"[info]The keys has changed vs last run. Regenerating[/]: "
f"{GENERATED_DOCKER_ENV_PATH} and {GENERATED_DOCKER_COMPOSE_ENV_PATH}"
)
if get_verbose():
get_console().print(f"[info]Generating new docker env file [/]: {GENERATED_DOCKER_ENV_PATH}")
GENERATED_DOCKER_ENV_PATH.write_text("\n".join(sorted(env.keys())))
if get_verbose():
get_console().print(
f"[info]Generating new docker compose env file [/]: {GENERATED_DOCKER_COMPOSE_ENV_PATH}"
)
GENERATED_DOCKER_COMPOSE_ENV_PATH.write_text(
"\n".join([f"{k}=${{{k}}}" for k in sorted(env.keys())])
)
def __post_init__(self):
if self.airflow_constraints_reference == "default":
self.airflow_constraints_reference = self.default_constraints_branch
if self.providers_constraints_reference == "default":
self.providers_constraints_reference = self.default_constraints_branch
if (
self.backend
and self.integration
and KEYCLOAK_INTEGRATION in self.integration
and not self.backend == POSTGRES_BACKEND
):
get_console().print(
"[error]When using the Keycloak integration the backend must be Postgres![/]\n"
)
sys.exit(2)
| ShellParams |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1038425,
"end": 1038924
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of UpdateProjectV2ItemFieldValue"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "project_v2_item")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
project_v2_item = sgqlc.types.Field("ProjectV2Item", graphql_name="projectV2Item")
"""The updated item."""
| UpdateProjectV2ItemFieldValuePayload |
python | getsentry__sentry | src/sentry/tasks/assemble.py | {
"start": 10602,
"end": 27474
} | class ____:
def __init__(
self,
assemble_result: AssembleResult,
organization: Organization,
release: str | None,
dist: str | None,
project_ids: list[int],
is_release_bundle_migration: bool = False,
):
self.assemble_result = assemble_result
self._validate_bundle_guarded()
self.organization = organization
self.release = release
self.dist = dist
self.project_ids = project_ids
self.is_release_bundle_migration = is_release_bundle_migration
def _validate_bundle_guarded(self):
try:
self._validate_bundle()
except Exception:
metrics.incr("tasks.assemble.invalid_bundle")
# In case the bundle is invalid, we want to delete the actual `File` object created in the database, to
# avoid orphan entries.
self.delete_bundle_file_object()
raise AssembleArtifactsError("the bundle is invalid")
def _validate_bundle(self):
self.archive = ArtifactBundleArchive(self.assemble_result.bundle_temp_file)
metrics.incr(
"tasks.assemble.artifact_bundle.artifact_count", amount=self.archive.artifact_count
)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# In case any exception happens in the `with` block, we will capture it, and we want to delete the actual `File`
# object created in the database, to avoid orphan entries.
if exc_type is not None:
self.delete_bundle_file_object()
self.archive.close()
def delete_bundle_file_object(self):
self.assemble_result.delete_bundle()
def post_assemble(self):
if self.archive.artifact_count == 0:
metrics.incr("tasks.assemble.artifact_bundle.discarded_empty_bundle")
self.delete_bundle_file_object()
return
with metrics.timer("tasks.assemble.artifact_bundle"):
self._create_artifact_bundle()
@sentry_sdk.tracing.trace
def _create_artifact_bundle(self) -> None:
# We want to give precedence to the request fields and only if they are unset fallback to the manifest's
# contents.
self.release = self.release or self.archive.manifest.get("release")
self.dist = self.dist or self.archive.manifest.get("dist")
# In case we have a release bundle migration, we are fetching *all*
# the projects associated with a release, which can be quite a lot.
# We rather use the `project` of the bundle manifest instead.
if len(self.project_ids) > 2 and self.is_release_bundle_migration:
if project_in_manifest := self.archive.manifest.get("project"):
project_ids = list(
Project.objects.filter(
organization=self.organization,
status=ObjectStatus.ACTIVE,
slug=project_in_manifest,
).values_list("id", flat=True)
)
if len(project_ids) > 0:
self.project_ids = project_ids
bundle_id = self.archive.extract_bundle_id()
if not bundle_id:
# In case we didn't find the bundle_id in the manifest, we will just generate our own.
bundle_id = ArtifactBundleArchive.normalize_debug_id(
self.assemble_result.bundle.checksum
)
# When normalizing the debug_id from the checksum, or even when reading it from the bundle,
# the debug_id can have an additional appendix which we want to remove as it is
# incompatible with the SQL `uuid` type, which expects this to be a 16-byte UUID,
# formatted with `-` to 36 chars.
bundle_id = bundle_id[:36] if bundle_id else uuid.uuid4().hex
# We don't allow the creation of a bundle if no debug ids and release are present, since we are not able to
# efficiently index
if not self.archive.has_debug_ids() and not self.release:
raise AssembleArtifactsError(
"uploading a bundle without debug ids or release is prohibited"
)
# We take a snapshot in time in order to have consistent values in the database.
date_snapshot = timezone.now()
# We have to add this dictionary to both `values` and `defaults` since we want to update the date_added in
# case of a re-upload because the `date_added` of the ArtifactBundle is also updated.
new_date_added = {"date_added": date_snapshot}
# We want to run everything in a transaction, since we don't want the database to be in an inconsistent
# state after all of these updates.
with atomic_transaction(
using=(
router.db_for_write(ArtifactBundle),
router.db_for_write(File),
router.db_for_write(ReleaseArtifactBundle),
router.db_for_write(ProjectArtifactBundle),
router.db_for_write(DebugIdArtifactBundle),
)
):
artifact_bundle, created = self._create_or_update_artifact_bundle(
bundle_id=bundle_id, date_added=date_snapshot
)
# If a release version is passed, we want to create the weak association between a bundle and a release.
if self.release:
ReleaseArtifactBundle.objects.create_or_update(
organization_id=self.organization.id,
release_name=self.release,
# In case no dist is provided, we will fall back to "" which is the NULL equivalent for our
# tables.
dist_name=self.dist or NULL_STRING,
artifact_bundle=artifact_bundle,
values=new_date_added,
defaults=new_date_added,
)
for project_id in self.project_ids:
ProjectArtifactBundle.objects.create_or_update(
organization_id=self.organization.id,
project_id=project_id,
artifact_bundle=artifact_bundle,
values=new_date_added,
defaults=new_date_added,
)
# Instead of doing a `create_or_update` one-by-one, we will instead:
# - Use a `bulk_create` with `ignore_conflicts` to insert new rows efficiently
# if the artifact bundle was newly inserted. This is based on the assumption
# that the `bundle_id` is deterministic and the `created` flag signals that
# this identical bundle was already inserted.
# - Otherwise, update all the affected/conflicting rows with a single query.
if created:
debug_id_to_insert = [
DebugIdArtifactBundle(
organization_id=self.organization.id,
debug_id=debug_id,
artifact_bundle=artifact_bundle,
source_file_type=source_file_type.value,
date_added=date_snapshot,
)
for debug_id, source_file_type in self.archive.get_all_debug_ids()
]
DebugIdArtifactBundle.objects.bulk_create(
debug_id_to_insert, batch_size=50, ignore_conflicts=True
)
else:
DebugIdArtifactBundle.objects.filter(
organization_id=self.organization.id,
artifact_bundle=artifact_bundle,
).update(date_added=date_snapshot)
metrics.incr("sourcemaps.upload.artifact_bundle")
# If we don't have a release set, we don't want to run indexing, since we need at least the release for
# fast indexing performance. We might though run indexing if a customer has debug ids in the manifest, since
# we want to have a fallback mechanism in case they have problems setting them up (e.g., SDK version does
# not support them, some files were not injected...).
if created and self.release:
# After we committed the transaction we want to try and run indexing by passing non-null release and
# dist. The dist here can be "" since it will be the equivalent of NULL for the db query.
self._index_bundle_if_needed(
artifact_bundle,
release=self.release,
dist=(self.dist or NULL_STRING),
)
@sentry_sdk.tracing.trace
def _create_or_update_artifact_bundle(
self, bundle_id: str, date_added: datetime
) -> tuple[ArtifactBundle, bool]:
existing_artifact_bundles = list(
ArtifactBundle.objects.filter(organization_id=self.organization.id, bundle_id=bundle_id)
)
if len(existing_artifact_bundles) == 0:
existing_artifact_bundle = None
else:
existing_artifact_bundle = existing_artifact_bundles.pop()
# We want to remove all the duplicate artifact bundles that have the same bundle_id.
self._remove_duplicate_artifact_bundles(
ids=list(map(lambda value: value.id, existing_artifact_bundles))
)
# In case there is not ArtifactBundle with a specific bundle_id, we just create it and return.
if existing_artifact_bundle is None:
file = self.assemble_result.bundle
metrics.distribution(
"storage.put.size",
file.size,
tags={"usecase": "artifact-bundles", "compression": "none"},
unit="byte",
)
artifact_bundle = ArtifactBundle.objects.create(
organization_id=self.organization.id,
bundle_id=bundle_id,
file=file,
artifact_count=self.archive.artifact_count,
# By default, a bundle is not indexed.
indexing_state=ArtifactBundleIndexingState.NOT_INDEXED.value,
# "date_added" and "date_uploaded" will have the same value, but they will diverge once renewal is
# performed by other parts of Sentry. Renewal is required since we want to expire unused bundles
# after ~90 days.
date_added=date_added,
date_uploaded=date_added,
# When creating a new bundle by default its last modified date corresponds to the creation date.
date_last_modified=date_added,
)
return artifact_bundle, True
else:
# We store a reference to the previous file to which the bundle was pointing to.
existing_file = existing_artifact_bundle.file
# FIXME: We might want to get this error, but it currently blocks deploys
# if existing_file.checksum != self.assemble_result.bundle.checksum:
# logger.error("Detected duplicated `ArtifactBundle` with differing checksums")
# Only if the file objects are different we want to update the database, otherwise we will end up deleting
# a newly bound file.
if existing_file != self.assemble_result.bundle:
# In case there is an ArtifactBundle with a specific bundle_id, we want to change its underlying File
# model with its corresponding artifact count and also update the dates.
existing_artifact_bundle.update(
file=self.assemble_result.bundle,
artifact_count=self.archive.artifact_count,
date_added=date_added,
# If you upload a bundle which already exists, we track this as a modification since our goal is
# to show first all the bundles that have had the most recent activity.
date_last_modified=date_added,
)
# We now delete that file, in order to avoid orphan files in the database.
existing_file.delete()
# else: are we leaking the `assemble_result.bundle` in this case?
return existing_artifact_bundle, False
def _remove_duplicate_artifact_bundles(self, ids: list[int]):
# In case there are no ids to delete, we don't want to run the query, otherwise it will result in a deletion of
# all ArtifactBundle(s) with the specific bundle_id.
if not ids:
return
# Even though we delete via a QuerySet the associated file is also deleted, because django will still
# fire the on_delete signal.
ArtifactBundle.objects.filter(Q(id__in=ids), organization_id=self.organization.id).delete()
@sentry_sdk.tracing.trace
def _index_bundle_if_needed(self, artifact_bundle: ArtifactBundle, release: str, dist: str):
# We collect how many times we tried to perform indexing.
metrics.incr("tasks.assemble.artifact_bundle.try_indexing")
(total_bundles, indexed_bundles) = get_bundles_indexing_state(
self.organization, release, dist
)
# In case we didn't surpass the threshold, indexing will not happen.
if total_bundles < INDEXING_THRESHOLD:
return
# We collect how many times we run indexing.
metrics.incr("tasks.assemble.artifact_bundle.start_indexing")
# We want to measure how much time it takes to perform indexing.
with metrics.timer("tasks.assemble.artifact_bundle.index_bundles"):
# NOTE: this is doing a try/catch internally
index_artifact_bundles_for_release(
organization_id=self.organization.id,
artifact_bundles=[(artifact_bundle, self.archive)],
)
# Backfill older bundles we did not index yet if any are missing
if indexed_bundles + 1 < total_bundles:
backfill_artifact_bundle_db_indexing.delay(self.organization.id, release, dist)
@instrumented_task(
name="sentry.tasks.assemble.assemble_artifacts",
namespace=attachments_tasks,
processing_deadline_duration=30,
silo_mode=SiloMode.REGION,
)
def assemble_artifacts(
org_id,
version,
checksum,
chunks,
# These params have been added for supporting artifact bundles assembling.
project_ids=None,
dist=None,
is_release_bundle_migration=False,
**kwargs,
) -> None:
"""
Creates a release file or artifact bundle from an uploaded bundle given the checksums of its chunks.
"""
try:
organization = Organization.objects.get_from_cache(pk=org_id)
bind_organization_context(organization)
set_assemble_status(
AssembleTask.ARTIFACT_BUNDLE, org_id, checksum, ChunkFileState.ASSEMBLING
)
# Assemble the chunks into a temporary file
assemble_result = assemble_file(
task=AssembleTask.ARTIFACT_BUNDLE,
org_or_project=organization,
name=f"bundle-artifacts-{uuid.uuid4().hex}.zip",
checksum=checksum,
chunks=chunks,
file_type="artifact.bundle",
)
# If not file has been created this means that the file failed to assemble because of bad input data.
# In this case, assemble_file has set the assemble status already.
if assemble_result is None:
return
if not project_ids:
raise AssembleArtifactsError(
"uploading an artifact bundle without a project is prohibited"
)
# We first want to prepare the post assembler which will take care of validating the archive.
post_assembler = ArtifactBundlePostAssembler(
assemble_result=assemble_result,
organization=organization,
release=version,
dist=dist,
project_ids=project_ids,
is_release_bundle_migration=is_release_bundle_migration,
)
with post_assembler:
# Once the archive is valid, the post assembler can run the post assembling job.
post_assembler.post_assemble()
except AssembleArtifactsError as e:
set_assemble_status(
AssembleTask.ARTIFACT_BUNDLE, org_id, checksum, ChunkFileState.ERROR, detail=str(e)
)
except Exception as e:
logger.exception("failed to assemble bundle")
sentry_sdk.capture_exception(e)
set_assemble_status(
AssembleTask.ARTIFACT_BUNDLE,
org_id,
checksum,
ChunkFileState.ERROR,
detail="internal server error",
)
else:
set_assemble_status(AssembleTask.ARTIFACT_BUNDLE, org_id, checksum, ChunkFileState.OK)
| ArtifactBundlePostAssembler |
python | scikit-learn__scikit-learn | sklearn/discriminant_analysis.py | {
"start": 8494,
"end": 29777
} | class ____(
ClassNamePrefixFeaturesOutMixin,
LinearClassifierMixin,
TransformerMixin,
BaseEstimator,
):
"""Linear Discriminant Analysis.
A classifier with a linear decision boundary, generated by fitting class
conditional densities to the data and using Bayes' rule.
The model fits a Gaussian density to each class, assuming that all classes
share the same covariance matrix.
The fitted model can also be used to reduce the dimensionality of the input
by projecting it to the most discriminative directions, using the
`transform` method.
.. versionadded:: 0.17
For a comparison between
:class:`~sklearn.discriminant_analysis.LinearDiscriminantAnalysis`
and :class:`~sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis`, see
:ref:`sphx_glr_auto_examples_classification_plot_lda_qda.py`.
Read more in the :ref:`User Guide <lda_qda>`.
Parameters
----------
solver : {'svd', 'lsqr', 'eigen'}, default='svd'
Solver to use, possible values:
- 'svd': Singular value decomposition (default).
Does not compute the covariance matrix, therefore this solver is
recommended for data with a large number of features.
- 'lsqr': Least squares solution.
Can be combined with shrinkage or custom covariance estimator.
- 'eigen': Eigenvalue decomposition.
Can be combined with shrinkage or custom covariance estimator.
.. versionchanged:: 1.2
`solver="svd"` now has experimental Array API support. See the
:ref:`Array API User Guide <array_api>` for more details.
shrinkage : 'auto' or float, default=None
Shrinkage parameter, possible values:
- None: no shrinkage (default).
- 'auto': automatic shrinkage using the Ledoit-Wolf lemma.
- float between 0 and 1: fixed shrinkage parameter.
This should be left to None if `covariance_estimator` is used.
Note that shrinkage works only with 'lsqr' and 'eigen' solvers.
For a usage example, see
:ref:`sphx_glr_auto_examples_classification_plot_lda.py`.
priors : array-like of shape (n_classes,), default=None
The class prior probabilities. By default, the class proportions are
inferred from the training data.
n_components : int, default=None
Number of components (<= min(n_classes - 1, n_features)) for
dimensionality reduction. If None, will be set to
min(n_classes - 1, n_features). This parameter only affects the
`transform` method.
For a usage example, see
:ref:`sphx_glr_auto_examples_decomposition_plot_pca_vs_lda.py`.
store_covariance : bool, default=False
If True, explicitly compute the weighted within-class covariance
matrix when solver is 'svd'. The matrix is always computed
and stored for the other solvers.
.. versionadded:: 0.17
tol : float, default=1.0e-4
Absolute threshold for a singular value of X to be considered
significant, used to estimate the rank of X. Dimensions whose
singular values are non-significant are discarded. Only used if
solver is 'svd'.
.. versionadded:: 0.17
covariance_estimator : covariance estimator, default=None
If not None, `covariance_estimator` is used to estimate
the covariance matrices instead of relying on the empirical
covariance estimator (with potential shrinkage).
The object should have a fit method and a ``covariance_`` attribute
like the estimators in :mod:`sklearn.covariance`.
if None the shrinkage parameter drives the estimate.
This should be left to None if `shrinkage` is used.
Note that `covariance_estimator` works only with 'lsqr' and 'eigen'
solvers.
.. versionadded:: 0.24
Attributes
----------
coef_ : ndarray of shape (n_features,) or (n_classes, n_features)
Weight vector(s).
intercept_ : ndarray of shape (n_classes,)
Intercept term.
covariance_ : array-like of shape (n_features, n_features)
Weighted within-class covariance matrix. It corresponds to
`sum_k prior_k * C_k` where `C_k` is the covariance matrix of the
samples in class `k`. The `C_k` are estimated using the (potentially
shrunk) biased estimator of covariance. If solver is 'svd', only
exists when `store_covariance` is True.
explained_variance_ratio_ : ndarray of shape (n_components,)
Percentage of variance explained by each of the selected components.
If ``n_components`` is not set then all components are stored and the
sum of explained variances is equal to 1.0. Only available when eigen
or svd solver is used.
means_ : array-like of shape (n_classes, n_features)
Class-wise means.
priors_ : array-like of shape (n_classes,)
Class priors (sum to 1).
scalings_ : array-like of shape (rank, n_classes - 1)
Scaling of the features in the space spanned by the class centroids.
Only available for 'svd' and 'eigen' solvers.
xbar_ : array-like of shape (n_features,)
Overall mean. Only present if solver is 'svd'.
classes_ : array-like of shape (n_classes,)
Unique class labels.
n_features_in_ : int
Number of features seen during :term:`fit`.
.. versionadded:: 0.24
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
.. versionadded:: 1.0
See Also
--------
QuadraticDiscriminantAnalysis : Quadratic Discriminant Analysis.
Examples
--------
>>> import numpy as np
>>> from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> y = np.array([1, 1, 1, 2, 2, 2])
>>> clf = LinearDiscriminantAnalysis()
>>> clf.fit(X, y)
LinearDiscriminantAnalysis()
>>> print(clf.predict([[-0.8, -1]]))
[1]
"""
_parameter_constraints: dict = {
"solver": [StrOptions({"svd", "lsqr", "eigen"})],
"shrinkage": [StrOptions({"auto"}), Interval(Real, 0, 1, closed="both"), None],
"n_components": [Interval(Integral, 1, None, closed="left"), None],
"priors": ["array-like", None],
"store_covariance": ["boolean"],
"tol": [Interval(Real, 0, None, closed="left")],
"covariance_estimator": [HasMethods("fit"), None],
}
def __init__(
self,
solver="svd",
shrinkage=None,
priors=None,
n_components=None,
store_covariance=False,
tol=1e-4,
covariance_estimator=None,
):
self.solver = solver
self.shrinkage = shrinkage
self.priors = priors
self.n_components = n_components
self.store_covariance = store_covariance # used only in svd solver
self.tol = tol # used only in svd solver
self.covariance_estimator = covariance_estimator
def _solve_lstsq(self, X, y, shrinkage, covariance_estimator):
"""Least squares solver.
The least squares solver computes a straightforward solution of the
optimal decision rule based directly on the discriminant functions. It
can only be used for classification (with any covariance estimator),
because
estimation of eigenvectors is not performed. Therefore, dimensionality
reduction with the transform is not supported.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data.
y : array-like of shape (n_samples,) or (n_samples, n_classes)
Target values.
shrinkage : 'auto', float or None
Shrinkage parameter, possible values:
- None: no shrinkage.
- 'auto': automatic shrinkage using the Ledoit-Wolf lemma.
- float between 0 and 1: fixed shrinkage parameter.
Shrinkage parameter is ignored if `covariance_estimator` is
not None
covariance_estimator : estimator, default=None
If not None, `covariance_estimator` is used to estimate
the covariance matrices instead of relying the empirical
covariance estimator (with potential shrinkage).
The object should have a fit method and a ``covariance_`` attribute
like the estimators in sklearn.covariance.
if None the shrinkage parameter drives the estimate.
.. versionadded:: 0.24
Notes
-----
This solver is based on [1]_, section 2.6.2, pp. 39-41.
References
----------
.. [1] R. O. Duda, P. E. Hart, D. G. Stork. Pattern Classification
(Second Edition). John Wiley & Sons, Inc., New York, 2001. ISBN
0-471-05669-3.
"""
self.means_ = _class_means(X, y)
self.covariance_ = _class_cov(
X, y, self.priors_, shrinkage, covariance_estimator
)
self.coef_ = linalg.lstsq(self.covariance_, self.means_.T)[0].T
self.intercept_ = -0.5 * np.diag(np.dot(self.means_, self.coef_.T)) + np.log(
self.priors_
)
def _solve_eigen(self, X, y, shrinkage, covariance_estimator):
"""Eigenvalue solver.
The eigenvalue solver computes the optimal solution of the Rayleigh
coefficient (basically the ratio of between class scatter to within
class scatter). This solver supports both classification and
dimensionality reduction (with any covariance estimator).
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data.
y : array-like of shape (n_samples,) or (n_samples, n_targets)
Target values.
shrinkage : 'auto', float or None
Shrinkage parameter, possible values:
- None: no shrinkage.
- 'auto': automatic shrinkage using the Ledoit-Wolf lemma.
- float between 0 and 1: fixed shrinkage constant.
Shrinkage parameter is ignored if `covariance_estimator` is
not None
covariance_estimator : estimator, default=None
If not None, `covariance_estimator` is used to estimate
the covariance matrices instead of relying the empirical
covariance estimator (with potential shrinkage).
The object should have a fit method and a ``covariance_`` attribute
like the estimators in sklearn.covariance.
if None the shrinkage parameter drives the estimate.
.. versionadded:: 0.24
Notes
-----
This solver is based on [1]_, section 3.8.3, pp. 121-124.
References
----------
.. [1] R. O. Duda, P. E. Hart, D. G. Stork. Pattern Classification
(Second Edition). John Wiley & Sons, Inc., New York, 2001. ISBN
0-471-05669-3.
"""
self.means_ = _class_means(X, y)
self.covariance_ = _class_cov(
X, y, self.priors_, shrinkage, covariance_estimator
)
Sw = self.covariance_ # within scatter
St = _cov(X, shrinkage, covariance_estimator) # total scatter
Sb = St - Sw # between scatter
evals, evecs = linalg.eigh(Sb, Sw)
self.explained_variance_ratio_ = np.sort(evals / np.sum(evals))[::-1][
: self._max_components
]
evecs = evecs[:, np.argsort(evals)[::-1]] # sort eigenvectors
self.scalings_ = evecs
self.coef_ = np.dot(self.means_, evecs).dot(evecs.T)
self.intercept_ = -0.5 * np.diag(np.dot(self.means_, self.coef_.T)) + np.log(
self.priors_
)
def _solve_svd(self, X, y):
"""SVD solver.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data.
y : array-like of shape (n_samples,) or (n_samples, n_targets)
Target values.
"""
xp, is_array_api_compliant = get_namespace(X)
if is_array_api_compliant:
svd = xp.linalg.svd
else:
svd = scipy.linalg.svd
n_samples, _ = X.shape
n_classes = self.classes_.shape[0]
self.means_ = _class_means(X, y)
if self.store_covariance:
self.covariance_ = _class_cov(X, y, self.priors_)
Xc = []
for idx, group in enumerate(self.classes_):
Xg = X[y == group]
Xc.append(Xg - self.means_[idx, :])
self.xbar_ = self.priors_ @ self.means_
Xc = xp.concat(Xc, axis=0)
# 1) within (univariate) scaling by with classes std-dev
std = xp.std(Xc, axis=0)
# avoid division by zero in normalization
std[std == 0] = 1.0
fac = xp.asarray(1.0 / (n_samples - n_classes), dtype=X.dtype, device=device(X))
# 2) Within variance scaling
X = xp.sqrt(fac) * (Xc / std)
# SVD of centered (within)scaled data
_, S, Vt = svd(X, full_matrices=False)
rank = xp.sum(xp.astype(S > self.tol, xp.int32))
# Scaling of within covariance is: V' 1/S
scalings = (Vt[:rank, :] / std).T / S[:rank]
fac = 1.0 if n_classes == 1 else 1.0 / (n_classes - 1)
# 3) Between variance scaling
# Scale weighted centers
X = (
(xp.sqrt((n_samples * self.priors_) * fac)) * (self.means_ - self.xbar_).T
).T @ scalings
# Centers are living in a space with n_classes-1 dim (maximum)
# Use SVD to find projection in the space spanned by the
# (n_classes) centers
_, S, Vt = svd(X, full_matrices=False)
if self._max_components == 0:
self.explained_variance_ratio_ = xp.empty((0,), dtype=S.dtype)
else:
self.explained_variance_ratio_ = (S**2 / xp.sum(S**2))[
: self._max_components
]
rank = xp.sum(xp.astype(S > self.tol * S[0], xp.int32))
self.scalings_ = scalings @ Vt.T[:, :rank]
coef = (self.means_ - self.xbar_) @ self.scalings_
self.intercept_ = -0.5 * xp.sum(coef**2, axis=1) + xp.log(self.priors_)
self.coef_ = coef @ self.scalings_.T
self.intercept_ -= self.xbar_ @ self.coef_.T
@_fit_context(
# LinearDiscriminantAnalysis.covariance_estimator is not validated yet
prefer_skip_nested_validation=False
)
def fit(self, X, y):
"""Fit the Linear Discriminant Analysis model.
.. versionchanged:: 0.19
`store_covariance` and `tol` has been moved to main constructor.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data.
y : array-like of shape (n_samples,)
Target values.
Returns
-------
self : object
Fitted estimator.
"""
xp, _ = get_namespace(X)
X, y = validate_data(
self, X, y, ensure_min_samples=2, dtype=[xp.float64, xp.float32]
)
self.classes_ = unique_labels(y)
n_samples, n_features = X.shape
n_classes = self.classes_.shape[0]
if n_samples == n_classes:
raise ValueError(
"The number of samples must be more than the number of classes."
)
if self.priors is None: # estimate priors from sample
_, cnts = xp.unique_counts(y) # non-negative ints
self.priors_ = xp.astype(cnts, X.dtype) / float(n_samples)
else:
self.priors_ = xp.asarray(self.priors, dtype=X.dtype)
if xp.any(self.priors_ < 0):
raise ValueError("priors must be non-negative")
if xp.abs(xp.sum(self.priors_) - 1.0) > 1e-5:
warnings.warn("The priors do not sum to 1. Renormalizing", UserWarning)
self.priors_ = self.priors_ / self.priors_.sum()
# Maximum number of components no matter what n_components is
# specified:
max_components = min(n_classes - 1, n_features)
if self.n_components is None:
self._max_components = max_components
else:
if self.n_components > max_components:
raise ValueError(
"n_components cannot be larger than min(n_features, n_classes - 1)."
)
self._max_components = self.n_components
if self.solver == "svd":
if self.shrinkage is not None:
raise NotImplementedError("shrinkage not supported with 'svd' solver.")
if self.covariance_estimator is not None:
raise ValueError(
"covariance estimator "
"is not supported "
"with svd solver. Try another solver"
)
self._solve_svd(X, y)
elif self.solver == "lsqr":
self._solve_lstsq(
X,
y,
shrinkage=self.shrinkage,
covariance_estimator=self.covariance_estimator,
)
elif self.solver == "eigen":
self._solve_eigen(
X,
y,
shrinkage=self.shrinkage,
covariance_estimator=self.covariance_estimator,
)
if size(self.classes_) == 2: # treat binary case as a special case
coef_ = xp.asarray(self.coef_[1, :] - self.coef_[0, :], dtype=X.dtype)
self.coef_ = xp.reshape(coef_, (1, -1))
intercept_ = xp.asarray(
self.intercept_[1] - self.intercept_[0], dtype=X.dtype
)
self.intercept_ = xp.reshape(intercept_, (1,))
self._n_features_out = self._max_components
return self
def transform(self, X):
"""Project data to maximize class separation.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data.
Returns
-------
X_new : ndarray of shape (n_samples, n_components) or \
(n_samples, min(rank, n_components))
Transformed data. In the case of the 'svd' solver, the shape
is (n_samples, min(rank, n_components)).
"""
if self.solver == "lsqr":
raise NotImplementedError(
"transform not implemented for 'lsqr' solver (use 'svd' or 'eigen')."
)
check_is_fitted(self)
X = validate_data(self, X, reset=False)
if self.solver == "svd":
X_new = (X - self.xbar_) @ self.scalings_
elif self.solver == "eigen":
X_new = X @ self.scalings_
return X_new[:, : self._max_components]
def predict_proba(self, X):
"""Estimate probability.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data.
Returns
-------
C : ndarray of shape (n_samples, n_classes)
Estimated probabilities.
"""
check_is_fitted(self)
xp, _ = get_namespace(X)
decision = self.decision_function(X)
if size(self.classes_) == 2:
proba = _expit(decision, xp)
return xp.stack([1 - proba, proba], axis=1)
else:
return softmax(decision)
def predict_log_proba(self, X):
"""Estimate log probability.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data.
Returns
-------
C : ndarray of shape (n_samples, n_classes)
Estimated log probabilities.
"""
xp, _ = get_namespace(X)
prediction = self.predict_proba(X)
smallest_normal = xp.finfo(prediction.dtype).smallest_normal
prediction[prediction == 0.0] += smallest_normal
return xp.log(prediction)
def decision_function(self, X):
"""Apply decision function to an array of samples.
The decision function is equal (up to a constant factor) to the
log-posterior of the model, i.e. `log p(y = k | x)`. In a binary
classification setting this instead corresponds to the difference
`log p(y = 1 | x) - log p(y = 0 | x)`. See :ref:`lda_qda_math`.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Array of samples (test vectors).
Returns
-------
y_scores : ndarray of shape (n_samples,) or (n_samples, n_classes)
Decision function values related to each class, per sample.
In the two-class case, the shape is `(n_samples,)`, giving the
log likelihood ratio of the positive class.
"""
# Only overrides for the docstring.
return super().decision_function(X)
def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
tags.array_api_support = True
return tags
| LinearDiscriminantAnalysis |
python | walkccc__LeetCode | solutions/1446. Consecutive Characters/1446.py | {
"start": 0,
"end": 206
} | class ____:
def maxPower(self, s: str) -> int:
ans = 1
count = 1
for i in range(1, len(s)):
count = count + 1 if s[i] == s[i - 1] else 1
ans = max(ans, count)
return ans
| Solution |
python | getsentry__sentry | src/sentry/users/services/user/impl.py | {
"start": 1860,
"end": 15193
} | class ____(UserService):
def serialize_many(
self,
*,
filter: UserFilterArgs,
as_user: RpcUser | None = None,
auth_context: AuthenticationContext | None = None,
serializer: UserSerializeType | None = None,
) -> list[OpaqueSerializedResponse]:
return self._FQ.serialize_many(filter, as_user, auth_context, serializer)
def get_many(self, *, filter: UserFilterArgs) -> list[RpcUser]:
return self._FQ.get_many(filter)
def get_many_ids(self, *, filter: UserFilterArgs) -> list[int]:
return self._FQ.get_many_ids(filter)
def get_many_profiles(self, *, filter: UserFilterArgs) -> list[RpcUserProfile]:
users = self._FQ.query_many(filter, select_related=False)
return [serialize_rpc_user_profile(user) for user in users]
def get_many_by_email(
self,
emails: list[str],
is_active: bool = True,
is_verified: bool = True,
organization_id: int | None = None,
) -> list[RpcUser]:
user_emails_query = UserEmail.objects.filter(in_iexact("email", emails))
if is_verified:
user_emails_query = user_emails_query.filter(is_verified=True)
emails_by_user_ids: MutableMapping[int, list[str]] = {}
for ue in user_emails_query:
emails_by_user_ids.setdefault(ue.user_id, []).append(ue.email)
user_query = self._FQ.base_query().filter(id__in=list(emails_by_user_ids.keys()))
if is_active:
user_query = user_query.filter(is_active=is_active)
if organization_id is not None:
user_query = user_query.filter(orgmembermapping_set__organization_id=organization_id)
return [
self._FQ.serialize_rpc(user).by_email(email)
for user in user_query
for email in emails_by_user_ids[user.id]
]
def get_by_username(
self, username: str, with_valid_password: bool = True, is_active: bool | None = None
) -> list[RpcUser]:
qs = self._FQ.base_query()
if is_active is not None:
qs = qs.filter(is_active=is_active)
if with_valid_password:
qs = qs.exclude(password="!")
try:
# First, assume username is an iexact match for username
user = qs.get(username__iexact=username)
return [serialize_rpc_user(user)]
except User.DoesNotExist:
# If not, we can take a stab at guessing it's an email address
if "@" in username:
# email isn't guaranteed unique
return [serialize_rpc_user(u) for u in qs.filter(email__iexact=username)]
return []
def get_existing_usernames(self, *, usernames: list[str]) -> list[str]:
users = User.objects.filter(username__in=usernames)
return list(users.values_list("username", flat=True))
def get_organizations(
self,
*,
user_id: int,
only_visible: bool = False,
) -> list[RpcOrganizationMapping]:
if user_id is None:
# This is impossible if type hints are followed or Pydantic enforces type-checking
# on serialization, but is still possible if we make a call
# from non-Mypy-checked code on the same silo. It can occur easily if
# `request.user.id` is passed as an argument where the user is an
# AnonymousUser. Check explicitly to guard against returning mappings
# representing invitations.
return [] # type: ignore[unreachable]
org_ids = OrganizationMemberMapping.objects.filter(user_id=user_id).values_list(
"organization_id", flat=True
)
org_query = OrganizationMapping.objects.filter(organization_id__in=org_ids)
if only_visible:
org_query = org_query.filter(status=OrganizationStatus.ACTIVE)
return [serialize_organization_mapping(o) for o in org_query]
def get_member_region_names(self, *, user_id: int) -> list[str]:
org_ids = OrganizationMemberMapping.objects.filter(user_id=user_id).values_list(
"organization_id", flat=True
)
region_query = (
OrganizationMapping.objects.filter(organization_id__in=org_ids)
.values_list("region_name", flat=True)
.distinct()
)
return list(region_query)
def flush_nonce(self, *, user_id: int) -> None:
user = User.objects.filter(id=user_id).first()
if user is not None:
user.update(session_nonce="foo")
def update_user(
self,
*,
user_id: int,
attrs: UserUpdateArgs,
) -> Any:
try:
user = User.objects.get(id=user_id)
except User.DoesNotExist:
return None
if len(attrs):
for k, v in attrs.items():
setattr(user, k, v)
user.save()
return serialize(user)
def get_user_by_social_auth(
self, *, organization_id: int, provider: str, uid: str
) -> RpcUser | None:
user = User.objects.filter(
social_auth__provider=provider,
social_auth__uid=uid,
orgmembermapping_set__organization_id=organization_id,
).first()
if user is None:
return None
return serialize_rpc_user(user)
def get_first_superuser(self) -> RpcUser | None:
user = User.objects.filter(is_superuser=True, is_active=True).first()
if user is None:
return None
return serialize_rpc_user(user)
def get_or_create_by_email(
self, *, email: str, ident: str | None = None, referrer: str | None = None
) -> UserCreateResult:
with transaction.atomic(router.db_for_write(User)):
rpc_user = self.get_user_by_email(email=email, ident=ident)
if rpc_user:
return UserCreateResult(user=rpc_user, created=False)
# Create User if it doesn't exist
user = User.objects.create(
username=f"{slugify(str.split(email, '@')[0])}-{uuid4().hex}",
email=email,
name=email,
)
user_signup.send_robust(
sender=self, user=user, source="api", referrer=referrer or "unknown"
)
user.update(flags=F("flags").bitor(User.flags.newsletter_consent_prompt))
return UserCreateResult(user=serialize_rpc_user(user), created=True)
def get_user_by_email(
self,
*,
email: str,
ident: str | None = None,
) -> RpcUser | None:
user_query = User.objects.filter(email__iexact=email, is_active=True)
if user_query.exists():
# Users are not supposed to have the same email but right now our auth pipeline let this happen
# So let's not break the user experience. Instead return the user with auth identity of ident or
# the first user if ident is None
user = user_query[0]
if user_query.count() > 1:
logger.warning("Email has multiple users", extra={"email": email})
if ident:
identity_query = AuthIdentity.objects.filter(user__in=user_query, ident=ident)
if identity_query.exists():
user = identity_query[0].user
if identity_query.count() > 1:
logger.warning(
"Email has two auth identity for the same ident",
extra={"email": email},
)
return serialize_rpc_user(user)
return None
def verify_user_email(self, *, email: str, user_id: int) -> bool:
user_email = UserEmail.objects.filter(email__iexact=email, user_id=user_id).first()
if user_email is None:
return False
if not user_email.is_verified:
user_email.update(is_verified=True)
return True
return False
def verify_any_email(self, *, email: str) -> bool:
user_email = UserEmail.objects.filter(email__iexact=email).first()
if user_email is None:
return False
if not user_email.is_verified:
user_email.update(is_verified=True)
return True
return False
def create_by_username_and_email(self, *, email: str, username: str) -> RpcUser:
return serialize_rpc_user(User.objects.create(username=username, email=email))
def trigger_user_consent_email_if_applicable(self, *, user_id: int) -> None:
user = User.objects.get(id=user_id)
flag = User.flags.newsletter_consent_prompt
user.update(flags=F("flags").bitor(flag))
user.send_confirm_emails(is_new_user=True)
def verify_user_emails(
self, *, user_id_emails: list[UserIdEmailArgs], only_verified: bool = False
) -> dict[int, RpcVerifyUserEmail]:
results = {}
for user_id_email in user_id_emails:
user_id = user_id_email["user_id"]
email = user_id_email["email"]
user_email_qs = UserEmail.objects.filter(user_id=user_id, email__iexact=email)
if only_verified:
user_email_qs = user_email_qs.filter(is_verified=True)
results[user_id] = RpcVerifyUserEmail(email=email, exists=user_email_qs.exists())
return results
def get_user_avatar(self, *, user_id: int) -> RpcAvatar | None:
possible_avatar = UserAvatar.objects.filter(user_id=user_id).first()
if not possible_avatar:
return None
return serialize_user_avatar(avatar=possible_avatar)
class _UserFilterQuery(
FilterQueryDatabaseImpl[User, UserFilterArgs, RpcUser, UserSerializeType],
):
def apply_filters(self, query: QuerySet[User], filters: UserFilterArgs) -> QuerySet[User]:
if "user_ids" in filters:
query = query.filter(id__in=filters["user_ids"])
if "is_active" in filters:
query = query.filter(is_active=filters["is_active"])
if "organization_id" in filters:
query = query.filter(
orgmembermapping_set__organization_id=filters["organization_id"]
)
if "email_verified" in filters:
query = query.filter(emails__is_verified=filters["email_verified"])
if "emails" in filters:
# Since we can have a lot of emails, the in_iexact helper creates too many
# conditions in the query, so we annotate the email and filter by the
# uppercased version of the email for case insensitive search
query = query.annotate(upper_emails=Upper("emails__email")).filter(
upper_emails__in=map(lambda x: x.upper(), filters["emails"])
)
if "query" in filters:
query = query.filter(
Q(emails__email__icontains=filters["query"])
| Q(name__icontains=filters["query"])
)
if "authenticator_types" in filters:
at = filters["authenticator_types"]
if at is None:
query = query.filter(authenticator__isnull=True)
else:
query = query.filter(authenticator__isnull=False, authenticator__type__in=at)
return query
def base_query(self, select_related: bool = True) -> QuerySet[User]:
if not select_related:
return User.objects.all()
return User.objects.extra(
select={
"permissions": "select array_agg(permission) from sentry_userpermission where user_id=auth_user.id",
"roles": """
SELECT array_agg(permissions)
FROM sentry_userrole
JOIN sentry_userrole_users
ON sentry_userrole_users.role_id=sentry_userrole.id
WHERE user_id=auth_user.id""",
"useremails": "select array_agg(row_to_json(sentry_useremail)) from sentry_useremail where user_id=auth_user.id",
"authenticators": "SELECT array_agg(row_to_json(auth_authenticator)) FROM auth_authenticator WHERE user_id=auth_user.id",
"useravatar": "SELECT array_agg(row_to_json(sentry_useravatar)) FROM sentry_useravatar WHERE user_id = auth_user.id",
}
)
def filter_arg_validator(self) -> Callable[[UserFilterArgs], str | None]:
return self._filter_has_any_key_validator("user_ids", "organization_id", "emails")
def serialize_api(self, serializer_type: UserSerializeType | None) -> Serializer:
serializer: Serializer = UserSerializer()
if serializer_type == UserSerializeType.DETAILED:
serializer = DetailedUserSerializer()
if serializer_type == UserSerializeType.SELF_DETAILED:
serializer = DetailedSelfUserSerializer()
return serializer
def serialize_rpc(self, user: User) -> RpcUser:
return serialize_rpc_user(user)
_FQ = _UserFilterQuery()
| DatabaseBackedUserService |
python | huggingface__transformers | src/transformers/models/data2vec/modeling_data2vec_text.py | {
"start": 15394,
"end": 16812
} | class ____(nn.Module):
def __init__(self, config, is_causal=False, layer_idx=None, is_cross_attention=False):
super().__init__()
self.is_cross_attention = is_cross_attention
attention_class = Data2VecTextCrossAttention if is_cross_attention else Data2VecTextSelfAttention
self.self = attention_class(config, is_causal=is_causal, layer_idx=layer_idx)
self.output = Data2VecTextSelfOutput(config)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
encoder_attention_mask: Optional[torch.FloatTensor] = None,
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[torch.Tensor]:
attention_mask = attention_mask if not self.is_cross_attention else encoder_attention_mask
attention_output, attn_weights = self.self(
hidden_states,
encoder_hidden_states=encoder_hidden_states,
attention_mask=attention_mask,
past_key_values=past_key_values,
cache_position=cache_position,
**kwargs,
)
attention_output = self.output(attention_output, hidden_states)
return attention_output, attn_weights
| Data2VecTextAttention |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 35133,
"end": 35247
} | class ____(BaseModel, extra="forbid"):
drop_replica: "Replica" = Field(..., description="")
| DropReplicaOperation |
python | doocs__leetcode | solution/1100-1199/1162.As Far from Land as Possible/Solution.py | {
"start": 0,
"end": 639
} | class ____:
def maxDistance(self, grid: List[List[int]]) -> int:
n = len(grid)
q = deque((i, j) for i in range(n) for j in range(n) if grid[i][j])
ans = -1
if len(q) in (0, n * n):
return ans
dirs = (-1, 0, 1, 0, -1)
while q:
for _ in range(len(q)):
i, j = q.popleft()
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < n and 0 <= y < n and grid[x][y] == 0:
grid[x][y] = 1
q.append((x, y))
ans += 1
return ans
| Solution |
python | getsentry__sentry | src/sentry/grouping/component.py | {
"start": 16520,
"end": 17080
} | class ____(
BaseGroupingComponent[ContextLineGroupingComponent | FilenameGroupingComponent]
):
id: str = "template"
ContributingComponent = (
ChainedExceptionGroupingComponent
| ExceptionGroupingComponent
| StacktraceGroupingComponent
| ThreadsGroupingComponent
| CSPGroupingComponent
| ExpectCTGroupingComponent
| ExpectStapleGroupingComponent
| HPKPGroupingComponent
| MessageGroupingComponent
| TemplateGroupingComponent
)
# Wrapper component used to link component trees to variants
| TemplateGroupingComponent |
python | huggingface__transformers | src/transformers/cache_utils.py | {
"start": 14942,
"end": 21237
} | class ____(StaticLayer):
"""
A static cache layer that stores the key and value states as static tensors of shape
`[batch_size, num_heads, min(max_cache_len, sliding_window), head_dim]`. It lazily allocates its full backing
tensors, and then mutates them in-place. Built for `torch.compile` support.
Args:
max_cache_len (`int`):
Maximum number of tokens that can be stored, used for tensor preallocation.
sliding_window (`int`):
The size of the sliding window.
"""
is_sliding = True
def __init__(self, max_cache_len: int, sliding_window: int):
effective_max_cache_len = min(sliding_window, max_cache_len)
super().__init__(max_cache_len=effective_max_cache_len)
self.cumulative_length = 0
def update(
self,
key_states: torch.Tensor,
value_states: torch.Tensor,
cache_kwargs: Optional[dict[str, Any]] = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Update the key and value caches in-place, and return the necessary keys and value states.
Args:
key_states (`torch.Tensor`): The new key states to cache.
value_states (`torch.Tensor`): The new value states to cache.
cache_kwargs (`dict[str, Any]`, *optional*): Additional arguments for the cache.
Returns:
tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states.
"""
# Lazy initialization
if not self.is_initialized:
self.lazy_initialization(key_states)
# Some old models give None for `cache_position` or even omit passing `cache_kwargs` when used as cross-attention,
# in which case we should copy the whole Layer (key_states.shape[-2] == self.max_cache_len)
cache_position = cache_kwargs.get("cache_position") if cache_kwargs is not None else None
cache_position = (
cache_position if cache_position is not None else torch.arange(key_states.shape[-2], device=self.device)
)
cumulative_length = self.cumulative_length
is_full = cumulative_length >= self.max_cache_len
# Update it now that we saved the value above
self.cumulative_length += key_states.shape[-2]
if is_full:
# In general, we should use a much simpler `cat` here as well, independently of the states size. However,
# dynamo is currently bugged when doing it - see https://github.com/pytorch/pytorch/issues/159855 for more details
if key_states.shape[-2] == 1:
# Roll all values to the left by 1 position
new_keys = self.keys.roll(-1, dims=-2)
new_values = self.values.roll(-1, dims=-2)
# Overwrite the last position with new states
# (note: very important to use a tensor to index here, see https://github.com/pytorch/pytorch/issues/159855)
index = torch.tensor([-1], dtype=int, device=self.device)
new_keys[:, :, index] = key_states
new_values[:, :, index] = value_states
# Copy back into `self` (do not just assign again) in order to keep the static dynamo address
self.keys.copy_(new_keys)
self.values.copy_(new_values)
# Very important to return the `self` tensors here, as they have the static dynamo address
return self.keys, self.values
# Already full but using more than 1 new token (e.g. prefill caching, chat continuation, etc...)
else:
full_key_states = torch.cat((self.keys[:, :, 1:, :], key_states), dim=-2)
full_value_states = torch.cat((self.values[:, :, 1:, :], value_states), dim=-2)
# Not yet full, but becoming full on this update
elif cumulative_length + key_states.shape[2] > self.max_cache_len:
# Fast prefill path, no need to cat() in this case, as the cache is currently empty
if cumulative_length == 0:
full_key_states = key_states
full_value_states = value_states
else:
full_key_states = torch.cat((self.keys[:, :, :cumulative_length, :], key_states), dim=-2)
full_value_states = torch.cat((self.values[:, :, :cumulative_length, :], value_states), dim=-2)
else:
try:
self.keys.index_copy_(2, cache_position, key_states)
self.values.index_copy_(2, cache_position, value_states)
except NotImplementedError:
self.keys[:, :, cache_position] = key_states
self.values[:, :, cache_position] = value_states
# Very important to return the `self` tensors here, as they have the static dynamo address
return self.keys, self.values
# We only cache the last `sliding_window` tokens
self.keys.copy_(full_key_states[:, :, -self.max_cache_len :, :])
self.values.copy_(full_value_states[:, :, -self.max_cache_len :, :])
# we should return the whole states instead of `self.keys/values` here, as otherwise we lose some context
return full_key_states, full_value_states
def get_mask_sizes(self, cache_position: torch.Tensor) -> tuple[int, int]:
"""Return the length and offset of the cache, used to generate the attention mask"""
query_length = cache_position.shape[0]
sliding_window = self.max_cache_len
is_full = self.cumulative_length >= self.max_cache_len
kv_offset = max(self.cumulative_length - sliding_window + 1, 0)
# The cache is already full
if is_full:
kv_length = sliding_window + query_length - 1
# Not yet full, but becoming full on this update
elif self.cumulative_length + query_length > sliding_window:
kv_length = self.cumulative_length + query_length
# Here the Cache is still smaller than the local size, but we return the local size as it's static
else:
kv_length = sliding_window
return kv_length, kv_offset
def get_seq_length(self) -> int:
"""Returns the sequence length of the cached states."""
return self.cumulative_length
| StaticSlidingWindowLayer |
python | rapidsai__cudf | python/cudf/cudf/pandas/fast_slow_proxy.py | {
"start": 33408,
"end": 33528
} | class ____(FallbackError):
"""Raises when cuDF produces a MemoryError or an rmm.RMMError"""
pass
| OOMFallbackError |
python | huggingface__transformers | src/transformers/models/prompt_depth_anything/modeling_prompt_depth_anything.py | {
"start": 14574,
"end": 20153
} | class ____(PromptDepthAnythingPreTrainedModel):
_no_split_modules = ["DPTViTEmbeddings"]
def __init__(self, config):
super().__init__(config)
self.backbone = load_backbone(config)
self.neck = PromptDepthAnythingNeck(config)
self.head = PromptDepthAnythingDepthEstimationHead(config)
# Initialize weights and apply final processing
self.post_init()
@auto_docstring
def forward(
self,
pixel_values: torch.FloatTensor,
prompt_depth: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple[torch.Tensor], DepthEstimatorOutput]:
r"""
prompt_depth (`torch.FloatTensor` of shape `(batch_size, 1, height, width)`, *optional*):
Prompt depth is the sparse or low-resolution depth obtained from multi-view geometry or a
low-resolution depth sensor. It generally has shape (height, width), where height
and width can be smaller than those of the images. It is optional and can be None, which means no prompt depth
will be used. If it is None, the output will be a monocular relative depth.
The values are recommended to be in meters, but this is not necessary.
Example:
```python
>>> from transformers import AutoImageProcessor, AutoModelForDepthEstimation
>>> import torch
>>> import numpy as np
>>> from PIL import Image
>>> import requests
>>> url = "https://github.com/DepthAnything/PromptDA/blob/main/assets/example_images/image.jpg?raw=true"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> image_processor = AutoImageProcessor.from_pretrained("depth-anything/prompt-depth-anything-vits-hf")
>>> model = AutoModelForDepthEstimation.from_pretrained("depth-anything/prompt-depth-anything-vits-hf")
>>> prompt_depth_url = "https://github.com/DepthAnything/PromptDA/blob/main/assets/example_images/arkit_depth.png?raw=true"
>>> prompt_depth = Image.open(requests.get(prompt_depth_url, stream=True).raw)
>>> # prepare image for the model
>>> inputs = image_processor(images=image, return_tensors="pt", prompt_depth=prompt_depth)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # interpolate to original size
>>> post_processed_output = image_processor.post_process_depth_estimation(
... outputs,
... target_sizes=[(image.height, image.width)],
... )
>>> # visualize the prediction
>>> predicted_depth = post_processed_output[0]["predicted_depth"]
>>> depth = predicted_depth * 1000.
>>> depth = depth.detach().cpu().numpy()
>>> depth = Image.fromarray(depth.astype("uint16")) # mm
```
"""
loss = None
if labels is not None:
raise NotImplementedError("Training is not implemented yet")
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
outputs = self.backbone.forward_with_filtered_kwargs(
pixel_values, output_hidden_states=output_hidden_states, output_attentions=output_attentions
)
hidden_states = outputs.feature_maps
_, _, height, width = pixel_values.shape
patch_size = self.config.patch_size
patch_height = height // patch_size
patch_width = width // patch_size
if prompt_depth is not None:
# normalize prompt depth
batch_size = prompt_depth.shape[0]
depth_min = torch.min(prompt_depth.reshape(batch_size, -1), dim=1).values
depth_max = torch.max(prompt_depth.reshape(batch_size, -1), dim=1).values
depth_min, depth_max = depth_min.view(batch_size, 1, 1, 1), depth_max.view(batch_size, 1, 1, 1)
prompt_depth = (prompt_depth - depth_min) / (depth_max - depth_min)
# normalize done
hidden_states = self.neck(hidden_states, patch_height, patch_width, prompt_depth=prompt_depth)
predicted_depth = self.head(hidden_states, patch_height, patch_width)
if prompt_depth is not None:
# denormalize predicted depth
depth_min = depth_min.squeeze(1).to(predicted_depth.device)
depth_max = depth_max.squeeze(1).to(predicted_depth.device)
predicted_depth = predicted_depth * (depth_max - depth_min) + depth_min
# denormalize done
if not return_dict:
if output_hidden_states:
output = (predicted_depth,) + outputs[1:]
else:
output = (predicted_depth,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return DepthEstimatorOutput(
loss=loss,
predicted_depth=predicted_depth,
hidden_states=outputs.hidden_states if output_hidden_states else None,
attentions=outputs.attentions,
)
__all__ = ["PromptDepthAnythingForDepthEstimation", "PromptDepthAnythingPreTrainedModel"]
| PromptDepthAnythingForDepthEstimation |
python | walkccc__LeetCode | solutions/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance/1334.py | {
"start": 0,
"end": 900
} | class ____:
def findTheCity(
self,
n: int,
edges: list[list[int]],
distanceThreshold: int,
) -> int:
ans = -1
minCitiesCount = n
dist = self._floydWarshall(n, edges, distanceThreshold)
for i in range(n):
citiesCount = sum(dist[i][j] <= distanceThreshold for j in range(n))
if citiesCount <= minCitiesCount:
ans = i
minCitiesCount = citiesCount
return ans
def _floydWarshall(
self,
n: int,
edges: list[list[int]],
distanceThreshold: int,
) -> list[list[int]]:
dist = [[distanceThreshold + 1] * n for _ in range(n)]
for i in range(n):
dist[i][i] = 0
for u, v, w in edges:
dist[u][v] = w
dist[v][u] = w
for k in range(n):
for i in range(n):
for j in range(n):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
return dist
| Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol8.py | {
"start": 299,
"end": 369
} | class ____(_BaseClass):
def __init__(self, my_str: str): ...
| _Class1 |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 231864,
"end": 235171
} | class ____(Request):
"""
Adds a task into a queue.
Fails if task state is not 'created'.
Fails if the following parameters in the task were not filled:
* execution.script.repository
* execution.script.entrypoint
:param queue: Queue id. If not provided, task is added to the default queue.
:type queue: str
:param task: Task ID
:type task: str
:param status_reason: Reason for status change
:type status_reason: str
:param status_message: Extra information regarding status change
:type status_message: str
"""
_service = "tasks"
_action = "enqueue"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"queue": {
"description": "Queue id. If not provided, task is added to the default queue.",
"type": ["string", "null"],
},
"status_message": {
"description": "Extra information regarding status change",
"type": "string",
},
"status_reason": {
"description": "Reason for status change",
"type": "string",
},
"task": {"description": "Task ID", "type": "string"},
},
"required": ["task"],
"type": "object",
}
def __init__(
self,
task: str,
queue: Optional[str] = None,
status_reason: Optional[str] = None,
status_message: Optional[str] = None,
**kwargs: Any
) -> None:
super(EnqueueRequest, self).__init__(**kwargs)
self.queue = queue
self.task = task
self.status_reason = status_reason
self.status_message = status_message
@schema_property("queue")
def queue(self) -> Optional[str]:
return self._property_queue
@queue.setter
def queue(self, value: Optional[str]) -> None:
if value is None:
self._property_queue = None
return
self.assert_isinstance(value, "queue", six.string_types)
self._property_queue = value
@schema_property("task")
def task(self) -> str:
return self._property_task
@task.setter
def task(self, value: str) -> None:
if value is None:
self._property_task = None
return
self.assert_isinstance(value, "task", six.string_types)
self._property_task = value
@schema_property("status_reason")
def status_reason(self) -> Optional[str]:
return self._property_status_reason
@status_reason.setter
def status_reason(self, value: Optional[str]) -> None:
if value is None:
self._property_status_reason = None
return
self.assert_isinstance(value, "status_reason", six.string_types)
self._property_status_reason = value
@schema_property("status_message")
def status_message(self) -> Optional[str]:
return self._property_status_message
@status_message.setter
def status_message(self, value: Optional[str]) -> None:
if value is None:
self._property_status_message = None
return
self.assert_isinstance(value, "status_message", six.string_types)
self._property_status_message = value
| EnqueueRequest |
python | kubernetes-client__python | kubernetes/client/models/v1beta2_resource_pool.py | {
"start": 383,
"end": 7818
} | 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 = {
'generation': 'int',
'name': 'str',
'resource_slice_count': 'int'
}
attribute_map = {
'generation': 'generation',
'name': 'name',
'resource_slice_count': 'resourceSliceCount'
}
def __init__(self, generation=None, name=None, resource_slice_count=None, local_vars_configuration=None): # noqa: E501
"""V1beta2ResourcePool - 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._generation = None
self._name = None
self._resource_slice_count = None
self.discriminator = None
self.generation = generation
self.name = name
self.resource_slice_count = resource_slice_count
@property
def generation(self):
"""Gets the generation of this V1beta2ResourcePool. # noqa: E501
Generation tracks the change in a pool over time. Whenever a driver changes something about one or more of the resources in a pool, it must change the generation in all ResourceSlices which are part of that pool. Consumers of ResourceSlices should only consider resources from the pool with the highest generation number. The generation may be reset by drivers, which should be fine for consumers, assuming that all ResourceSlices in a pool are updated to match or deleted. Combined with ResourceSliceCount, this mechanism enables consumers to detect pools which are comprised of multiple ResourceSlices and are in an incomplete state. # noqa: E501
:return: The generation of this V1beta2ResourcePool. # noqa: E501
:rtype: int
"""
return self._generation
@generation.setter
def generation(self, generation):
"""Sets the generation of this V1beta2ResourcePool.
Generation tracks the change in a pool over time. Whenever a driver changes something about one or more of the resources in a pool, it must change the generation in all ResourceSlices which are part of that pool. Consumers of ResourceSlices should only consider resources from the pool with the highest generation number. The generation may be reset by drivers, which should be fine for consumers, assuming that all ResourceSlices in a pool are updated to match or deleted. Combined with ResourceSliceCount, this mechanism enables consumers to detect pools which are comprised of multiple ResourceSlices and are in an incomplete state. # noqa: E501
:param generation: The generation of this V1beta2ResourcePool. # noqa: E501
:type: int
"""
if self.local_vars_configuration.client_side_validation and generation is None: # noqa: E501
raise ValueError("Invalid value for `generation`, must not be `None`") # noqa: E501
self._generation = generation
@property
def name(self):
"""Gets the name of this V1beta2ResourcePool. # noqa: E501
Name is used to identify the pool. For node-local devices, this is often the node name, but this is not required. It must not be longer than 253 characters and must consist of one or more DNS sub-domains separated by slashes. This field is immutable. # noqa: E501
:return: The name of this V1beta2ResourcePool. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this V1beta2ResourcePool.
Name is used to identify the pool. For node-local devices, this is often the node name, but this is not required. It must not be longer than 253 characters and must consist of one or more DNS sub-domains separated by slashes. This field is immutable. # noqa: E501
:param name: The name of this V1beta2ResourcePool. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and name is None: # noqa: E501
raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501
self._name = name
@property
def resource_slice_count(self):
"""Gets the resource_slice_count of this V1beta2ResourcePool. # noqa: E501
ResourceSliceCount is the total number of ResourceSlices in the pool at this generation number. Must be greater than zero. Consumers can use this to check whether they have seen all ResourceSlices belonging to the same pool. # noqa: E501
:return: The resource_slice_count of this V1beta2ResourcePool. # noqa: E501
:rtype: int
"""
return self._resource_slice_count
@resource_slice_count.setter
def resource_slice_count(self, resource_slice_count):
"""Sets the resource_slice_count of this V1beta2ResourcePool.
ResourceSliceCount is the total number of ResourceSlices in the pool at this generation number. Must be greater than zero. Consumers can use this to check whether they have seen all ResourceSlices belonging to the same pool. # noqa: E501
:param resource_slice_count: The resource_slice_count of this V1beta2ResourcePool. # noqa: E501
:type: int
"""
if self.local_vars_configuration.client_side_validation and resource_slice_count is None: # noqa: E501
raise ValueError("Invalid value for `resource_slice_count`, must not be `None`") # noqa: E501
self._resource_slice_count = resource_slice_count
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, V1beta2ResourcePool):
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, V1beta2ResourcePool):
return True
return self.to_dict() != other.to_dict()
| V1beta2ResourcePool |
python | kamyu104__LeetCode-Solutions | Python/n-ary-tree-postorder-traversal.py | {
"start": 146,
"end": 578
} | class ____(object):
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
result, stack = [], [root]
while stack:
node = stack.pop()
result.append(node.val)
for child in node.children:
if child:
stack.append(child)
return result[::-1]
| Solution |
python | ray-project__ray | python/ray/_common/tests/test_wait_for_condition.py | {
"start": 136,
"end": 3505
} | class ____:
"""Tests for the synchronous wait_for_condition function."""
def test_immediate_true_condition(self):
"""Test that function returns immediately when condition is already true."""
def always_true():
return True
wait_for_condition(always_true, timeout=5)
def test_condition_becomes_true(self):
"""Test waiting for a condition that becomes true after some time."""
counter = {"value": 0}
def condition():
counter["value"] += 1
return counter["value"] >= 3
wait_for_condition(condition, timeout=5, retry_interval_ms=50)
assert counter["value"] >= 3
def test_timeout_raises_runtime_error(self):
"""Test that timeout raises RuntimeError with appropriate message."""
def always_false():
return False
with pytest.raises(RuntimeError) as exc_info:
wait_for_condition(always_false, timeout=0.2, retry_interval_ms=50)
assert "condition wasn't met before the timeout expired" in str(exc_info.value)
def test_condition_with_kwargs(self):
"""Test passing kwargs to the condition predictor."""
def condition_with_args(target, current=0):
return current >= target
wait_for_condition(condition_with_args, timeout=1, target=5, current=10)
# Should not raise an exception since current >= target
def test_exception_handling_default(self):
"""Test that exceptions are caught by default and timeout occurs."""
def failing_condition():
raise ValueError("Test exception")
with pytest.raises(RuntimeError) as exc_info:
wait_for_condition(failing_condition, timeout=0.2, retry_interval_ms=50)
error_msg = str(exc_info.value)
assert "condition wasn't met before the timeout expired" in error_msg
assert "Last exception:" in error_msg
assert "ValueError: Test exception" in error_msg
def test_exception_handling_raise_true(self):
"""Test that exceptions are raised when raise_exceptions=True."""
def failing_condition():
raise ValueError("Test exception")
with pytest.raises(ValueError) as exc_info:
wait_for_condition(failing_condition, timeout=1, raise_exceptions=True)
assert "Test exception" in str(exc_info.value)
def test_custom_retry_interval(self):
"""Test that custom retry intervals are respected."""
call_times = []
def condition():
call_times.append(time.time())
return len(call_times) >= 3
wait_for_condition(condition, timeout=5, retry_interval_ms=200)
# Verify that calls were spaced approximately 200ms apart
if len(call_times) >= 2:
interval = call_times[1] - call_times[0]
assert 0.15 <= interval <= 0.25 # Allow some tolerance
def test_condition_with_mixed_results(self):
"""Test condition that fails initially then succeeds."""
attempts = {"count": 0}
def intermittent_condition():
attempts["count"] += 1
# Succeed on the 4th attempt
return attempts["count"] >= 4
wait_for_condition(intermittent_condition, timeout=2, retry_interval_ms=100)
assert attempts["count"] >= 4
| TestWaitForCondition |
python | skorch-dev__skorch | skorch/callbacks/training.py | {
"start": 720,
"end": 12880
} | class ____(Callback):
"""Save the model during training if the given metric improved.
This callback works by default in conjunction with the validation
scoring callback since it creates a ``valid_loss_best`` value
in the history which the callback uses to determine if this
epoch is save-worthy.
You can also specify your own metric to monitor or supply a
callback that dynamically evaluates whether the model should
be saved in this epoch.
As checkpointing is often used in conjunction with early stopping
there is a need to restore the state of the model to the best
checkpoint after training is done. The checkpoint callback will
do this for you if you wish.
Some or all of the following can be saved:
- model parameters (see ``f_params`` parameter);
- optimizer state (see ``f_optimizer`` parameter);
- criterion state (see ``f_criterion`` parameter);
- training history (see ``f_history`` parameter);
- entire model object (see ``f_pickle`` parameter).
If you've created a custom module, e.g. ``net.mymodule_``, you
can save that as well by passing ``f_mymodule``.
You can implement your own save protocol by subclassing
``Checkpoint`` and overriding :func:`~Checkpoint.save_model`.
This callback writes a bool flag to the history column
``event_cp`` indicating whether a checkpoint was created or not.
Example:
>>> net = MyNet(callbacks=[Checkpoint()])
>>> net.fit(X, y)
Example using a custom monitor where models are saved only in
epochs where the validation *and* the train losses are best:
>>> monitor = lambda net: all(net.history[-1, (
... 'train_loss_best', 'valid_loss_best')])
>>> net = MyNet(callbacks=[Checkpoint(monitor=monitor)])
>>> net.fit(X, y)
Parameters
----------
monitor : str, function, None
Value of the history to monitor or callback that determines
whether this epoch should lead to a checkpoint. The callback
takes the network instance as parameter.
In case ``monitor`` is set to ``None``, the callback will save
the network at every epoch.
**Note:** If you supply a lambda expression as monitor, you cannot
pickle the wrapper anymore as lambdas cannot be pickled. You can
mitigate this problem by using importable functions instead.
f_params : file-like object, str, None (default='params.pt')
File path to the file or file-like object where the model
parameters should be saved. Pass ``None`` to disable saving
model parameters.
If the value is a string you can also use format specifiers
to, for example, indicate the current epoch. Accessible format
values are ``net``, ``last_epoch`` and ``last_batch``.
Example to include last epoch number in file name:
>>> cb = Checkpoint(f_params="params_{last_epoch[epoch]}.pt")
f_optimizer : file-like object, str, None (default='optimizer.pt')
File path to the file or file-like object where the optimizer
state should be saved. Pass ``None`` to disable saving
model parameters.
Supports the same format specifiers as ``f_params``.
f_criterion : file-like object, str, None (default='criterion.pt')
File path to the file or file-like object where the criterion
state should be saved. Pass ``None`` to disable saving
model parameters.
Supports the same format specifiers as ``f_params``.
f_history : file-like object, str, None (default='history.json')
File path to the file or file-like object where the model
training history should be saved. Pass ``None`` to disable
saving history.
f_pickle : file-like object, str, None (default=None)
File path to the file or file-like object where the entire
model object should be pickled. Pass ``None`` to disable
pickling.
Supports the same format specifiers as ``f_params``.
fn_prefix: str (default='')
Prefix for filenames. If ``f_params``, ``f_optimizer``, ``f_history``,
or ``f_pickle`` are strings, they will be prefixed by ``fn_prefix``.
dirname: str (default='')
Directory where files are stored.
event_name: str, (default='event_cp')
Name of event to be placed in history when checkpoint is triggered.
Pass ``None`` to disable placing events in history.
sink : callable (default=noop)
The target that the information about created checkpoints is
sent to. This can be a logger or ``print`` function (to send to
stdout). By default the output is discarded.
load_best: bool (default=False)
Load the best checkpoint automatically once training ended.
This can be particularly helpful in combination with early stopping
as it allows for scoring with the best model, even when early stopping
ended training a number of epochs later. Note that this will only
work when ``monitor != None``.
use_safetensors : bool (default=False)
Whether to use the ``safetensors`` library to persist the state. By
default, PyTorch is used, which in turn uses :mod:`pickle` under the
hood. When enabling ``safetensors``, be aware that only PyTorch
tensors can be stored. Therefore, certain attributes like the
optimizer cannot be saved.
"""
def __init__(
self,
monitor='valid_loss_best',
f_params='params.pt',
f_optimizer='optimizer.pt',
f_criterion='criterion.pt',
f_history='history.json',
f_pickle=None,
fn_prefix='',
dirname='',
event_name='event_cp',
sink=noop,
load_best=False,
use_safetensors=False,
**kwargs
):
self.monitor = monitor
self.f_params = f_params
self.f_optimizer = f_optimizer
self.f_criterion = f_criterion
self.f_history = f_history
self.f_pickle = f_pickle
self.fn_prefix = fn_prefix
self.dirname = dirname
self.event_name = event_name
self.sink = sink
self.load_best = load_best
self.use_safetensors = use_safetensors
self._check_kwargs(kwargs)
vars(self).update(**kwargs)
self._validate_filenames()
def _check_kwargs(self, kwargs):
for key in kwargs:
if not key.startswith('f_'):
raise TypeError(
"{cls_name} got an unexpected argument '{key}', did you mean "
"'f_{key}'?".format(cls_name=self.__class__.__name__, key=key))
if self.use_safetensors and self.f_optimizer is not None:
raise ValueError(
"Cannot save optimizer state when using safetensors, "
"please set f_optimizer=None or don't use safetensors.")
def initialize(self):
self._validate_filenames()
if self.dirname and not os.path.exists(self.dirname):
os.makedirs(self.dirname, exist_ok=True)
return self
def on_train_end(self, net, **kwargs):
if not self.load_best or self.monitor is None:
return
self._sink("Loading best checkpoint after training.", net.verbose)
net.load_params(checkpoint=self, use_safetensors=self.use_safetensors)
def on_epoch_end(self, net, **kwargs):
if "{}_best".format(self.monitor) in net.history[-1]:
warnings.warn(
"Checkpoint monitor parameter is set to '{0}' and the history "
"contains '{0}_best'. Perhaps you meant to set the parameter "
"to '{0}_best'".format(self.monitor), UserWarning)
if self.monitor is None:
do_checkpoint = True
elif callable(self.monitor):
do_checkpoint = self.monitor(net)
else:
try:
do_checkpoint = net.history[-1, self.monitor]
except KeyError as e:
msg = (
f"{e.args[0]} Make sure you have validation data if you use "
"validation scores for checkpointing.")
raise SkorchException(msg)
if self.event_name is not None:
net.history.record(self.event_name, bool(do_checkpoint))
if do_checkpoint:
self.save_model(net)
self._sink("A checkpoint was triggered in epoch {}.".format(
len(net.history) + 1
), net.verbose)
def _f_kwargs(self):
return {key: getattr(self, key) for key in dir(self)
if key.startswith('f_') and (key != 'f_history_')}
def save_model(self, net):
"""Save the model.
This function saves some or all of the following:
- model parameters;
- optimizer state;
- criterion state;
- training history;
- custom modules;
- entire model object.
"""
kwargs_module, kwargs_other = _check_f_arguments(
self.__class__.__name__, **self._f_kwargs())
for key, val in kwargs_module.items():
if val is None:
continue
f = self._format_target(net, val, -1)
key = key[:-1] # remove trailing '_'
self._save_params(f, net, 'f_' + key, key + " state")
f_history = kwargs_other.get('f_history')
if f_history is not None:
f = self.f_history_
self._save_params(f, net, "f_history", "history")
f_pickle = kwargs_other.get('f_pickle')
if f_pickle:
f_pickle = self._format_target(net, f_pickle, -1)
with open_file_like(f_pickle, 'wb') as f:
pickle.dump(net, f)
@property
def f_history_(self):
# This is a property and not in initialize to allow ``NeuralNet``
# to call ``load_params`` without needing the checkpoint to
# by initialized.
if self.f_history is None:
return None
return os.path.join(
self.dirname, self.fn_prefix + self.f_history)
def get_formatted_files(self, net):
"""Returns a dictionary of formatted filenames"""
idx = -1
if (
self.event_name is not None and
net.history
):
for i, v in enumerate(net.history[:, self.event_name]):
if v:
idx = i
return {key: self._format_target(net, val, idx) for key, val
in self._f_kwargs().items()}
def _save_params(self, f, net, f_name, log_name):
try:
net.save_params(**{f_name: f, 'use_safetensors': self.use_safetensors})
except Exception as e: # pylint: disable=broad-except
self._sink(
"Unable to save {} to {}, {}: {}".format(
log_name, f, type(e).__name__, e), net.verbose)
def _format_target(self, net, f, idx):
"""Apply formatting to the target filename template."""
if f is None:
return None
if isinstance(f, str):
f = self.fn_prefix + f.format(
net=net,
last_epoch=net.history[idx],
last_batch=net.history[idx, 'batches', -1],
)
return os.path.join(self.dirname, f)
return f
def _validate_filenames(self):
"""Checks if passed filenames are valid.
Specifically, f_* parameter should not be passed in
conjunction with dirname.
"""
_check_f_arguments(self.__class__.__name__, **self._f_kwargs())
if not self.dirname:
return
def _is_truthy_and_not_str(f):
return f and not isinstance(f, str)
if any(_is_truthy_and_not_str(val) for val in self._f_kwargs().values()):
raise SkorchException(
'dirname can only be used when f_* are strings')
def _sink(self, text, verbose):
# We do not want to be affected by verbosity if sink is not print
if (self.sink is not print) or verbose:
self.sink(text)
| Checkpoint |
python | huggingface__transformers | src/transformers/models/udop/modeling_udop.py | {
"start": 37059,
"end": 38347
} | class ____(nn.Module):
def __init__(self, max_2d_position_embeddings=501, hidden_size=1024):
super().__init__()
self.max_2d_position_embeddings = max_2d_position_embeddings
self.x_position_embeddings = nn.Embedding(max_2d_position_embeddings, hidden_size)
self.y_position_embeddings = nn.Embedding(max_2d_position_embeddings, hidden_size)
def forward(self, bbox):
bbox = torch.clip(bbox, 0.0, 1.0)
bbox = (bbox * (self.max_2d_position_embeddings - 1)).long()
left_position_embeddings = self.x_position_embeddings(bbox[:, :, 0])
upper_position_embeddings = self.y_position_embeddings(bbox[:, :, 1])
right_position_embeddings = self.x_position_embeddings(bbox[:, :, 2])
lower_position_embeddings = self.y_position_embeddings(bbox[:, :, 3])
embeddings = (
left_position_embeddings
+ upper_position_embeddings
+ right_position_embeddings
+ lower_position_embeddings
)
return embeddings
# get function for bucket computation
# protected member access seems to be lesser evil than copy paste whole function
get_relative_position_bucket = UdopAttention._relative_position_bucket
AUGMENTATION_RANGE = (0.80, 1.25)
| UdopCellEmbeddings |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/annotatedVar5.py | {
"start": 63,
"end": 796
} | class ____(object):
def __init__(self):
self.inst_var1 = 3
@property
def prop1(self):
return 1
@prop1.setter
def prop1(self, val):
pass
def foo(self):
# This should generate an error because the assigned
# type doesn't match the declared type.
self.inst_var1 = 3 # type: str
self.inst_var1: str = "hello"
# This should generate an error because the declared
# type doesn't match the previously declared type.
self.inst_var1: int = "hello"
# This should generate an error because the assigned
# type doesn't match the declared type.
self.inst_var1 = "hello" # type: int
self.prop1 = 3
| ClassC |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/ddl.py | {
"start": 15879,
"end": 16376
} | class ____(_DropBase[str]):
"""Represent a DROP SCHEMA statement.
The argument here is the string name of the schema.
"""
__visit_name__ = "drop_schema"
stringify_dialect = "default"
def __init__(
self,
name: str,
cascade: bool = False,
if_exists: bool = False,
) -> None:
"""Create a new :class:`.DropSchema` construct."""
super().__init__(element=name, if_exists=if_exists)
self.cascade = cascade
| DropSchema |
python | astropy__astropy | astropy/table/tests/conftest.py | {
"start": 1179,
"end": 1232
} | class ____(table.MaskedColumn):
pass
| MyMaskedColumn |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-sub-question-weaviate/llama_index/packs/sub_question_weaviate/base.py | {
"start": 532,
"end": 2694
} | class ____(BaseLlamaPack):
"""Weaviate Sub-Question query engine pack."""
def __init__(
self,
collection_name: str,
host: str,
auth_client_secret: str,
nodes: Optional[List[TextNode]] = None,
**kwargs: Any,
) -> None:
"""Init params."""
from weaviate import Client
self.client: Client = Client(host, auth_client_secret=auth_client_secret)
weaviate_client = self.client
weaviate_collection = weaviate_client.get_or_create_collection(collection_name)
self._vector_store = WeaviateVectorStore(
weaviate_collection=weaviate_collection
)
if nodes is not None:
self._storage_context = StorageContext.from_defaults(
vector_store=self._vector_store
)
self._index = VectorStoreIndex(
nodes, storage_context=self._storage_context, **kwargs
)
else:
self._index = VectorStoreIndex.from_vector_store(
self._vector_store, **kwargs
)
self._storage_context = self._index.storage_context
self.retriever = self._index.as_retriever()
query_engine = self._index.as_query_engine()
query_engine_tools = [
QueryEngineTool(
query_engine=query_engine, metadata=ToolMetadata(name="Vector Index")
)
]
self.query_engine = SubQuestionQueryEngine.from_defaults(
query_engine_tools=query_engine_tools
)
def get_modules(self) -> Dict[str, Any]:
"""Get modules."""
return {
"vector_store": self._vector_store,
"storage_context": self._storage_context,
"index": self._index,
"retriever": self.retriever,
"query_engine": self.query_engine,
}
def retrieve(self, query_str: str) -> Any:
"""Retrieve."""
return self.retriever.retrieve(query_str)
def run(self, *args: Any, **kwargs: Any) -> Any:
"""Run the pipeline."""
return self.query_engine.query(*args, **kwargs)
| WeaviateSubQuestionPack |
python | PrefectHQ__prefect | tests/test_flows.py | {
"start": 126113,
"end": 139853
} | class ____:
class TestSync:
@property
def flow(self):
@flow
def test_flow():
pass
return test_flow
def test_to_deployment_returns_runner_deployment(self):
deployment = self.flow.to_deployment(
name="test",
tags=["price", "luggage"],
parameters={"name": "Arthur"},
concurrency_limit=42,
description="This is a test",
version="alpha",
enforce_parameter_schema=True,
triggers=[
{
"name": "Happiness",
"enabled": True,
"match": {"prefect.resource.id": "prefect.flow-run.*"},
"expect": ["prefect.flow-run.Completed"],
"match_related": {
"prefect.resource.name": "seed",
"prefect.resource.role": "flow",
},
}
],
)
assert isinstance(deployment, RunnerDeployment)
assert deployment.name == "test"
assert deployment.tags == ["price", "luggage"]
assert deployment.parameters == {"name": "Arthur"}
assert deployment.concurrency_limit == 42
assert deployment.description == "This is a test"
assert deployment.version == "alpha"
assert deployment.enforce_parameter_schema
assert deployment.triggers == [
DeploymentEventTrigger(
name="Happiness",
enabled=True,
posture=Posture.Reactive,
match={"prefect.resource.id": "prefect.flow-run.*"},
expect=["prefect.flow-run.Completed"],
match_related={
"prefect.resource.name": "seed",
"prefect.resource.role": "flow",
},
)
]
def test_to_deployment_accepts_interval(self):
deployment = self.flow.to_deployment(name="test", interval=3600)
assert deployment.schedules
assert isinstance(deployment.schedules[0].schedule, IntervalSchedule)
assert deployment.schedules[0].schedule.interval == datetime.timedelta(
seconds=3600
)
def test_to_deployment_accepts_cron(self):
deployment = self.flow.to_deployment(name="test", cron="* * * * *")
assert deployment.schedules
assert deployment.schedules[0].schedule == CronSchedule(cron="* * * * *")
def test_to_deployment_accepts_rrule(self):
deployment = self.flow.to_deployment(name="test", rrule="FREQ=MINUTELY")
assert deployment.schedules
assert deployment.schedules[0].schedule == RRuleSchedule(
rrule="FREQ=MINUTELY"
)
def test_to_deployment_invalid_name_raises(self):
with pytest.raises(InvalidNameError, match="contains an invalid character"):
self.flow.to_deployment("test/deployment")
@pytest.mark.parametrize(
"kwargs",
[
{**d1, **d2}
for d1, d2 in combinations(
[
{"interval": 3600},
{"cron": "* * * * *"},
{"rrule": "FREQ=MINUTELY"},
],
2,
)
],
)
def test_to_deployment_raises_on_multiple_schedule_parameters(self, kwargs):
with warnings.catch_warnings():
# `schedule` parameter is deprecated and will raise a warning
warnings.filterwarnings("ignore", category=DeprecationWarning)
expected_message = "Only one of interval, cron, rrule, schedule, or schedules can be provided."
with pytest.raises(ValueError, match=expected_message):
self.flow.to_deployment(__file__, **kwargs)
def test_to_deployment_respects_with_options_name_from_flow(self):
"""regression test for https://github.com/PrefectHQ/prefect/issues/15380"""
@flow(name="original-name")
def test_flow():
pass
flow_with_new_name = test_flow.with_options(name="new-name")
deployment = flow_with_new_name.to_deployment(name="test-deployment")
assert isinstance(deployment, RunnerDeployment)
assert deployment.name == "test-deployment"
assert deployment.flow_name == "new-name"
def test_to_deployment_respects_with_options_name_from_storage(
self, monkeypatch
):
"""regression test for https://github.com/PrefectHQ/prefect/issues/15380"""
@flow(name="original-name")
def test_flow():
pass
flow_with_new_name = test_flow.with_options(name="new-name")
mock_storage = MagicMock(spec=RunnerStorage)
mock_entrypoint = "fake_module:test_flow"
mock_from_storage = MagicMock(
return_value=RunnerDeployment(
name="test-deployment",
flow_name="new-name",
entrypoint=mock_entrypoint,
)
)
monkeypatch.setattr(RunnerDeployment, "from_storage", mock_from_storage)
flow_with_new_name._storage = mock_storage
flow_with_new_name._entrypoint = mock_entrypoint
deployment = flow_with_new_name.to_deployment(name="test-deployment")
assert isinstance(deployment, RunnerDeployment)
assert deployment.name == "test-deployment"
assert deployment.flow_name == "new-name"
assert deployment.entrypoint == mock_entrypoint
mock_from_storage.assert_called_once()
call_args = mock_from_storage.call_args[1]
assert call_args["storage"] == mock_storage
assert call_args["entrypoint"] == mock_entrypoint
assert call_args["name"] == "test-deployment"
assert call_args["flow_name"] == "new-name"
def test_to_deployment_accepts_concurrency_limit(self):
concurrency_limit = ConcurrencyLimitConfig(
limit=42, collision_strategy="CANCEL_NEW"
)
deployment = self.flow.to_deployment(
name="test", concurrency_limit=concurrency_limit
)
assert deployment.concurrency_limit == 42
assert deployment.concurrency_options.collision_strategy == "CANCEL_NEW"
class TestAsync:
@property
def flow(self):
@flow
async def test_flow():
pass
return test_flow
async def test_to_deployment_returns_runner_deployment(self):
deployment = await self.flow.ato_deployment(
name="test",
tags=["price", "luggage"],
parameters={"name": "Arthur"},
concurrency_limit=42,
description="This is a test",
version="alpha",
enforce_parameter_schema=True,
triggers=[
{
"name": "Happiness",
"enabled": True,
"match": {"prefect.resource.id": "prefect.flow-run.*"},
"expect": ["prefect.flow-run.Completed"],
"match_related": {
"prefect.resource.name": "seed",
"prefect.resource.role": "flow",
},
}
],
)
assert isinstance(deployment, RunnerDeployment)
assert deployment.name == "test"
assert deployment.tags == ["price", "luggage"]
assert deployment.parameters == {"name": "Arthur"}
assert deployment.concurrency_limit == 42
assert deployment.description == "This is a test"
assert deployment.version == "alpha"
assert deployment.enforce_parameter_schema
assert deployment.triggers == [
DeploymentEventTrigger(
name="Happiness",
enabled=True,
posture=Posture.Reactive,
match={"prefect.resource.id": "prefect.flow-run.*"},
expect=["prefect.flow-run.Completed"],
match_related={
"prefect.resource.name": "seed",
"prefect.resource.role": "flow",
},
)
]
async def test_to_deployment_can_produce_a_module_path_entrypoint(self):
deployment = await self.flow.ato_deployment(
name="test", entrypoint_type=EntrypointType.MODULE_PATH
)
assert (
deployment.entrypoint == f"{self.flow.__module__}.{self.flow.__name__}"
)
async def test_to_deployment_accepts_cron(self):
deployment = await self.flow.ato_deployment(name="test", cron="* * * * *")
assert deployment.schedules
assert deployment.schedules[0].schedule == CronSchedule(cron="* * * * *")
async def test_to_deployment_accepts_rrule(self):
deployment = await self.flow.ato_deployment(
name="test", rrule="FREQ=MINUTELY"
)
assert deployment.schedules
assert deployment.schedules[0].schedule == RRuleSchedule(
rrule="FREQ=MINUTELY"
)
async def test_to_deployment_invalid_name_raises(self):
with pytest.raises(InvalidNameError, match="contains an invalid character"):
await self.flow.ato_deployment("test/deployment")
@pytest.mark.parametrize(
"kwargs",
[
{**d1, **d2}
for d1, d2 in combinations(
[
{"interval": 3600},
{"cron": "* * * * *"},
{"rrule": "FREQ=MINUTELY"},
],
2,
)
],
)
async def test_to_deployment_raises_on_multiple_schedule_parameters(
self, kwargs
):
with warnings.catch_warnings():
# `schedule` parameter is deprecated and will raise a warning
warnings.filterwarnings("ignore", category=DeprecationWarning)
expected_message = "Only one of interval, cron, rrule, schedule, or schedules can be provided."
with pytest.raises(ValueError, match=expected_message):
await self.flow.ato_deployment(__file__, **kwargs)
async def test_to_deployment_respects_with_options_name_from_flow(self):
"""regression test for https://github.com/PrefectHQ/prefect/issues/15380"""
@flow(name="original-name")
def test_flow():
pass
flow_with_new_name = test_flow.with_options(name="new-name")
deployment = await flow_with_new_name.ato_deployment(name="test-deployment")
assert isinstance(deployment, RunnerDeployment)
assert deployment.name == "test-deployment"
assert deployment.flow_name == "new-name"
async def test_to_deployment_respects_with_options_name_from_storage(
self, monkeypatch
):
"""regression test for https://github.com/PrefectHQ/prefect/issues/15380"""
@flow(name="original-name")
def test_flow():
pass
flow_with_new_name = test_flow.with_options(name="new-name")
mock_storage = MagicMock(spec=RunnerStorage)
mock_entrypoint = "fake_module:test_flow"
mock_from_storage = AsyncMock(
return_value=RunnerDeployment(
name="test-deployment",
flow_name="new-name",
entrypoint=mock_entrypoint,
)
)
monkeypatch.setattr(RunnerDeployment, "afrom_storage", mock_from_storage)
flow_with_new_name._storage = mock_storage
flow_with_new_name._entrypoint = mock_entrypoint
deployment = await flow_with_new_name.ato_deployment(name="test-deployment")
assert isinstance(deployment, RunnerDeployment)
assert deployment.name == "test-deployment"
assert deployment.flow_name == "new-name"
assert deployment.entrypoint == mock_entrypoint
mock_from_storage.assert_awaited_once()
call_args = mock_from_storage.call_args[1]
assert call_args["storage"] == mock_storage
assert call_args["entrypoint"] == mock_entrypoint
assert call_args["name"] == "test-deployment"
assert call_args["flow_name"] == "new-name"
async def test_to_deployment_accepts_concurrency_limit(self):
concurrency_limit = ConcurrencyLimitConfig(
limit=42, collision_strategy="CANCEL_NEW"
)
deployment = await self.flow.ato_deployment(
name="test", concurrency_limit=concurrency_limit
)
assert deployment.concurrency_limit == 42
assert deployment.concurrency_options.collision_strategy == "CANCEL_NEW"
| TestFlowToDeployment |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_optimize14.py | {
"start": 315,
"end": 1265
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("optimize14.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with comments."""
workbook = Workbook(
self.got_filename, {"constant_memory": True, "in_memory": False}
)
worksheet = workbook.add_worksheet()
worksheet.write("A1", "Foo")
worksheet.write("C7", "Bar")
worksheet.write("G14", "Baz")
worksheet.write_comment("A1", "Some text")
worksheet.write_comment("D1", "Some text")
worksheet.write_comment("C7", "Some text")
worksheet.write_comment("E10", "Some text")
worksheet.write_comment("G14", "Some text")
worksheet.set_comments_author("John")
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | urllib3__urllib3 | test/with_dummyserver/test_connectionpool.py | {
"start": 51691,
"end": 54558
} | class ____(HypercornDummyServerTestCase):
def test_retry_after(self) -> None:
# Request twice in a second to get a 429 response.
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request(
"GET",
"/retry_after",
fields={"status": "429 Too Many Requests"},
retries=False,
)
r = pool.request(
"GET",
"/retry_after",
fields={"status": "429 Too Many Requests"},
retries=False,
)
assert r.status == 429
r = pool.request(
"GET",
"/retry_after",
fields={"status": "429 Too Many Requests"},
retries=True,
)
assert r.status == 200
# Request twice in a second to get a 503 response.
r = pool.request(
"GET",
"/retry_after",
fields={"status": "503 Service Unavailable"},
retries=False,
)
r = pool.request(
"GET",
"/retry_after",
fields={"status": "503 Service Unavailable"},
retries=False,
)
assert r.status == 503
r = pool.request(
"GET",
"/retry_after",
fields={"status": "503 Service Unavailable"},
retries=True,
)
assert r.status == 200
# Ignore Retry-After header on status which is not defined in
# Retry.RETRY_AFTER_STATUS_CODES.
r = pool.request(
"GET",
"/retry_after",
fields={"status": "418 I'm a teapot"},
retries=True,
)
assert r.status == 418
def test_redirect_after(self) -> None:
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request("GET", "/redirect_after", retries=False)
assert r.status == 303
# Real timestamps are needed for this test
t = time.time()
r = pool.request("GET", "/redirect_after")
assert r.status == 200
delta = time.time() - t
assert delta >= 1
t = time.time()
timestamp = t + 2
r = pool.request("GET", "/redirect_after?date=" + str(timestamp))
assert r.status == 200
delta = time.time() - t
assert delta >= 1
# Retry-After is past
t = time.time()
timestamp = t - 1
r = pool.request("GET", "/redirect_after?date=" + str(timestamp))
delta = time.time() - t
assert r.status == 200
assert delta < 1
| TestRetryAfter |
python | paramiko__paramiko | paramiko/agent.py | {
"start": 6000,
"end": 6658
} | class ____(AgentProxyThread):
"""
Class to be used when wanting to ask a local SSH Agent being
asked from a remote fake agent (so use a unix socket for ex.)
"""
def __init__(self, agent):
AgentProxyThread.__init__(self, agent)
def get_connection(self):
"""
Return a pair of socket object and string address.
May block!
"""
conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
conn.bind(self._agent._get_filename())
conn.listen(1)
(r, addr) = conn.accept()
return r, addr
except:
raise
| AgentLocalProxy |
python | kamyu104__LeetCode-Solutions | Python/delivering-boxes-from-storage-to-ports.py | {
"start": 29,
"end": 964
} | class ____(object):
def boxDelivering(self, boxes, portsCount, maxBoxes, maxWeight):
"""
:type boxes: List[List[int]]
:type portsCount: int
:type maxBoxes: int
:type maxWeight: int
:rtype: int
"""
dp = [0]*(len(boxes)+1)
left, cost, curr = 0, 1, 0
for right in xrange(len(boxes)):
if right == 0 or boxes[right][0] != boxes[right-1][0]:
cost += 1
curr += boxes[right][1]
while right-left+1 > maxBoxes or \
curr > maxWeight or \
(left+1 < right+1 and dp[left+1] == dp[left]): # greedily drop box to make cost as smaller as possible
curr -= boxes[left][1]
if boxes[left+1][0] != boxes[left][0]:
cost -= 1
left += 1
dp[right+1] = dp[(left-1)+1] + cost
return dp[len(boxes)]
| Solution |
python | jina-ai__jina | jina/enums.py | {
"start": 3788,
"end": 4688
} | class ____(BetterEnum):
"""The enum for representing the parallel type of pods in a deployment."""
ANY = 1 #: one of the shards will receive the message
ALL = 2 #: all shards will receive the message, blocked until all done with the message
ALL_ASYNC = 3 #: (reserved) all replica will receive the message, but any one of them can return, useful in backup
@property
def is_push(self) -> bool:
"""
Check if :class:`PollingType` is using `push` protocol.
:return: True if this :class:`PollingType` is using `push` protocol else False.
"""
return self.value == 1
@property
def is_block(self) -> bool:
"""
Check if :class:`PollingType` is using `block` protocol.
:return: True if this :class:`PollingType` is requiring `block` protocol else False.
"""
return self.value == 2
| PollingType |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 7225,
"end": 8886
} | class ____(WebTestCase):
final_return = None # type: Future
def get_handlers(self):
test = self
class FinishHandler(RequestHandler):
@gen.coroutine
def get(self):
test.final_return = self.finish()
yield test.final_return
@gen.coroutine
def post(self):
self.write("hello,")
yield self.flush()
test.final_return = self.finish("world")
yield test.final_return
class RenderHandler(RequestHandler):
def create_template_loader(self, path):
return DictLoader({"foo.html": "hi"})
@gen.coroutine
def get(self):
test.final_return = self.render("foo.html")
return [("/finish", FinishHandler), ("/render", RenderHandler)]
def get_app_kwargs(self):
return dict(template_path="FinalReturnTest")
def test_finish_method_return_future(self):
response = self.fetch(self.get_url("/finish"))
self.assertEqual(response.code, 200)
self.assertIsInstance(self.final_return, Future)
self.assertTrue(self.final_return.done())
response = self.fetch(self.get_url("/finish"), method="POST", body=b"")
self.assertEqual(response.code, 200)
self.assertIsInstance(self.final_return, Future)
self.assertTrue(self.final_return.done())
def test_render_method_return_future(self):
response = self.fetch(self.get_url("/render"))
self.assertEqual(response.code, 200)
self.assertIsInstance(self.final_return, Future)
| FinalReturnTest |
python | huggingface__transformers | tests/repo_utils/test_check_copies.py | {
"start": 5460,
"end": 8009
} | class ____:
attr_1 = 1
attr_2 = 2
def __init__(self, a=1, b=2):
self.a = a
self.b = b
# Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward
def forward(self, c):
return 1
def only_in_bert(self, c):
return 7
def existing_common(self, c):
return 4
def existing_diff_not_ignored(self, c):
return 8
# Ignore copy
def existing_diff_to_be_ignored(self, c):
return 6
# Ignore copy
def only_in_roberta_to_be_ignored(self, c):
return 3
"""
def replace_in_file(filename, old, new):
with open(filename, encoding="utf-8") as f:
content = f.read()
content = content.replace(old, new)
with open(filename, "w", encoding="utf-8", newline="\n") as f:
f.write(content)
def create_tmp_repo(tmp_dir):
"""
Creates a mock repository in a temporary folder for testing.
"""
tmp_dir = Path(tmp_dir)
if tmp_dir.exists():
shutil.rmtree(tmp_dir)
tmp_dir.mkdir(exist_ok=True)
model_dir = tmp_dir / "src" / "transformers" / "models"
model_dir.mkdir(parents=True, exist_ok=True)
models = {
"bert": MOCK_BERT_CODE,
"bertcopy": MOCK_BERT_COPY_CODE,
"dummy_bert_match": MOCK_DUMMY_BERT_CODE_MATCH,
"dummy_roberta_match": MOCK_DUMMY_ROBERTA_CODE_MATCH,
"dummy_bert_no_match": MOCK_DUMMY_BERT_CODE_NO_MATCH,
"dummy_roberta_no_match": MOCK_DUMMY_ROBERTA_CODE_NO_MATCH,
}
for model, code in models.items():
model_subdir = model_dir / model
model_subdir.mkdir(exist_ok=True)
with open(model_subdir / f"modeling_{model}.py", "w", encoding="utf-8", newline="\n") as f:
f.write(code)
@contextmanager
def patch_transformer_repo_path(new_folder):
"""
Temporarily patches the variables defines in `check_copies` to use a different location for the repo.
"""
old_repo_path = check_copies.REPO_PATH
old_doc_path = check_copies.PATH_TO_DOCS
old_transformer_path = check_copies.TRANSFORMERS_PATH
repo_path = Path(new_folder).resolve()
check_copies.REPO_PATH = str(repo_path)
check_copies.PATH_TO_DOCS = str(repo_path / "docs" / "source" / "en")
check_copies.TRANSFORMERS_PATH = str(repo_path / "src" / "transformers")
try:
yield
finally:
check_copies.REPO_PATH = old_repo_path
check_copies.PATH_TO_DOCS = old_doc_path
check_copies.TRANSFORMERS_PATH = old_transformer_path
| RobertaBertDummyModel |
python | doocs__leetcode | solution/2700-2799/2743.Count Substrings Without Repeating Character/Solution.py | {
"start": 0,
"end": 306
} | class ____:
def numberOfSpecialSubstrings(self, s: str) -> int:
cnt = Counter()
ans = j = 0
for i, c in enumerate(s):
cnt[c] += 1
while cnt[c] > 1:
cnt[s[j]] -= 1
j += 1
ans += i - j + 1
return ans
| Solution |
python | ray-project__ray | rllib/offline/tests/test_offline_prelearner.py | {
"start": 538,
"end": 12051
} | class ____(unittest.TestCase):
EXPECTED_KEYS = [
Columns.OBS,
Columns.NEXT_OBS,
Columns.ACTIONS,
Columns.REWARDS,
Columns.TERMINATEDS,
Columns.TRUNCATEDS,
"n_step",
]
@classmethod
def setUpClass(cls):
ray.init()
@classmethod
def tearDownClass(cls):
ray.shutdown()
def setUp(self) -> None:
data_path = "offline/tests/data/cartpole/cartpole-v1_large"
self.base_path = Path(__file__).parents[2]
self.data_path = "local://" + self.base_path.joinpath(data_path).as_posix()
# Get the observation and action spaces.
env = gym.make("CartPole-v1")
self.observation_space = env.observation_space
self.action_space = env.action_space
# Set up the configuration.
self.config = (
BCConfig()
.environment(
observation_space=self.observation_space,
action_space=self.action_space,
)
.api_stack(
enable_env_runner_and_connector_v2=True,
enable_rl_module_and_learner=True,
)
.offline_data(
input_=[self.data_path],
dataset_num_iters_per_learner=1,
)
.training(
train_batch_size_per_learner=256,
)
)
def test_offline_prelearner_buffer_class(self):
"""Tests using a user-defined buffer class with kwargs."""
from ray.rllib.utils.replay_buffers.prioritized_episode_buffer import (
PrioritizedEpisodeReplayBuffer,
)
sample_batch_data_path = (
self.base_path / "offline/tests/data/cartpole/large.json"
)
self.config.offline_data(
input_=["local://" + sample_batch_data_path.as_posix()],
# Note, for the data we need to read a JSON file.
input_read_method="read_json",
# Note, this has to be set to `True`.
input_read_sample_batches=True,
# Use a user-defined `PreLearner` class and kwargs.
prelearner_buffer_class=PrioritizedEpisodeReplayBuffer,
prelearner_buffer_kwargs={
"capacity": 2000,
"alpha": 0.8,
},
)
# Build the algorithm to get the learner.
algo = self.config.build()
# Get the module state from the `Learner`(s).
module_state = algo.offline_data.learner_handles[0].get_state(
component=COMPONENT_RL_MODULE,
)[COMPONENT_RL_MODULE]
# Set up an `OfflinePreLearner` instance.
oplr = OfflinePreLearner(
config=self.config,
module_spec=algo.offline_data.module_spec,
module_state=module_state,
)
# Ensure we have indeed a `PrioritizedEpisodeReplayBuffer` in the `PreLearner`
# with the `kwargs` we set.
self.assertIsInstance(oplr.episode_buffer, PrioritizedEpisodeReplayBuffer)
self.assertEqual(oplr.episode_buffer.capacity, 2000)
self.assertEqual(oplr.episode_buffer._alpha, 0.8)
# Now sample from the dataset and convert the `SampleBatch` in the `PreLearner`
# and sample episodes.
batch = algo.offline_data.data.take_batch(10)
batch = unflatten_dict(oplr(batch))
# Ensure all transformations worked and we have a `MultiAgentBatch`.
self.assertIsInstance(batch, dict)
# Ensure that we have as many environment steps as the train batch size.
self.assertEqual(
batch[DEFAULT_POLICY_ID][Columns.REWARDS].shape[0],
self.config.train_batch_size_per_learner,
)
# Ensure all keys are available and the length of each value is the
# train batch size.
for key in self.EXPECTED_KEYS:
self.assertIn(key, batch[DEFAULT_POLICY_ID])
self.assertEqual(
len(batch[DEFAULT_POLICY_ID][key]),
self.config.train_batch_size_per_learner,
)
def test_offline_prelearner_convert_to_episodes(self):
"""Tests conversion from column data to episodes."""
# Create the dataset.
data = ray.data.read_parquet(self.data_path)
# Now, take a small batch from the data and conert it to episodes.
batch = data.take_batch(batch_size=10)
episodes = OfflinePreLearner._map_to_episodes(False, batch)["episodes"]
self.assertTrue(len(episodes) == 10)
self.assertTrue(isinstance(episodes[0], SingleAgentEpisode))
def test_offline_prelearner_ignore_final_observation(self):
# Create the dataset.
data = ray.data.read_parquet(self.data_path)
# Now, take a small batch from the data and conert it to episodes.
batch = data.take_batch(batch_size=10)
episodes = OfflinePreLearner._map_to_episodes(
False, batch, ignore_final_observation=True
)["episodes"]
self.assertTrue(
all(all(eps.get_observations()[-1] == [0.0] * 4) for eps in episodes)
)
def test_offline_prelearner_convert_from_old_sample_batch_to_episodes(self):
"""Tests conversion from `SampleBatch` data to episodes."""
# Use the old records storing `SampleBatch`es.
sample_batch_data_path = (
self.base_path / "offline/tests/data/cartpole/large.json"
)
# Create the dataset.
data = ray.data.read_json(sample_batch_data_path.as_posix())
# Sample a small batch from the raw data.
batch = data.take_batch(batch_size=10)
# Convert `SampleBatch` data to episode data.
episodes = OfflinePreLearner._map_sample_batch_to_episode(False, batch)[
"episodes"
]
# Assert that we have sampled episodes.
self.assertTrue(len(episodes) == 10)
self.assertTrue(isinstance(episodes[0], SingleAgentEpisode))
def test_offline_prelearner_in_map_batches(self):
"""Tests using the `OfflinePreLearner` in `map_batches` where it is used
in `OfflineData`.
"""
# Create a simple dataset.
data = ray.data.read_parquet(self.data_path)
# Generate a batch iterator that uses the `OfflinePreLearner` to convert
# data to episodes.
batch_iterator = data.map_batches(
functools.partial(
OfflinePreLearner._map_to_episodes,
False,
)
).iter_batches(
batch_size=10,
prefetch_batches=1,
)
# Now sample a single batch.
batch = next(iter(batch_iterator))
# Assert that we have indeed sampled episodes.
self.assertTrue("episodes" in batch)
self.assertTrue(isinstance(batch["episodes"][0], SingleAgentEpisode))
def test_offline_prelearner_sample_from_old_sample_batch_data(self):
"""Tests sampling from a `SampleBatch` dataset."""
data_path = self.base_path / "offline/tests/data/cartpole/large.json"
self.config.offline_data(
input_=["local://" + data_path.as_posix()],
# Note, the default is `read_parquet`.
input_read_method="read_json",
# Signal that we want to read in old `SampleBatch` data.
input_read_sample_batches=True,
# Use a different input batch size b/c each `SampleBatch`
# contains multiple timesteps.
input_read_batch_size=50,
)
# Build the algorithm to get the learner.
algo = self.config.build()
# Get the module state from the `Learner`.
module_state = algo.offline_data.learner_handles[0].get_state(
component=COMPONENT_RL_MODULE,
)[COMPONENT_RL_MODULE]
# Set up an `OfflinePreLearner` instance.
oplr = OfflinePreLearner(
config=self.config,
module_spec=algo.offline_data.module_spec,
module_state=module_state,
)
# Now, pull a batch of defined size from the dataset.
batch = algo.offline_data.data.take_batch(
self.config.train_batch_size_per_learner
)
# Pass the batch through the `OfflinePreLearner`. Note, the batch is
# a batch of `SampleBatch`es and could potentially have more than the
# defined number of experiences to be used for learning.
# The `OfflinePreLearner`'s episode buffer should buffer all data
# and sample the exact size requested by the user, i.e.
# `train_batch_size_per_learner`
batch = unflatten_dict(oplr(batch))
# Ensure all transformations worked and we have a `MultiAgentBatch`.
self.assertIsInstance(batch, dict)
# Ensure that we have as many environment steps as the train batch size.
self.assertEqual(
batch[DEFAULT_POLICY_ID][Columns.REWARDS].shape[0],
self.config.train_batch_size_per_learner,
)
# Ensure all keys are available and the length of each value is the
# train batch size.
for key in self.EXPECTED_KEYS:
self.assertIn(key, batch[DEFAULT_POLICY_ID])
self.assertEqual(
len(batch[DEFAULT_POLICY_ID][key]),
self.config.train_batch_size_per_learner,
)
def test_offline_prelearner_sample_from_episode_data(self):
# Store data only temporary.
data_path = "/tmp/cartpole-v1_episodes/"
# Configure PPO for recording.
config = (
PPOConfig()
.environment(
env="CartPole-v1",
)
.env_runners(
batch_mode="complete_episodes",
)
.offline_data(
output=data_path,
output_write_episodes=True,
)
)
# Record some episodes.
algo = config.build()
for _ in range(3):
algo.train()
# Reset the input data and the episode read flag.
self.config.offline_data(
input_=[data_path],
input_read_episodes=True,
input_read_batch_size=50,
)
# Build the `BC` algorithm.
algo = self.config.build()
# Read in the generated set of episode data.
episode_ds = ray.data.read_parquet(data_path)
# Sample a batch of episodes from the episode dataset.
episode_batch = episode_ds.take_batch(256)
# Get the module state from the `Learner`.
module_state = algo.offline_data.learner_handles[0].get_state(
component=COMPONENT_RL_MODULE,
)[COMPONENT_RL_MODULE]
# Set up an `OfflinePreLearner` instance.
oplr = OfflinePreLearner(
config=self.config,
module_spec=algo.offline_data.module_spec,
module_state=module_state,
spaces=algo.offline_data.spaces[INPUT_ENV_SPACES],
)
# Sample a batch.
batch = unflatten_dict(oplr(episode_batch))
# Assert that we have indeed a batch of `train_batch_size_per_learner`.
self.assertEqual(
batch[DEFAULT_POLICY_ID][Columns.REWARDS].shape[0],
self.config.train_batch_size_per_learner,
)
# Remove all generated Parquet data from disk.
shutil.rmtree(data_path)
if __name__ == "__main__":
import sys
import pytest
sys.exit(pytest.main(["-v", __file__]))
| TestOfflinePreLearner |
python | huggingface__transformers | src/transformers/models/unispeech_sat/modeling_unispeech_sat.py | {
"start": 38308,
"end": 43691
} | class ____(UniSpeechSatPreTrainedModel):
def __init__(self, config: UniSpeechSatConfig):
super().__init__(config)
self.config = config
self.feature_extractor = UniSpeechSatFeatureEncoder(config)
self.feature_projection = UniSpeechSatFeatureProjection(config)
self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
if config.do_stable_layer_norm:
self.encoder = UniSpeechSatEncoderStableLayerNorm(config)
else:
self.encoder = UniSpeechSatEncoder(config)
# Initialize weights and apply final processing
self.post_init()
def _mask_hidden_states(
self,
hidden_states: torch.FloatTensor,
mask_time_indices: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
):
"""
Masks extracted features along time axis and/or along feature axis according to
[SpecAugment](https://huggingface.co/papers/1904.08779).
"""
# `config.apply_spec_augment` can set masking to False
if not getattr(self.config, "apply_spec_augment", True):
return hidden_states
# generate indices & apply SpecAugment along time axis
batch_size, sequence_length, hidden_size = hidden_states.size()
if mask_time_indices is not None:
# apply SpecAugment along time axis with given mask_time_indices
hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
elif self.config.mask_time_prob > 0 and self.training:
mask_time_indices = _compute_mask_indices(
(batch_size, sequence_length),
mask_prob=self.config.mask_time_prob,
mask_length=self.config.mask_time_length,
attention_mask=attention_mask,
min_masks=self.config.mask_time_min_masks,
)
mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)
hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
if self.config.mask_feature_prob > 0 and self.training:
# generate indices & apply SpecAugment along feature axis
mask_feature_indices = _compute_mask_indices(
(batch_size, hidden_size),
mask_prob=self.config.mask_feature_prob,
mask_length=self.config.mask_feature_length,
min_masks=self.config.mask_feature_min_masks,
)
mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)
mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)
hidden_states[mask_feature_indices] = 0
return hidden_states
@auto_docstring
def forward(
self,
input_values: Optional[torch.Tensor],
attention_mask: Optional[torch.Tensor] = None,
mask_time_indices: Optional[torch.FloatTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, UniSpeechSatBaseModelOutput]:
r"""
mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
masked extracted features in *config.proj_codevector_dim* space.
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
extract_features = self.feature_extractor(input_values)
extract_features = extract_features.transpose(1, 2)
if attention_mask is not None:
# compute reduced attention_mask corresponding to feature vectors
attention_mask = self._get_feature_vector_attention_mask(extract_features.shape[1], attention_mask)
hidden_states, extract_features = self.feature_projection(extract_features)
hidden_states = self._mask_hidden_states(
hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask
)
encoder_outputs = self.encoder(
hidden_states,
attention_mask=attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_states = encoder_outputs[0]
if not return_dict:
return (hidden_states, extract_features) + encoder_outputs[1:]
return UniSpeechSatBaseModelOutput(
last_hidden_state=hidden_states,
extract_features=extract_features,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
)
@auto_docstring(
custom_intro="""
UniSpeechSat Model with a vector-quantization module and ctc loss for pre-training.
"""
)
| UniSpeechSatModel |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 170776,
"end": 179111
} | class ____:
def f(self, *args, **kwargs):
return stats.percentileofscore(*args, **kwargs)
@pytest.mark.parametrize("kind, result", [("rank", 40),
("mean", 35),
("strict", 30),
("weak", 40)])
def test_unique(self, kind, result):
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
assert_equal(self.f(a, 4, kind=kind), result)
@pytest.mark.parametrize("kind, result", [("rank", 45),
("mean", 40),
("strict", 30),
("weak", 50)])
def test_multiple2(self, kind, result):
a = [1, 2, 3, 4, 4, 5, 6, 7, 8, 9]
assert_equal(self.f(a, 4, kind=kind), result)
@pytest.mark.parametrize("kind, result", [("rank", 50),
("mean", 45),
("strict", 30),
("weak", 60)])
def test_multiple3(self, kind, result):
a = [1, 2, 3, 4, 4, 4, 5, 6, 7, 8]
assert_equal(self.f(a, 4, kind=kind), result)
@pytest.mark.parametrize("kind, result", [("rank", 30),
("mean", 30),
("strict", 30),
("weak", 30)])
def test_missing(self, kind, result):
a = [1, 2, 3, 5, 6, 7, 8, 9, 10, 11]
assert_equal(self.f(a, 4, kind=kind), result)
@pytest.mark.parametrize("kind, result", [("rank", 40),
("mean", 35),
("strict", 30),
("weak", 40)])
def test_large_numbers(self, kind, result):
a = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
assert_equal(self.f(a, 40, kind=kind), result)
@pytest.mark.parametrize("kind, result", [("rank", 50),
("mean", 45),
("strict", 30),
("weak", 60)])
def test_large_numbers_multiple3(self, kind, result):
a = [10, 20, 30, 40, 40, 40, 50, 60, 70, 80]
assert_equal(self.f(a, 40, kind=kind), result)
@pytest.mark.parametrize("kind, result", [("rank", 30),
("mean", 30),
("strict", 30),
("weak", 30)])
def test_large_numbers_missing(self, kind, result):
a = [10, 20, 30, 50, 60, 70, 80, 90, 100, 110]
assert_equal(self.f(a, 40, kind=kind), result)
@pytest.mark.parametrize("kind, result", [("rank", [0, 10, 100, 100]),
("mean", [0, 5, 95, 100]),
("strict", [0, 0, 90, 100]),
("weak", [0, 10, 100, 100])])
def test_boundaries(self, kind, result):
a = [10, 20, 30, 50, 60, 70, 80, 90, 100, 110]
assert_equal(self.f(a, [0, 10, 110, 200], kind=kind), result)
@pytest.mark.parametrize("kind, result", [("rank", [0, 10, 100]),
("mean", [0, 5, 95]),
("strict", [0, 0, 90]),
("weak", [0, 10, 100])])
def test_inf(self, kind, result):
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, +np.inf]
assert_equal(self.f(a, [-np.inf, 1, +np.inf], kind=kind), result)
cases = [("propagate", [], 1, np.nan),
("propagate", [np.nan], 1, np.nan),
("propagate", [np.nan], [0, 1, 2], [np.nan, np.nan, np.nan]),
("propagate", [1, 2], [1, 2, np.nan], [50, 100, np.nan]),
("omit", [1, 2, np.nan], [0, 1, 2], [0, 50, 100]),
("omit", [1, 2], [0, 1, np.nan], [0, 50, np.nan]),
("omit", [np.nan, np.nan], [0, 1, 2], [np.nan, np.nan, np.nan])]
@pytest.mark.parametrize("policy, a, score, result", cases)
def test_nans_ok(self, policy, a, score, result):
assert_equal(self.f(a, score, nan_policy=policy), result)
cases = [
("raise", [1, 2, 3, np.nan], [1, 2, 3],
"The input contains nan values"),
("raise", [1, 2, 3], [1, 2, 3, np.nan],
"The input contains nan values"),
]
@pytest.mark.parametrize("policy, a, score, message", cases)
def test_nans_fail(self, policy, a, score, message):
with assert_raises(ValueError, match=message):
self.f(a, score, nan_policy=policy)
@pytest.mark.parametrize("shape", [
(6, ),
(2, 3),
(2, 1, 3),
(2, 1, 1, 3),
])
def test_nd(self, shape):
a = np.array([0, 1, 2, 3, 4, 5])
scores = a.reshape(shape)
results = scores*10
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
assert_equal(self.f(a, scores, kind="rank"), results)
def test_multidimensional_error(self):
# gh-21563 reported that `percentileofscore` accepted multidimensional
# arrays but did not produce meaningful results.
message = "`a` must be 1-dimensional."
with pytest.raises(ValueError, match=message):
stats.percentileofscore(np.ones((3, 3)), 1)
PowerDivCase = namedtuple('Case', # type: ignore[name-match]
['f_obs', 'f_exp', 'ddof', 'axis',
'chi2', # Pearson's
'log', # G-test (log-likelihood)
'mod_log', # Modified log-likelihood
'cr', # Cressie-Read (lambda=2/3)
])
# The details of the first two elements in power_div_1d_cases are used
# in a test in TestPowerDivergence. Check that code before making
# any changes here.
power_div_1d_cases = [
# Use the default f_exp.
PowerDivCase(f_obs=[4, 8, 12, 8], f_exp=None, ddof=0, axis=None,
chi2=4,
log=2*(4*np.log(4/8) + 12*np.log(12/8)),
mod_log=2*(8*np.log(8/4) + 8*np.log(8/12)),
cr=(4*((4/8)**(2/3) - 1) + 12*((12/8)**(2/3) - 1))/(5/9)),
# Give a non-uniform f_exp.
PowerDivCase(f_obs=[4, 8, 12, 8], f_exp=[2, 16, 12, 2], ddof=0, axis=None,
chi2=24,
log=2*(4*np.log(4/2) + 8*np.log(8/16) + 8*np.log(8/2)),
mod_log=2*(2*np.log(2/4) + 16*np.log(16/8) + 2*np.log(2/8)),
cr=(4*((4/2)**(2/3) - 1) + 8*((8/16)**(2/3) - 1) +
8*((8/2)**(2/3) - 1))/(5/9)),
# f_exp is a scalar.
PowerDivCase(f_obs=[4, 8, 12, 8], f_exp=8, ddof=0, axis=None,
chi2=4,
log=2*(4*np.log(4/8) + 12*np.log(12/8)),
mod_log=2*(8*np.log(8/4) + 8*np.log(8/12)),
cr=(4*((4/8)**(2/3) - 1) + 12*((12/8)**(2/3) - 1))/(5/9)),
# f_exp equal to f_obs.
PowerDivCase(f_obs=[3, 5, 7, 9], f_exp=[3, 5, 7, 9], ddof=0, axis=0,
chi2=0, log=0, mod_log=0, cr=0),
]
power_div_empty_cases = [
# Shape is (0,)--a data set with length 0. The computed
# test statistic should be 0.
PowerDivCase(f_obs=[],
f_exp=None, ddof=0, axis=0,
chi2=0, log=0, mod_log=0, cr=0),
# Shape is (0, 3). This is 3 data sets, but each data set has
# length 0, so the computed test statistic should be [0, 0, 0].
PowerDivCase(f_obs=np.array([[],[],[]]).T,
f_exp=None, ddof=0, axis=0,
chi2=[0, 0, 0],
log=[0, 0, 0],
mod_log=[0, 0, 0],
cr=[0, 0, 0]),
# Shape is (3, 0). This represents an empty collection of
# data sets in which each data set has length 3. The test
# statistic should be an empty array.
PowerDivCase(f_obs=np.array([[],[],[]]),
f_exp=None, ddof=0, axis=0,
chi2=[],
log=[],
mod_log=[],
cr=[]),
]
@make_xp_test_case(stats.power_divergence)
| TestPercentileOfScore |
python | MongoEngine__mongoengine | tests/fields/test_complex_base_field.py | {
"start": 103,
"end": 310
} | class ____(MongoDBTestCase):
def test_field_validation(self):
with pytest.raises(TypeError, match="field argument must be a Field instance"):
ComplexBaseField("test")
| TestComplexBaseField |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-file/llama_index/readers/file/docs/base.py | {
"start": 525,
"end": 3001
} | class ____(BaseReader):
"""PDF parser."""
def __init__(self, return_full_document: Optional[bool] = False) -> None:
"""
Initialize PDFReader.
"""
self.return_full_document = return_full_document
@retry(
stop=stop_after_attempt(RETRY_TIMES),
)
def load_data(
self,
file: Union[Path, PurePosixPath],
extra_info: Optional[Dict] = None,
fs: Optional[AbstractFileSystem] = None,
) -> List[Document]:
"""Parse file."""
fs = fs or get_default_fs()
_Path = Path if is_default_fs(fs) else PurePosixPath
if not isinstance(file, (Path, PurePosixPath)):
file = _Path(file)
try:
import pypdf
except ImportError:
raise ImportError(
"pypdf is required to read PDF files: `pip install pypdf`"
)
with fs.open(str(file), "rb") as fp:
# Load the file in memory if the filesystem is not the default one to avoid
# issues with pypdf
stream = fp if is_default_fs(fs) else io.BytesIO(fp.read())
# Create a PDF object
pdf = pypdf.PdfReader(stream)
# Get the number of pages in the PDF document
num_pages = len(pdf.pages)
docs = []
# This block returns a whole PDF as a single Document
if self.return_full_document:
metadata = {"file_name": file.name}
if extra_info is not None:
metadata.update(extra_info)
# Join text extracted from each page
text = "\n".join(
pdf.pages[page].extract_text() for page in range(num_pages)
)
docs.append(Document(text=text, metadata=metadata))
# This block returns each page of a PDF as its own Document
else:
# Iterate over every page
for page in range(num_pages):
# Extract the text from the page
page_text = pdf.pages[page].extract_text()
page_label = pdf.page_labels[page]
metadata = {"page_label": page_label, "file_name": file.name}
if extra_info is not None:
metadata.update(extra_info)
docs.append(Document(text=page_text, metadata=metadata))
return docs
| PDFReader |
python | django-haystack__django-haystack | haystack/fields.py | {
"start": 15365,
"end": 15427
} | class ____(FacetField, DecimalField):
pass
| FacetDecimalField |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 51053,
"end": 54908
} | class ____(BiffRecord):
"""
This record stores the position of window panes. It is part of the Sheet
View Settings Block. If the sheet does not contain any splits, this
record will not occur.
A sheet can be split in two different ways, with unfrozen panes or with
frozen panes. A flag in the WINDOW2 record specifies, if the panes are
frozen, which affects the contents of this record.
Record PANE, BIFF2-BIFF8:
Offset Size Contents
0 2 Position of the vertical split
(px, 0 = No vertical split):
Unfrozen pane: Width of the left pane(s)
(in twips = 1/20 of a point)
Frozen pane: Number of visible
columns in left pane(s)
2 2 Position of the horizontal split
(py, 0 = No horizontal split):
Unfrozen pane: Height of the top pane(s)
(in twips = 1/20 of a point)
Frozen pane: Number of visible
rows in top pane(s)
4 2 Index to first visible row
in bottom pane(s)
6 2 Index to first visible column
in right pane(s)
8 1 Identifier of pane with active
cell cursor
[9] 1 Not used (BIFF5-BIFF8 only, not written
in BIFF2-BIFF4)
If the panes are frozen, pane 0 is always active, regardless
of the cursor position. The correct identifiers for all possible
combinations of visible panes are shown in the following pictures.
px = 0, py = 0 px = 0, py > 0
-------------------------- ------------|-------------
| | | |
| | | 3 |
| | | |
- 3 - --------------------------
| | | |
| | | 2 |
| | | |
-------------------------- ------------|-------------
px > 0, py = 0 px > 0, py > 0
------------|------------- ------------|-------------
| | | | | |
| | | | 3 | 2 |
| | | | | |
- 3 | 1 - --------------------------
| | | | | |
| | | | 1 | 0 |
| | | | | |
------------|------------- ------------|-------------
"""
_REC_ID = 0x0041
valid_active_pane = {
# entries are of the form:
# (int(px > 0),int(px>0)) -> allowed values
(0,0):(3,),
(0,1):(2,3),
(1,0):(1,3),
(1,1):(0,1,2,3),
}
def __init__(self, px, py, first_row_bottom, first_col_right, active_pane):
allowed = self.valid_active_pane.get(
(int(px > 0),int(py > 0))
)
if active_pane not in allowed:
raise ValueError('Cannot set active_pane to %i, must be one of %s' % (
active_pane, ', '.join(allowed)
))
self._rec_data = pack('<5H',
px, py,
first_row_bottom, first_col_right,
active_pane)
| PanesRecord |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/list/retrievers.py | {
"start": 939,
"end": 1839
} | class ____(BaseRetriever):
"""
Simple retriever for SummaryIndex that returns all nodes.
Args:
index (SummaryIndex): The index to retrieve from.
"""
def __init__(
self,
index: SummaryIndex,
callback_manager: Optional[CallbackManager] = None,
object_map: Optional[dict] = None,
verbose: bool = False,
**kwargs: Any,
) -> None:
self._index = index
super().__init__(
callback_manager=callback_manager, object_map=object_map, verbose=verbose
)
def _retrieve(
self,
query_bundle: QueryBundle,
) -> List[NodeWithScore]:
"""Retrieve nodes."""
del query_bundle
node_ids = self._index.index_struct.nodes
nodes = self._index.docstore.get_nodes(node_ids)
return [NodeWithScore(node=node) for node in nodes]
| SummaryIndexRetriever |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 74007,
"end": 74280
} | class ____:
xlListConflictDialog = 0 # from enum XlListConflict
xlListConflictDiscardAllConflicts = 2 # from enum XlListConflict
xlListConflictError = 3 # from enum XlListConflict
xlListConflictRetryAllConflicts = 1 # from enum XlListConflict
| ListConflict |
python | google__jax | jax/_src/pallas/mosaic/core.py | {
"start": 6345,
"end": 6929
} | class ____(enum.Enum):
ANY = "any" # TODO(b/368401328): Remove this and just use pl.ANY.
VMEM = "vmem"
VMEM_SHARED = "vmem_shared"
SMEM = "smem"
CMEM = "cmem"
SEMAPHORE = "semaphore_mem"
HBM = "hbm"
HOST = "host"
def __str__(self) -> str:
return self.value
def from_type(self, ty):
return pallas_core.MemoryRef(ty, memory_space=self)
def __call__(self, shape: Sequence[int], dtype: jnp.dtype):
# A convenience function for constructing MemoryRef types of ShapedArrays.
return self.from_type(jax_core.ShapedArray(tuple(shape), dtype))
| MemorySpace |
python | doocs__leetcode | solution/0900-0999/0978.Longest Turbulent Subarray/Solution.py | {
"start": 0,
"end": 287
} | class ____:
def maxTurbulenceSize(self, arr: List[int]) -> int:
ans = f = g = 1
for a, b in pairwise(arr):
ff = g + 1 if a < b else 1
gg = f + 1 if a > b else 1
f, g = ff, gg
ans = max(ans, f, g)
return ans
| Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_selection02.py | {
"start": 315,
"end": 1255
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("selection02.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet1 = workbook.add_worksheet()
worksheet2 = workbook.add_worksheet()
worksheet3 = workbook.add_worksheet()
worksheet4 = workbook.add_worksheet()
worksheet5 = workbook.add_worksheet()
worksheet6 = workbook.add_worksheet()
worksheet1.set_selection(3, 2, 3, 2)
worksheet2.set_selection(3, 2, 6, 6)
worksheet3.set_selection(6, 6, 3, 2)
worksheet4.set_selection("C4")
worksheet5.set_selection("C4:G7")
worksheet6.set_selection("G7:C4")
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/quantum_espresso/package.py | {
"start": 216,
"end": 846
} | class ____(Package):
"""Used to test that a few problematic concretization
cases with the old concretizer have been solved by the
new ones.
"""
homepage = "http://www.example.com"
url = "http://www.example.com/qe-1.0.tar.gz"
version("1.0", md5="1234567890abcdef1234567890abcdef")
variant("invino", default=True, description="?")
variant("veritas", default=True, description="?")
depends_on("fftw@:1.0")
depends_on("fftw+mpi", when="+invino")
depends_on("openblas", when="^fftw@:1")
depends_on("libelf@0.8.10:")
depends_on("libelf@:0.8.12", when="+veritas")
| QuantumEspresso |
python | python-openxml__python-docx | tests/opc/test_part.py | {
"start": 6358,
"end": 11651
} | class ____:
def it_constructs_part_from_selector_if_defined(self, cls_selector_fixture):
# fixture ----------------------
(
cls_selector_fn_,
part_load_params,
CustomPartClass_,
part_of_custom_type_,
) = cls_selector_fixture
partname, content_type, reltype, blob, package = part_load_params
# exercise ---------------------
PartFactory.part_class_selector = cls_selector_fn_
part = PartFactory(partname, content_type, reltype, blob, package)
# verify -----------------------
cls_selector_fn_.assert_called_once_with(content_type, reltype)
CustomPartClass_.load.assert_called_once_with(partname, content_type, blob, package)
assert part is part_of_custom_type_
def it_constructs_custom_part_type_for_registered_content_types(
self, part_args_, CustomPartClass_, part_of_custom_type_
):
# fixture ----------------------
partname, content_type, reltype, package, blob = part_args_
# exercise ---------------------
PartFactory.part_type_for[content_type] = CustomPartClass_
part = PartFactory(partname, content_type, reltype, blob, package)
# verify -----------------------
CustomPartClass_.load.assert_called_once_with(partname, content_type, blob, package)
assert part is part_of_custom_type_
def it_constructs_part_using_default_class_when_no_custom_registered(
self, part_args_2_, DefaultPartClass_, part_of_default_type_
):
partname, content_type, reltype, blob, package = part_args_2_
part = PartFactory(partname, content_type, reltype, blob, package)
DefaultPartClass_.load.assert_called_once_with(partname, content_type, blob, package)
assert part is part_of_default_type_
# fixtures ---------------------------------------------
@pytest.fixture
def blob_(self, request):
return instance_mock(request, str)
@pytest.fixture
def blob_2_(self, request):
return instance_mock(request, str)
@pytest.fixture
def cls_method_fn_(self, request, cls_selector_fn_):
return function_mock(request, "docx.opc.part.cls_method_fn", return_value=cls_selector_fn_)
@pytest.fixture
def cls_selector_fixture(
self,
cls_selector_fn_,
cls_method_fn_,
part_load_params,
CustomPartClass_,
part_of_custom_type_,
):
original_part_class_selector = PartFactory.part_class_selector
yield (
cls_selector_fn_,
part_load_params,
CustomPartClass_,
part_of_custom_type_,
)
PartFactory.part_class_selector = original_part_class_selector
@pytest.fixture
def cls_selector_fn_(self, request, CustomPartClass_):
cls_selector_fn_ = loose_mock(request)
# Python 3 version
cls_selector_fn_.return_value = CustomPartClass_
# Python 2 version
cls_selector_fn_.__func__ = loose_mock(
request, name="__func__", return_value=cls_selector_fn_
)
return cls_selector_fn_
@pytest.fixture
def content_type_(self, request):
return instance_mock(request, str)
@pytest.fixture
def content_type_2_(self, request):
return instance_mock(request, str)
@pytest.fixture
def CustomPartClass_(self, request, part_of_custom_type_):
CustomPartClass_ = Mock(name="CustomPartClass", spec=Part)
CustomPartClass_.load.return_value = part_of_custom_type_
return CustomPartClass_
@pytest.fixture
def DefaultPartClass_(self, request, part_of_default_type_):
DefaultPartClass_ = cls_attr_mock(request, PartFactory, "default_part_type")
DefaultPartClass_.load.return_value = part_of_default_type_
return DefaultPartClass_
@pytest.fixture
def package_(self, request):
return instance_mock(request, OpcPackage)
@pytest.fixture
def package_2_(self, request):
return instance_mock(request, OpcPackage)
@pytest.fixture
def part_load_params(self, partname_, content_type_, reltype_, blob_, package_):
return partname_, content_type_, reltype_, blob_, package_
@pytest.fixture
def part_of_custom_type_(self, request):
return instance_mock(request, Part)
@pytest.fixture
def part_of_default_type_(self, request):
return instance_mock(request, Part)
@pytest.fixture
def partname_(self, request):
return instance_mock(request, PackURI)
@pytest.fixture
def partname_2_(self, request):
return instance_mock(request, PackURI)
@pytest.fixture
def part_args_(self, request, partname_, content_type_, reltype_, package_, blob_):
return partname_, content_type_, reltype_, blob_, package_
@pytest.fixture
def part_args_2_(self, request, partname_2_, content_type_2_, reltype_2_, package_2_, blob_2_):
return partname_2_, content_type_2_, reltype_2_, blob_2_, package_2_
@pytest.fixture
def reltype_(self, request):
return instance_mock(request, str)
@pytest.fixture
def reltype_2_(self, request):
return instance_mock(request, str)
| DescribePartFactory |
python | google__jax | tests/mosaic/gpu_test.py | {
"start": 100959,
"end": 123345
} | class ____(TestCase):
@parameterized.product(
swizzle=(None, 32, 64, 128),
shape=((64, None), (5, None), (2, 3, 5, None)),
dtype=(jnp.float32, jnp.float16, jnp.int4),
)
def test_tma_load_basic(self, swizzle, shape, dtype):
bw = bitwidth(dtype_to_ir_type(dtype))
minor_size = 64 if swizzle is None else 8 * swizzle // bw
shape = (*shape[:-1], minor_size)
i1 = ir.IntegerType.get_signless(1)
def kernel(ctx, src, dst, smem):
tmp, barrier = smem
ctx.async_copy(src_ref=src, dst_ref=tmp, swizzle=swizzle, barrier=barrier)
barrier.wait_parity(c(0, i1))
copy(tmp, dst, swizzle=swizzle)
x = np.arange(np.prod(shape), dtype=dtype).reshape(shape)
smem = (x, mgpu.TMABarrier())
y = mgpu.as_gpu_kernel(kernel, (1, 1, 1), (128, 1, 1), x, x, smem)(x)
np.testing.assert_array_equal(y, x)
@parameterized.product(
swizzle=(None, 32, 64, 128),
shape=((64, None), (5, None), (2, 3, 5, None)),
dtype=(jnp.float32, jnp.float16, jnp.int4),
)
def test_tma_prefetch_basic(self, swizzle, shape, dtype):
bw = bitwidth(dtype_to_ir_type(dtype))
minor_size = 64 if swizzle is None else 8 * swizzle // bw
shape = (*shape[:-1], minor_size)
i1 = ir.IntegerType.get_signless(1)
def kernel(ctx, src, dst, smem):
tmp, barrier = smem
ctx.async_prefetch(gmem_ref=src, swizzle=swizzle)
ctx.async_copy(src_ref=src, dst_ref=tmp, swizzle=swizzle, barrier=barrier)
barrier.wait_parity(c(0, i1))
copy(tmp, dst, swizzle=swizzle)
x = np.arange(np.prod(shape), dtype=dtype).reshape(shape)
smem = (x, mgpu.TMABarrier())
y = mgpu.as_gpu_kernel(kernel, (1, 1, 1), (128, 1, 1), x, x, smem)(x)
np.testing.assert_array_equal(y, x)
@parameterized.product(
swizzle=(16, 32, 64, 128),
shape=((64, None),),
dtype=(jnp.int32, jnp.int16),
idx_dtype=(jnp.int32, jnp.int8),
)
def test_tma_gather_basic(self, swizzle, shape, dtype, idx_dtype):
if not jtu.is_cuda_compute_capability_at_least("10.0"):
self.skipTest("TMA gather requires CUDA compute capability 10.0 or higher")
i1 = ir.IntegerType.get_signless(1)
swizzle_elems = 8 * swizzle // bitwidth(dtype_to_ir_type(dtype))
col_slice = swizzle_elems if swizzle != 16 else 128
shape = (*shape[:-1], 2 * col_slice)
def kernel(ctx, src, idx, dst, smem):
tmp, barrier = smem
idxs = mgpu.FragmentedArray.load_untiled(
idx, layout=fa.TMA_GATHER_INDICES_LAYOUT, optimized=False, is_signed=False
)
ctx.async_copy(
src_ref=src,
dst_ref=tmp,
swizzle=swizzle,
barrier=barrier,
gmem_slice=(idxs, mgpu.ds(col_slice, col_slice)),
)
barrier.wait_parity(c(0, i1))
copy(tmp, dst, swizzle=swizzle)
x = np.arange(np.prod(shape), dtype=dtype).reshape(shape)
idx = jax.random.permutation(jax.random.key(1234), 48).astype(idx_dtype)
out_type = jax.ShapeDtypeStruct((len(idx), col_slice), dtype)
smem = (out_type, mgpu.TMABarrier())
y = mgpu.as_gpu_kernel(
kernel, (1, 1, 1), (128, 1, 1), (x, idx), out_type, smem,
)(x, idx)
np.testing.assert_array_equal(y, x[idx, slice(col_slice, 2 * col_slice)])
@parameterized.product(
swizzle=(16, 32, 64, 128),
shape=((64, None),),
dtype=(jnp.int32, jnp.int16),
transpose_tiles=(False, True),
)
def test_tma_gather_tiled(self, swizzle, shape, dtype, transpose_tiles):
if not jtu.is_cuda_compute_capability_at_least("10.0"):
self.skipTest("TMA gather requires CUDA compute capability 10.0 or higher")
i1 = ir.IntegerType.get_signless(1)
swizzle_elems = 8 * swizzle // bitwidth(dtype_to_ir_type(dtype))
col_slice = swizzle_elems if swizzle != 16 else 128
shape = (*shape[:-1], 3 * col_slice)
# Using (8, swizzle_elems) produces too short transfers (we'd end up with
# misaligned SMEM addresses).
tiling = (8, swizzle_elems) if swizzle != 16 else (8, 2 * swizzle_elems)
if transpose_tiles:
transforms = (mgpu.TileTransform(tiling), mgpu.TransposeTransform((1, 0, 2, 3)))
else:
transforms = mgpu.TileTransform(tiling)
def kernel(ctx, src, idx, dst, smem):
tmp, barrier = smem
idxs = mgpu.FragmentedArray.load_untiled(
idx, layout=fa.TMA_GATHER_INDICES_LAYOUT, optimized=False, is_signed=False
)
ctx.async_copy(
src_ref=src,
dst_ref=tmp,
swizzle=swizzle,
barrier=barrier,
gmem_slice=(idxs, mgpu.ds(col_slice, 2 * col_slice)),
gmem_transform=transforms,
)
barrier.wait_parity(c(0, i1))
ctx.async_copy(
src_ref=tmp,
dst_ref=dst,
swizzle=swizzle,
gmem_transform=transforms,
)
ctx.await_async_copy(0)
x = np.arange(np.prod(shape), dtype=dtype).reshape(shape)
idx = jax.random.permutation(jax.random.key(1234), 48).astype(jnp.int32)
out_type = jax.ShapeDtypeStruct((len(idx), 2 * col_slice), dtype)
smem_shape = tile_shape((len(idx), 2 * col_slice), tiling)
if transpose_tiles:
smem_shape = (smem_shape[1], smem_shape[0], *smem_shape[2:])
smem = (
jax.ShapeDtypeStruct(smem_shape, dtype),
mgpu.TMABarrier(),
)
y = mgpu.as_gpu_kernel(
kernel, (1, 1, 1), (128, 1, 1), (x, idx), out_type, smem,
)(x, idx)
np.testing.assert_array_equal(y, x[idx, slice(col_slice, 3 * col_slice)])
def test_tma_with_1d_tiling(self):
swizzle = 128
dtype = jnp.float16
shape = (64, 128)
tiling = (1, swizzle // jnp.dtype(dtype).itemsize)
def kernel(ctx, dst, smem):
iota_tensor(*shape, dtype=dtype).store_tiled(smem, swizzle=swizzle)
ctx.async_copy(
src_ref=smem,
dst_ref=dst,
swizzle=swizzle,
gmem_transform=mgpu.TileTransform(tiling),
)
ctx.await_async_copy(0)
x = np.arange(np.prod(shape), dtype=dtype).reshape(shape)
smem = jax.ShapeDtypeStruct(utils.tile_shape(shape, tiling), dtype)
y = mgpu.as_gpu_kernel(kernel, (1, 1, 1), (128, 1, 1), (), x, smem)()
np.testing.assert_array_equal(y, x)
@parameterized.named_parameters(
(
f"_{''.join(map(str, collective_dims))}={collective_size}{'_' + ''.join(map(str, noncollective_dims)) if noncollective_dims else ''}",
collective_dims,
noncollective_dims,
collective_size,
)
for collective_dims in itertools.chain.from_iterable(
itertools.combinations(Dimension, n) for n in range(1, 4)
)
for noncollective_dims in itertools.chain.from_iterable(
itertools.combinations(Dimension, n) for n in range(3)
)
for collective_size in (1, 2, 4)
if all(d not in noncollective_dims for d in collective_dims)
)
def test_tma_load_multicast(self, collective_dims, noncollective_dims, collective_dim_size):
index = ir.IndexType.get()
swizzle = 128
dtype = jnp.float16
cluster = [1, 1, 1]
for d in collective_dims:
cluster[d] = collective_dim_size
for d in noncollective_dims:
cluster[d] = 2
if math.prod(cluster) > jtu.get_cuda_nonportable_max_cluster_size():
self.skipTest("Cluster too big")
collective_size = math.prod(cluster[d] for d in collective_dims)
noncollective_size = math.prod(cluster) // collective_size
# We use the 2 dimension to exercise splitting the collective over
# multiple dimensions when the cluster is large.
shape = (noncollective_size, 2, 16 * collective_size, 64)
minor_size = 64 if swizzle is None else swizzle // jnp.dtype(dtype).itemsize
shape = (*shape[:-1], minor_size)
# Note that this kernel does not use the non-collective dimensions in any
# interesting way and so they don't really have to be part of the cluster.
# We use them to test that the multicast mask is generated correctly.
def kernel(ctx, src, dst, scratch):
tmp, barrier = scratch
stride = 1
noncollective_idx = c(0, index)
for d in noncollective_dims:
noncollective_idx = arith.addi(
noncollective_idx,
arith.muli(gpu.cluster_block_id(d), c(stride, index))
)
stride *= cluster[d]
ctx.async_copy(
src_ref=src,
dst_ref=tmp,
gmem_slice=(noncollective_idx,),
swizzle=swizzle,
barrier=barrier,
collective=collective_dims,
)
barrier.wait()
# This is _not_ the real cluster block idx, because it does not consider
# the column-major ordering of the grid dimensions.
idx = c(0, index)
stride = 1
for d in collective_dims:
idx = arith.addi(
idx, arith.muli(gpu.cluster_block_id(d), c(stride, index))
)
stride *= cluster[d]
idx_minor = arith.divui(idx, c(2, index))
idx_major = arith.remui(idx, c(2, index))
slc_minor = ds(
arith.muli(idx_minor, c(16 * 2, index)), 16 * 2
)
copy(
memref_slice(tmp, (idx_major, slc_minor)),
memref_slice(dst, (noncollective_idx, idx_major, slc_minor)),
swizzle=swizzle,
)
x = np.arange(np.prod(shape), dtype=dtype).reshape(shape)
smem_shape = (jax.ShapeDtypeStruct(shape[1:], dtype), mgpu.TMABarrier())
y = mgpu.as_gpu_kernel(
kernel, cluster, (128, 1, 1), x, x, smem_shape, cluster=cluster
)(x)
np.testing.assert_array_equal(y, x)
@parameterized.product(
swizzle=(None, 128),
shape=((128, 128), (5, 32, 128)),
dtype=(jnp.float16, jnp.float32),
)
def test_tma_load_tiled(self, swizzle, shape, dtype):
# TODO(apaszke): ptxas seems to freeze when generating code for copy with
# swizzle 32 and 64.
i1 = ir.IntegerType.get_signless(1)
index = ir.IndexType.get()
tiling = (32, (swizzle or 128) // jnp.dtype(dtype).itemsize)
tiled_shape = tile_shape(shape, tiling)[:len(shape)]
def kernel(ctx, src, dst, scratch):
tmp, barrier = scratch
ctx.async_copy(
src_ref=src,
dst_ref=tmp,
swizzle=swizzle,
barrier=barrier,
gmem_transform=mgpu.TileTransform(tiling),
)
barrier.wait_parity(c(0, i1))
for idxs in np.ndindex(tiled_shape):
untiled_idxs, tiled_idxs = idxs[:-len(tiling)], idxs[-len(tiling):]
s = (
*untiled_idxs,
*(ds(c(ix * t, index), t) for ix, t in zip(tiled_idxs, tiling)),
)
copy(memref_slice(tmp, idxs), memref_slice(dst, s), swizzle=swizzle)
x = np.arange(np.prod(shape), dtype=dtype).reshape(shape)
smem = (
jax.ShapeDtypeStruct(tile_shape(shape, tiling), dtype),
mgpu.TMABarrier(),
)
f = mgpu.as_gpu_kernel(kernel, (1, 1, 1), (128, 1, 1), x, x, smem)
y = f(x)
np.testing.assert_array_equal(y, x)
@parameterized.product(
swizzle=(None, 128),
shape=((128, 128), (5, 32, 128)),
dtype=(jnp.float16, jnp.float32),
)
@jtu.thread_unsafe_test()
def test_tma_prefetch_tiled(self, swizzle, shape, dtype):
# TODO(apaszke): ptxas seems to freeze when generating code for copy with
# swizzle 32 and 64.
i1 = ir.IntegerType.get_signless(1)
index = ir.IndexType.get()
tiling = (32, (swizzle or 128) // jnp.dtype(dtype).itemsize)
tiled_shape = tile_shape(shape, tiling)[:len(shape)]
def kernel(ctx, src, dst, scratch):
tmp, barrier = scratch
ctx.async_prefetch(
gmem_ref=src, swizzle=swizzle, gmem_transform=mgpu.TileTransform(tiling)
)
ctx.async_copy(
src_ref=src,
dst_ref=tmp,
swizzle=swizzle,
barrier=barrier,
gmem_transform=mgpu.TileTransform(tiling),
)
barrier.wait_parity(c(0, i1))
for idxs in np.ndindex(tiled_shape):
untiled_idxs, tiled_idxs = idxs[:-len(tiling)], idxs[-len(tiling):]
s = (
*untiled_idxs,
*(ds(c(ix * t, index), t) for ix, t in zip(tiled_idxs, tiling)),
)
copy(memref_slice(tmp, idxs), memref_slice(dst, s), swizzle=swizzle)
x = np.arange(np.prod(shape), dtype=dtype).reshape(shape)
smem = (
jax.ShapeDtypeStruct(tile_shape(shape, tiling), dtype),
mgpu.TMABarrier(),
)
env_vars = {
"MOSAIC_GPU_DUMP_HOST_LLVM": "1",
"MOSAIC_GPU_DUMP_PTX": "1",
}
with jtu.set_env(**env_vars), self.capture_stdout() as ptx_llvm_ir:
f = mgpu.as_gpu_kernel(kernel, (1, 1, 1), (128, 1, 1), x, x, smem)
y = f(x)
# We should only create one descriptor for both prefetch and copy.
self.assertEqual(ptx_llvm_ir().count("call void @mosaic_gpu_init_tma_desc("), 1)
self.assertIn("cp.async.bulk.prefetch.tensor", ptx_llvm_ir())
np.testing.assert_array_equal(y, x)
@parameterized.product(swizzle=(None, 128))
def test_tma_load_tiled_rounding(self, swizzle):
# TODO(apaszke): ptxas seems to freeze when generating code for copy with
# swizzle 32 and 64.
shape = (5, 32, 144)
dtype = jnp.float16
i1 = ir.IntegerType.get_signless(1)
index = ir.IndexType.get()
tiling = (32, (swizzle or 128) // jnp.dtype(dtype).itemsize)
rounded_shape = (*shape[:-1], shape[-1] // tiling[-1] * tiling[-1])
tiled_shape = tile_shape(rounded_shape, tiling)[:len(shape)]
def kernel(ctx, src, dst, scratch):
tmp, barrier = scratch
ctx.async_copy(
src_ref=src,
dst_ref=tmp,
swizzle=swizzle,
barrier=barrier,
gmem_transform=mgpu.TileTransform(
tiling, rounding=mgpu.Rounding.DOWN
),
)
barrier.wait_parity(c(0, i1))
for idxs in np.ndindex(tiled_shape):
untiled_idxs, tiled_idxs = idxs[:-len(tiling)], idxs[-len(tiling):]
s = (
*untiled_idxs,
*(ds(c(ix * t, index), t) for ix, t in zip(tiled_idxs, tiling)),
)
copy(memref_slice(tmp, idxs), memref_slice(dst, s), swizzle=swizzle)
x = np.arange(np.prod(shape), dtype=dtype).reshape(shape)
tmp_shape = jax.ShapeDtypeStruct(tile_shape(rounded_shape, tiling), dtype)
smem = (tmp_shape, mgpu.TMABarrier())
out_shape = jax.ShapeDtypeStruct(rounded_shape, dtype)
f = mgpu.as_gpu_kernel(kernel, (1, 1, 1), (128, 1, 1), x, out_shape, smem)
y = f(x)
np.testing.assert_array_equal(y, x[..., :rounded_shape[-1]])
def test_tma_load_indexed_tiled(self):
shape = (128, 2, 128)
tiling = mgpu.TileTransform((32, 32))
def kernel(ctx, src, dst, scratch):
tmp, barrier = scratch
ctx.async_copy(
src_ref=src,
dst_ref=tmp,
barrier=barrier,
gmem_transform=tiling,
gmem_slice=(slice(None), 1, slice(None)),
)
barrier.wait()
ctx.async_copy(src_ref=tmp, dst_ref=dst, gmem_transform=tiling)
ctx.await_async_copy(0)
x = np.arange(np.prod(shape), dtype=jnp.float32).reshape(shape)
smem = (
jax.ShapeDtypeStruct((4, 4, 32, 32), jnp.float32),
mgpu.TMABarrier(),
)
out_shape = jax.ShapeDtypeStruct((128, 128), jnp.float32)
f = mgpu.as_gpu_kernel(kernel, (1, 1, 1), (128, 1, 1), x, out_shape, smem)
np.testing.assert_array_equal(f(x), x[:, 1, :])
@parameterized.product(
swizzle=(None, 128),
dtype=(jnp.float16, jnp.float32),
)
def test_tma_squeeze_indexing(self, swizzle, dtype):
# TODO(apaszke): ptxas seems to freeze when generating code for copy with
# swizzle 32 and 64.
minor_size = 64 if swizzle is None else swizzle // jnp.dtype(dtype).itemsize
shape = (4, 5, minor_size)
def kernel(ctx, src, dst, smem):
tmp, barrier = smem
for i in range(4):
ctx.async_copy(
src_ref=src,
dst_ref=memref_slice(tmp, i),
gmem_slice=i,
swizzle=swizzle,
barrier=barrier,
)
barrier.wait()
copy(tmp, dst, swizzle=swizzle)
x = np.arange(np.prod(shape), dtype=dtype).reshape(shape)
smem = (x, mgpu.TMABarrier())
y = mgpu.as_gpu_kernel(kernel, (1, 1, 1), (128, 1, 1), x, x, smem)(x)
np.testing.assert_array_equal(y, x)
def test_parity_tracking(self):
shape = (16, 64)
index = ir.IndexType.get()
def kernel(ctx, src, dst, smem):
tmp, barrier = smem
for i in range(shape[0]):
s = ds(c(i, index), 1)
ctx.async_copy(
src_ref=src, dst_ref=tmp, gmem_slice=s, barrier=barrier,
)
barrier.wait()
copy(tmp, memref_slice(dst, s))
x = np.arange(np.prod(shape), dtype=jnp.float16).reshape(shape)
y = mgpu.as_gpu_kernel(
kernel, (1, 1, 1), (128, 1, 1), x, x, (x[0:1], mgpu.TMABarrier())
)(x)
np.testing.assert_array_equal(y, x)
@parameterized.product(
swizzle=(None, 32, 64, 128),
shape=((64, None), (5, None), (2, 3, 5, None)),
dtype=(jnp.float16, jnp.float32),
)
def test_tma_store(self, swizzle, shape, dtype):
minor_size = 64 if swizzle is None else swizzle // jnp.dtype(dtype).itemsize
shape = (*shape[:-1], minor_size)
def kernel(ctx, src, dst, tmp):
copy(src, tmp, swizzle=swizzle)
ctx.async_copy(src_ref=tmp, dst_ref=dst, swizzle=swizzle)
ctx.await_async_copy(0)
x = np.arange(np.prod(shape), dtype=dtype).reshape(shape)
y = mgpu.as_gpu_kernel(kernel, (1, 1, 1), (128, 1, 1), x, x, x)(x)
np.testing.assert_array_equal(y, x)
@parameterized.parameters(0, 1)
def test_tma_small_tile_load(self, small_dim):
if small_dim == 0:
shape = (4, 128)
elif small_dim == 1:
shape = (128, 8)
else:
raise ValueError("small_dim must be 0 or 1")
tiled_shape = ((shape[0] + 63) // 64, (shape[1] + 63) // 64, 64, 64)
padded_shape = (math.prod(tiled_shape[0::2]), math.prod(tiled_shape[1::2]))
def kernel(ctx, src, dst, smem):
tmp, barrier = smem
ctx.async_copy(
src_ref=src,
dst_ref=tmp,
swizzle=128,
gmem_transform=mgpu.TileTransform((64, 64)),
gmem_slice=(ds(0, padded_shape[0]), ds(0, padded_shape[1])),
barrier=barrier,
)
barrier.wait()
copy(tmp, dst, swizzle=128)
x = np.arange(np.prod(shape), dtype=jnp.float16).reshape(shape)
tiled = jax.ShapeDtypeStruct(tiled_shape, jnp.float16)
y_tiled = mgpu.as_gpu_kernel(
kernel, (1, 1, 1), (128, 1, 1), x, tiled, (tiled, mgpu.TMABarrier()),
)(x)
y = y_tiled.swapaxes(1, 2).reshape(padded_shape)
# y should contain x and zero everywhere else.
np.testing.assert_array_equal(y[:shape[0], :shape[1]], x)
y_mut = np.asarray(y).copy()
y_mut[:shape[0], :shape[1]] = 0
np.testing.assert_array_equal(y_mut, np.zeros_like(y_mut))
@parameterized.product(small_dim=(0, 1),)
def test_tma_small_tile_store(self, small_dim):
if small_dim == 0:
shape = (4, 128)
elif small_dim == 1:
shape = (128, 8)
else:
raise ValueError("small_dim must be 0 or 1")
tiled_shape = ((shape[0] + 63) // 64, (shape[1] + 63) // 64, 64, 64)
m, n = (math.prod(tiled_shape[0::2]), math.prod(tiled_shape[1::2]))
def kernel(ctx, dst, tmp):
vals = iota_tensor(m, n, jnp.float16)
vals.store_tiled(tmp, swizzle=128)
ctx.async_copy(
src_ref=tmp,
dst_ref=dst,
swizzle=128,
gmem_transform=mgpu.TileTransform((64, 64)),
gmem_slice=(ds(0, m), ds(0, n)),
)
ctx.await_async_copy(0)
tiled = jax.ShapeDtypeStruct(tiled_shape, jnp.float16)
out = jax.ShapeDtypeStruct(shape, jnp.float16)
y = mgpu.as_gpu_kernel(
kernel, (1, 1, 1), (128, 1, 1), (), out, tiled,
)()
iota = np.arange(m * n, dtype=jnp.float16).reshape([m, n])
np.testing.assert_array_equal(y, iota[:shape[0], :shape[1]])
def test_tma_invalid(self):
def kernel(ctx, src, dst, tmp):
copy(src, tmp)
ctx.async_copy(src_ref=tmp, dst_ref=dst)
ctx.await_async_copy(0)
def run_kernel(shape):
x = np.arange(np.prod(shape), dtype=np.int32).reshape(shape)
_ = mgpu.as_gpu_kernel(kernel, (1, 1, 1), (128, 1, 1), x, x, x)(x)
with self.assertRaisesRegex(ValueError, "all GMEM strides except the last"):
run_kernel([1] * 6)
with self.assertRaisesRegex(
ValueError, "last dimension to be divisible by 128"
):
run_kernel([23])
@parameterized.product(
swizzle=(16, 32, 64, 128),
shape=((64, 128), (128, 32)),
dtype=(jnp.float32, jnp.float16, jnp.float8_e5m2, jnp.int4),
)
def test_cp_async(self, swizzle, shape, dtype):
bw = bitwidth(dtype_to_ir_type(dtype))
swizzle_elems = 8 * swizzle // bw
tiling = (8, swizzle_elems)
if shape[-1] < swizzle_elems:
self.skipTest("Minor dimension too small")
minor_size = 64 if swizzle is None else swizzle_elems
shape = (*shape[:-1], minor_size)
def kernel(ctx, src, dst, tmp):
ctx.async_copy(
src_ref=src,
dst_ref=tmp,
swizzle=swizzle,
gmem_transform=mgpu.TileTransform(tiling),
implementation=mgpu.AsyncCopyImplementation.CP_ASYNC,
)
ctx.await_cp_async_copy(0)
mgpu.copy_tiled(tmp, dst, swizzle=swizzle)
x = np.arange(np.prod(shape), dtype=dtype).reshape(shape)
smem = jax.ShapeDtypeStruct(mgpu.tile_shape(shape, tiling), dtype)
y = mgpu.as_gpu_kernel(kernel, (1, 1, 1), (128, 1, 1), x, x, smem)(x)
np.testing.assert_array_equal(y, x)
def test_tma_collective_async_cp_with_no_swizzle(self):
def body(ctx, src, dst, scratch):
tmp, barrier = scratch
ctx.async_copy(
src_ref=src, dst_ref=tmp, collective=gpu.Dimension.x, barrier=barrier
)
barrier.wait()
block_id = gpu.cluster_block_id(gpu.Dimension.x)
ctx.async_copy(src_ref=tmp, dst_ref=dst, gmem_slice=block_id)
dtype = jnp.float32
kernel = mgpu.as_gpu_kernel(
body,
grid=(2, 1, 1),
cluster=(2, 1, 1),
block=(128, 1, 1),
in_shape=jax.ShapeDtypeStruct((128,), dtype),
out_shape=jax.ShapeDtypeStruct((2, 128), dtype),
smem_scratch_shape=[
jax.ShapeDtypeStruct((128,), dtype),
mgpu.TMABarrier(),
],
)
x = jnp.arange(128, dtype=jnp.float32)
np.testing.assert_array_equal(kernel(x), jnp.stack([x, x], axis=0))
| AsyncCopyTest |
python | huggingface__transformers | src/transformers/models/doge/modular_doge.py | {
"start": 11531,
"end": 13220
} | class ____(LlamaRotaryEmbedding):
pass
def flex_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Union[torch.Tensor, "BlockMask"],
scaling: Optional[float] = None,
softcap: Optional[float] = None,
**kwargs,
) -> tuple[torch.Tensor, torch.Tensor]:
block_mask = None
causal_mask = None
if isinstance(attention_mask, BlockMask):
block_mask = attention_mask
else:
causal_mask = attention_mask
if causal_mask is not None:
causal_mask = causal_mask[:, :, :, : key.shape[-2]]
def score_mod(score, batch_idx, head_idx, q_idx, kv_idx):
if softcap is not None:
score = softcap * torch.tanh(score / softcap)
if causal_mask is not None:
score = score + causal_mask[batch_idx][head_idx][q_idx][kv_idx]
return score
attn_output, attention_weights = compile_friendly_flex_attention(
query,
key,
value,
score_mod=score_mod,
block_mask=block_mask,
enable_gqa=True,
scale=scaling,
# Last time checked on PyTorch == 2.5.1: Flex Attention always computes the lse regardless.
# For simplification, we thus always return it as no additional computations are introduced.
return_lse=True,
)
# lse is returned in float32
attention_weights = attention_weights.to(value.dtype)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attention_weights
ALL_ATTENTION_FUNCTIONS = AttentionInterface()
ALL_ATTENTION_FUNCTIONS["doge_flex_attention"] = flex_attention_forward
| DogeRotaryEmbedding |
python | keras-team__keras | keras/src/losses/losses_test.py | {
"start": 37200,
"end": 41884
} | class ____(testing.TestCase):
def test_config(self):
self.run_class_serialization_test(
losses.BinaryCrossentropy(name="bce", axis=-1)
)
def test_all_correct_unweighted(self):
y_true = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype="float32")
bce_obj = losses.BinaryCrossentropy()
loss = bce_obj(y_true, y_true)
self.assertAlmostEqual(loss, 0.0)
# Test with logits.
logits = np.array(
[
[10.0, -10.0, -10.0],
[-10.0, 10.0, -10.0],
[-10.0, -10.0, 10.0],
]
)
bce_obj = losses.BinaryCrossentropy(from_logits=True)
loss = bce_obj(y_true, logits)
self.assertAlmostEqual(loss, 0.0)
def test_unweighted(self):
y_true = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype="float32")
y_pred = np.array(
[[0.9, 0.1, 0.2], [0.3, 0.8, 0.1], [0.1, 0.2, 0.7]], dtype="float32"
)
bce_obj = losses.BinaryCrossentropy()
loss = bce_obj(y_true, y_pred)
self.assertAllClose(loss, 0.20046903)
y_true = np.array([1, 0, 1, 0]).reshape([2, 2])
y_pred = np.array([1, 1, 1, 0], dtype=np.float32).reshape([2, 2])
bce_obj = losses.BinaryCrossentropy()
loss = bce_obj(y_true, y_pred)
self.assertAlmostEqual(loss, 3.98559)
# Test with logits.
y_true = np.array([[1, 0, 1], [0, 1, 1]])
logits = np.array([[10.0, -10.0, 10.0], [10.0, 10.0, -10.0]])
bce_obj = losses.BinaryCrossentropy(from_logits=True)
loss = bce_obj(y_true, logits)
self.assertAlmostEqual(loss, 3.3333)
def test_scalar_weighted(self):
bce_obj = losses.BinaryCrossentropy()
y_true = np.array([1, 0, 1, 0]).reshape([2, 2])
y_pred = np.array([1, 1, 1, 0], dtype="float32").reshape([2, 2])
loss = bce_obj(y_true, y_pred, sample_weight=2.3)
self.assertAlmostEqual(loss, 9.1668)
# Test with logits.
y_true = np.array([[1, 0, 1], [0, 1, 1]])
logits = np.array([[10.0, -10.0, 10.0], [10.0, 10.0, -10.0]])
bce_obj = losses.BinaryCrossentropy(from_logits=True)
loss = bce_obj(y_true, logits, sample_weight=2.3)
self.assertAlmostEqual(loss, 7.666)
def test_sample_weighted(self):
bce_obj = losses.BinaryCrossentropy()
y_true = np.array([1, 0, 1, 0]).reshape([2, 2])
y_pred = np.array([1, 1, 1, 0], dtype="float32").reshape([2, 2])
sample_weight = np.array([1.2, 3.4]).reshape((2, 1))
loss = bce_obj(y_true, y_pred, sample_weight=sample_weight)
self.assertAlmostEqual(loss, 4.7827)
# Test with logits.
y_true = np.array([[1, 0, 1], [0, 1, 1]])
logits = np.array([[10.0, -10.0, 10.0], [10.0, 10.0, -10.0]])
weights = np.array([4, 3])
bce_obj = losses.BinaryCrossentropy(from_logits=True)
loss = bce_obj(y_true, logits, sample_weight=weights)
self.assertAlmostEqual(loss, 10.0)
def test_no_reduction(self):
y_true = np.array([[1, 0, 1], [0, 1, 1]])
logits = np.array([[10.0, -10.0, 10.0], [10.0, 10.0, -10.0]])
bce_obj = losses.BinaryCrossentropy(from_logits=True, reduction=None)
loss = bce_obj(y_true, logits)
self.assertAllClose(loss, [0.0, 6.666], atol=1e-3)
def test_label_smoothing(self):
logits = np.array([[10.0, -10.0, -10.0]])
y_true = np.array([[1, 0, 1]])
label_smoothing = 0.1
bce_obj = losses.BinaryCrossentropy(
from_logits=True, label_smoothing=label_smoothing
)
loss = bce_obj(y_true, logits)
expected_value = (10.0 + 5.0 * label_smoothing) / 3.0
self.assertAlmostEqual(loss, expected_value)
def test_shape_mismatch(self):
y_true = np.array([[0], [1], [2]])
y_pred = np.array(
[[0.9, 0.05, 0.05], [0.5, 0.89, 0.6], [0.05, 0.01, 0.94]]
)
cce_obj = losses.BinaryCrossentropy()
with self.assertRaisesRegex(ValueError, "must have the same shape"):
cce_obj(y_true, y_pred)
@pytest.mark.skipif(
backend.backend() == "torch",
reason="Torch doesn't support bfloat16 for BinaryCrossentropy",
)
def test_dtype_arg(self):
y_true = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype="float32")
y_pred = np.array(
[[0.9, 0.1, 0.2], [0.3, 0.8, 0.1], [0.1, 0.2, 0.7]], dtype="float32"
)
bce_obj = losses.BinaryCrossentropy(dtype="bfloat16")
loss = bce_obj(y_true, y_pred)
self.assertDType(loss, "bfloat16")
| BinaryCrossentropyTest |
python | bokeh__bokeh | tests/unit/bokeh/models/test_ranges.py | {
"start": 1413,
"end": 4230
} | class ____:
def test_basic(self) -> None:
r = Range1d()
check_properties_existence(r, [
"start",
"end",
"reset_start",
"reset_end",
"bounds",
"min_interval",
"max_interval",
])
def test_qualified(self) -> None:
assert Range1d.__qualified_model__ == "Range1d"
def test_init_with_timedelta(self) -> None:
range1d = Range1d(start=-dt.timedelta(seconds=5), end=dt.timedelta(seconds=3))
assert range1d.start == -dt.timedelta(seconds=5)
assert range1d.end == dt.timedelta(seconds=3)
assert range1d.bounds is None
def test_init_with_datetime(self) -> None:
range1d = Range1d(start=dt.datetime(2016, 4, 28, 2, 20, 50), end=dt.datetime(2017, 4, 28, 2, 20, 50))
assert range1d.start == dt.datetime(2016, 4, 28, 2, 20, 50)
assert range1d.end == dt.datetime(2017, 4, 28, 2, 20, 50)
assert range1d.bounds is None
def test_init_with_float(self) -> None:
range1d = Range1d(start=-1.0, end=3.0)
assert range1d.start == -1.0
assert range1d.end == 3.0
assert range1d.bounds is None
def test_init_with_int(self) -> None:
range1d = Range1d(start=-1, end=3)
assert range1d.start == -1
assert range1d.end == 3
assert range1d.bounds is None
def test_init_with_positional_arguments(self) -> None:
range1d = Range1d(1, 2)
assert range1d.start == 1
assert range1d.end == 2
assert range1d.bounds is None
def test_init_with_keyword_arguments(self) -> None:
range1d = Range1d(start=1, end=2)
assert range1d.start == 1
assert range1d.end == 2
assert range1d.bounds is None
def test_cannot_initialize_with_both_keyword_and_positional_arguments(self) -> None:
with pytest.raises(ValueError):
Range1d(1, 2, start=1, end=2)
def test_cannot_initialize_with_three_positional_arguments(self) -> None:
with pytest.raises(ValueError):
Range1d(1, 2, 3)
def test_with_max_bound_smaller_than_min_bounded_raises_valueerror(self) -> None:
with pytest.raises(ValueError):
Range1d(1, 2, bounds=(1, 0))
with pytest.raises(ValueError):
Range1d(1, 2, bounds=[1, 0])
def test_bounds_with_text_rejected_as_the_correct_value_error(self) -> None:
with pytest.raises(ValueError) as e:
Range1d(1, 2, bounds="21") # The string is indexable, so this may not fail properly
assert "expected either None or" in e.value.args[0]
def test_bounds_with_three_item_tuple_raises_valueerror(self) -> None:
with pytest.raises(ValueError):
Range1d(1, 2, bounds=(0, 1, 2))
| Test_Range1d |
python | Pylons__pyramid | src/pyramid/predicates.py | {
"start": 1071,
"end": 1497
} | class ____:
def __init__(self, val, config):
self.orig = val
try:
val = re.compile(val)
except re.error as why:
raise ConfigurationError(why.args[0])
self.val = val
def text(self):
return f'path_info = {self.orig}'
phash = text
def __call__(self, context, request):
return self.val.match(request.upath_info) is not None
| PathInfoPredicate |
python | walkccc__LeetCode | solutions/2765. Longest Alternating Subarray/2765.py | {
"start": 0,
"end": 548
} | class ____:
def alternatingSubarray(self, nums: list[int]) -> int:
ans = 1
dp = 1
for i in range(1, len(nums)):
targetDiff = -1 if dp % 2 == 0 else 1
# Append nums[i] to the current alternating subarray.
if nums[i] - nums[i - 1] == targetDiff:
dp += 1
# Reset the alternating subarray to nums[i - 1..i].
elif nums[i] - nums[i - 1] == 1:
dp = 2
# Reset the alternating subarray to nums[i].
else:
dp = 1
ans = max(ans, dp)
return -1 if ans == 1 else ans
| Solution |
python | numba__numba | numba/tests/doc_examples/test_examples.py | {
"start": 701,
"end": 23610
} | class ____(TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._mpl_blocker = MatplotlibBlocker()
def setUp(self):
sys.meta_path.insert(0, self._mpl_blocker)
def tearDown(self):
sys.meta_path.remove(self._mpl_blocker)
def test_mandelbrot(self):
with captured_stdout():
# magictoken.ex_mandelbrot.begin
from timeit import default_timer as timer
try:
from matplotlib.pylab import imshow, show
have_mpl = True
except ImportError:
have_mpl = False
import numpy as np
from numba import jit
@jit(nopython=True)
def mandel(x, y, max_iters):
"""
Given the real and imaginary parts of a complex number,
determine if it is a candidate for membership in the Mandelbrot
set given a fixed number of iterations.
"""
i = 0
c = complex(x,y)
z = 0.0j
for i in range(max_iters):
z = z * z + c
if (z.real * z.real + z.imag * z.imag) >= 4:
return i
return 255
@jit(nopython=True)
def create_fractal(min_x, max_x, min_y, max_y, image, iters):
height = image.shape[0]
width = image.shape[1]
pixel_size_x = (max_x - min_x) / width
pixel_size_y = (max_y - min_y) / height
for x in range(width):
real = min_x + x * pixel_size_x
for y in range(height):
imag = min_y + y * pixel_size_y
color = mandel(real, imag, iters)
image[y, x] = color
return image
image = np.zeros((500 * 2, 750 * 2), dtype=np.uint8)
s = timer()
create_fractal(-2.0, 1.0, -1.0, 1.0, image, 20)
e = timer()
print(e - s)
if have_mpl:
imshow(image)
show()
# magictoken.ex_mandelbrot.end
def test_moving_average(self):
with captured_stdout():
# magictoken.ex_moving_average.begin
import numpy as np
from numba import guvectorize
@guvectorize(['void(float64[:], intp[:], float64[:])'],
'(n),()->(n)')
def move_mean(a, window_arr, out):
window_width = window_arr[0]
asum = 0.0
count = 0
for i in range(window_width):
asum += a[i]
count += 1
out[i] = asum / count
for i in range(window_width, len(a)):
asum += a[i] - a[i - window_width]
out[i] = asum / count
arr = np.arange(20, dtype=np.float64).reshape(2, 10)
print(arr)
print(move_mean(arr, 3))
# magictoken.ex_moving_average.end
def test_nogil(self):
with captured_stdout():
# magictoken.ex_no_gil.begin
import math
import threading
from timeit import repeat
import numpy as np
from numba import jit
nthreads = 4
size = 10**6
def func_np(a, b):
"""
Control function using Numpy.
"""
return np.exp(2.1 * a + 3.2 * b)
@jit('void(double[:], double[:], double[:])', nopython=True,
nogil=True)
def inner_func_nb(result, a, b):
"""
Function under test.
"""
for i in range(len(result)):
result[i] = math.exp(2.1 * a[i] + 3.2 * b[i])
def timefunc(correct, s, func, *args, **kwargs):
"""
Benchmark *func* and print out its runtime.
"""
print(s.ljust(20), end=" ")
# Make sure the function is compiled before the benchmark is
# started
res = func(*args, **kwargs)
if correct is not None:
assert np.allclose(res, correct), (res, correct)
# time it
print('{:>5.0f} ms'.format(min(repeat(
lambda: func(*args, **kwargs), number=5, repeat=2)) * 1000))
return res
def make_singlethread(inner_func):
"""
Run the given function inside a single thread.
"""
def func(*args):
length = len(args[0])
result = np.empty(length, dtype=np.float64)
inner_func(result, *args)
return result
return func
def make_multithread(inner_func, numthreads):
"""
Run the given function inside *numthreads* threads, splitting
its arguments into equal-sized chunks.
"""
def func_mt(*args):
length = len(args[0])
result = np.empty(length, dtype=np.float64)
args = (result,) + args
chunklen = (length + numthreads - 1) // numthreads
# Create argument tuples for each input chunk
chunks = [[arg[i * chunklen:(i + 1) * chunklen] for arg in
args] for i in range(numthreads)]
# Spawn one thread per chunk
threads = [threading.Thread(target=inner_func, args=chunk)
for chunk in chunks]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return result
return func_mt
func_nb = make_singlethread(inner_func_nb)
func_nb_mt = make_multithread(inner_func_nb, nthreads)
a = np.random.rand(size)
b = np.random.rand(size)
correct = timefunc(None, "numpy (1 thread)", func_np, a, b)
timefunc(correct, "numba (1 thread)", func_nb, a, b)
timefunc(correct, "numba (%d threads)" % nthreads, func_nb_mt, a, b)
# magictoken.ex_no_gil.end
def test_vectorize_one_signature(self):
with captured_stdout():
# magictoken.ex_vectorize_one_signature.begin
from numba import vectorize, float64
@vectorize([float64(float64, float64)])
def f(x, y):
return x + y
# magictoken.ex_vectorize_one_signature.end
def test_vectorize_multiple_signatures(self):
with captured_stdout():
# magictoken.ex_vectorize_multiple_signatures.begin
from numba import vectorize, int32, int64, float32, float64
import numpy as np
@vectorize([int32(int32, int32),
int64(int64, int64),
float32(float32, float32),
float64(float64, float64)])
def f(x, y):
return x + y
# magictoken.ex_vectorize_multiple_signatures.end
# magictoken.ex_vectorize_return_call_one.begin
a = np.arange(6)
result = f(a, a)
# result == array([ 0, 2, 4, 6, 8, 10])
# magictoken.ex_vectorize_return_call_one.end
self.assertIsInstance(result, np.ndarray)
correct = np.array([0, 2, 4, 6, 8, 10])
np.testing.assert_array_equal(result, correct)
# magictoken.ex_vectorize_return_call_two.begin
a = np.linspace(0, 1, 6)
result = f(a, a)
# Now, result == array([0. , 0.4, 0.8, 1.2, 1.6, 2. ])
# magictoken.ex_vectorize_return_call_two.end
self.assertIsInstance(result, np.ndarray)
correct = np.array([0., 0.4, 0.8, 1.2, 1.6, 2. ])
np.testing.assert_allclose(result, correct)
# magictoken.ex_vectorize_return_call_three.begin
a = np.arange(12).reshape(3, 4)
# a == array([[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11]])
result1 = f.reduce(a, axis=0)
# result1 == array([12, 15, 18, 21])
result2 = f.reduce(a, axis=1)
# result2 == array([ 6, 22, 38])
result3 = f.accumulate(a)
# result3 == array([[ 0, 1, 2, 3],
# [ 4, 6, 8, 10],
# [12, 15, 18, 21]])
result4 = f.accumulate(a, axis=1)
# result3 == array([[ 0, 1, 3, 6],
# [ 4, 9, 15, 22],
# [ 8, 17, 27, 38]])
# magictoken.ex_vectorize_return_call_three.end
self.assertIsInstance(result1, np.ndarray)
correct = np.array([12, 15, 18, 21])
np.testing.assert_array_equal(result1, correct)
self.assertIsInstance(result2, np.ndarray)
correct = np.array([6, 22, 38])
np.testing.assert_array_equal(result2, correct)
self.assertIsInstance(result3, np.ndarray)
correct = np.array([
[0, 1, 2, 3],
[4, 6, 8, 10],
[12, 15, 18, 21]
])
np.testing.assert_array_equal(result3, correct)
self.assertIsInstance(result4, np.ndarray)
correct = np.array([
[0, 1, 3, 6],
[4, 9, 15, 22],
[8, 17, 27, 38]
])
np.testing.assert_array_equal(result4, correct)
def test_guvectorize(self):
with captured_stdout():
# magictoken.ex_guvectorize.begin
from numba import guvectorize, int64
import numpy as np
@guvectorize([(int64[:], int64, int64[:])], '(n),()->(n)')
def g(x, y, res):
for i in range(x.shape[0]):
res[i] = x[i] + y
# magictoken.ex_guvectorize.end
# magictoken.ex_guvectorize_call_one.begin
a = np.arange(5)
result = g(a, 2)
# result == array([2, 3, 4, 5, 6])
# magictoken.ex_guvectorize_call_one.end
self.assertIsInstance(result, np.ndarray)
correct = np.array([2, 3, 4, 5, 6])
np.testing.assert_array_equal(result, correct)
# magictoken.ex_guvectorize_call_two.begin
a = np.arange(6).reshape(2, 3)
# a == array([[0, 1, 2],
# [3, 4, 5]])
result1 = g(a, 10)
# result1 == array([[10, 11, 12],
# [13, 14, 15]])
result2 = g(a, np.array([10, 20]))
g(a, np.array([10, 20]))
# result2 == array([[10, 11, 12],
# [23, 24, 25]])
# magictoken.ex_guvectorize_call_two.end
self.assertIsInstance(result1, np.ndarray)
correct = np.array([[10, 11, 12], [13, 14, 15]])
np.testing.assert_array_equal(result1, correct)
self.assertIsInstance(result2, np.ndarray)
correct = np.array([[10, 11, 12], [23, 24, 25]])
np.testing.assert_array_equal(result2, correct)
def test_guvectorize_scalar_return(self):
with captured_stdout():
# magictoken.ex_guvectorize_scalar_return.begin
from numba import guvectorize, int64
import numpy as np
@guvectorize([(int64[:], int64, int64[:])], '(n),()->()')
def g(x, y, res):
acc = 0
for i in range(x.shape[0]):
acc += x[i] + y
res[0] = acc
# magictoken.ex_guvectorize_scalar_return.end
# magictoken.ex_guvectorize_scalar_return_call.begin
a = np.arange(5)
result = g(a, 2)
# At this point, result == 20.
# magictoken.ex_guvectorize_scalar_return_call.end
self.assertIsInstance(result, np.integer)
self.assertEqual(result, 20)
def test_guvectorize_jit(self):
with captured_stdout():
# magictoken.gufunc_jit.begin
import numpy as np
from numba import jit, guvectorize
@guvectorize('(n)->(n)')
def copy(x, res):
for i in range(x.shape[0]):
res[i] = x[i]
@jit(nopython=True)
def jit_fn(x, res):
copy(x, res)
# magictoken.gufunc_jit.end
# magictoken.gufunc_jit_call.begin
x = np.arange(5, dtype='i4')
res = np.zeros_like(x)
jit_fn(x, res)
# At this point, res == np.array([0, 1, 2, 3, 4], 'i4').
# magictoken.gufunc_jit_call.end
self.assertPreciseEqual(x, res)
def test_guvectorize_jit_fail(self):
with captured_stdout():
# magictoken.gufunc_jit_fail.begin
import numpy as np
from numba import jit, guvectorize
@guvectorize('(n)->(n)')
def copy(x, res):
for i in range(x.shape[0]):
res[i] = x[i]
@jit(nopython=True)
def jit_fn(x, res):
copy(x, res)
x = np.ones((1, 5))
res = np.empty((5,))
with self.assertRaises(ValueError) as raises:
jit_fn(x, res)
# magictoken.gufunc_jit_fail.end
self.assertIn('Loop and array shapes are incompatible',
str(raises.exception))
def test_guvectorize_overwrite(self):
with captured_stdout():
# magictoken.ex_guvectorize_overwrite.begin
from numba import guvectorize, float64
import numpy as np
@guvectorize([(float64[:], float64[:])], '()->()')
def init_values(invals, outvals):
invals[0] = 6.5
outvals[0] = 4.2
# magictoken.ex_guvectorize_overwrite.end
# magictoken.ex_guvectorize_overwrite_call_one.begin
invals = np.zeros(shape=(3, 3), dtype=np.float64)
# invals == array([[6.5, 6.5, 6.5],
# [6.5, 6.5, 6.5],
# [6.5, 6.5, 6.5]])
outvals = init_values(invals)
# outvals == array([[4.2, 4.2, 4.2],
# [4.2, 4.2, 4.2],
# [4.2, 4.2, 4.2]])
# magictoken.ex_guvectorize_overwrite_call_one.end
self.assertIsInstance(invals, np.ndarray)
correct = np.array([
[6.5, 6.5, 6.5],
[6.5, 6.5, 6.5],
[6.5, 6.5, 6.5]])
np.testing.assert_array_equal(invals, correct)
self.assertIsInstance(outvals, np.ndarray)
correct = np.array([
[4.2, 4.2, 4.2],
[4.2, 4.2, 4.2],
[4.2, 4.2, 4.2]])
np.testing.assert_array_equal(outvals, correct)
# magictoken.ex_guvectorize_overwrite_call_two.begin
invals = np.zeros(shape=(3, 3), dtype=np.float32)
# invals == array([[0., 0., 0.],
# [0., 0., 0.],
# [0., 0., 0.]], dtype=float32)
outvals = init_values(invals)
# outvals == array([[4.2, 4.2, 4.2],
# [4.2, 4.2, 4.2],
# [4.2, 4.2, 4.2]])
print(invals)
# invals == array([[0., 0., 0.],
# [0., 0., 0.],
# [0., 0., 0.]], dtype=float32)
# magictoken.ex_guvectorize_overwrite_call_two.end
self.assertIsInstance(invals, np.ndarray)
correct = np.array([
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]], dtype=np.float32)
np.testing.assert_array_equal(invals, correct)
self.assertIsInstance(outvals, np.ndarray)
correct = np.array([
[4.2, 4.2, 4.2],
[4.2, 4.2, 4.2],
[4.2, 4.2, 4.2]])
np.testing.assert_array_equal(outvals, correct)
# magictoken.ex_guvectorize_overwrite_call_three.begin
@guvectorize(
[(float64[:], float64[:])],
'()->()',
writable_args=('invals',)
)
def init_values(invals, outvals):
invals[0] = 6.5
outvals[0] = 4.2
invals = np.zeros(shape=(3, 3), dtype=np.float32)
# invals == array([[0., 0., 0.],
# [0., 0., 0.],
# [0., 0., 0.]], dtype=float32)
outvals = init_values(invals)
# outvals == array([[4.2, 4.2, 4.2],
# [4.2, 4.2, 4.2],
# [4.2, 4.2, 4.2]])
print(invals)
# invals == array([[6.5, 6.5, 6.5],
# [6.5, 6.5, 6.5],
# [6.5, 6.5, 6.5]], dtype=float32)
# magictoken.ex_guvectorize_overwrite_call_three.end
self.assertIsInstance(invals, np.ndarray)
correct = np.array([
[6.5, 6.5, 6.5],
[6.5, 6.5, 6.5],
[6.5, 6.5, 6.5]])
np.testing.assert_array_equal(invals, correct)
self.assertIsInstance(outvals, np.ndarray)
correct = np.array([
[4.2, 4.2, 4.2],
[4.2, 4.2, 4.2],
[4.2, 4.2, 4.2]])
np.testing.assert_array_equal(outvals, correct)
def test_vectorize_dynamic(self):
with captured_stdout():
# magictoken.ex_vectorize_dynamic.begin
from numba import vectorize
@vectorize
def f(x, y):
return x * y
# magictoken.ex_vectorize_dynamic.end
# magictoken.ex_vectorize_dynamic_call_one.begin
result = f(3,4)
# result == 12
print(f.types)
# ['ll->l']
# magictoken.ex_vectorize_dynamic_call_one.end
self.assertEqual(result, 12)
if IS_WIN32:
if numpy_version < (2, 0):
correct = ['ll->q']
else:
correct = ['qq->q']
else:
correct = ['ll->l']
self.assertEqual(f.types, correct)
# magictoken.ex_vectorize_dynamic_call_two.begin
result = f(1.,2.)
# result == 2.0
print(f.types)
# ['ll->l', 'dd->d']
# magictoken.ex_vectorize_dynamic_call_two.end
self.assertEqual(result, 2.0)
if IS_WIN32:
if numpy_version < (2, 0):
correct = ['ll->q', 'dd->d']
else:
correct = ['qq->q', 'dd->d']
else:
correct = ['ll->l', 'dd->d']
self.assertEqual(f.types, correct)
# magictoken.ex_vectorize_dynamic_call_three.begin
result = f(1,2.)
# result == 2.0
print(f.types)
# ['ll->l', 'dd->d']
# magictoken.ex_vectorize_dynamic_call_three.end
self.assertEqual(result, 2.0)
if IS_WIN32:
if numpy_version < (2, 0):
correct = ['ll->q', 'dd->d']
else:
correct = ['qq->q', 'dd->d']
else:
correct = ['ll->l', 'dd->d']
self.assertEqual(f.types, correct)
# magictoken.ex_vectorize_dynamic_call_four.begin
@vectorize
def g(a, b):
return a / b
print(g(2.,3.))
# 0.66666666666666663
print(g(2,3))
# 0.66666666666666663
print(g.types)
# ['dd->d']
# magictoken.ex_vectorize_dynamic_call_four.end
correct = ['dd->d']
self.assertEqual(g.types, correct)
def test_guvectorize_dynamic(self):
with captured_stdout():
# magictoken.ex_guvectorize_dynamic.begin
from numba import guvectorize
import numpy as np
@guvectorize('(n),()->(n)')
def g(x, y, res):
for i in range(x.shape[0]):
res[i] = x[i] + y
# magictoken.ex_guvectorize_dynamic.end
# magictoken.ex_guvectorize_dynamic_call_one.begin
x = np.arange(5, dtype=np.int64)
y = 10
res = np.zeros_like(x)
g(x, y, res)
# res == array([10, 11, 12, 13, 14])
print(g.types)
# ['ll->l']
# magictoken.ex_guvectorize_dynamic_call_one.end
correct = np.array([10, 11, 12, 13, 14])
np.testing.assert_array_equal(res, correct)
if IS_WIN32:
correct = ['qq->q']
else:
correct = ['ll->l']
self.assertEqual(g.types, correct)
# magictoken.ex_guvectorize_dynamic_call_two.begin
x = np.arange(5, dtype=np.double)
y = 2.2
res = np.zeros_like(x)
g(x, y, res)
# res == array([2.2, 3.2, 4.2, 5.2, 6.2])
# magictoken.ex_guvectorize_dynamic_call_two.end
# magictoken.ex_guvectorize_dynamic_call_three.begin
print(g.types) # shorthand for g.ufunc.types
# ['ll->l', 'dd->d']
# magictoken.ex_guvectorize_dynamic_call_three.end
if IS_WIN32:
correct = ['qq->q', 'dd->d']
else:
correct = ['ll->l', 'dd->d']
self.assertEqual(g.types, correct)
# magictoken.ex_guvectorize_dynamic_call_four.begin
x = np.arange(5, dtype=np.int64)
y = 2
res = np.zeros_like(x)
g(x, y, res)
print(res)
# res == array([2, 3, 4, 5, 6])
# magictoken.ex_guvectorize_dynamic_call_four.end
correct = np.array([2, 3, 4, 5, 6])
np.testing.assert_array_equal(res, correct)
if __name__ == '__main__':
unittest.main()
| DocsExamplesTest |
python | google__pytype | pytype/tools/xref/callgraph.py | {
"start": 577,
"end": 2127
} | class ____:
id: str
params: list[Any] = dataclasses.field(default_factory=list)
param_attrs: list[Any] = dataclasses.field(default_factory=list)
local_attrs: list[Any] = dataclasses.field(default_factory=list)
calls: list[Any] = dataclasses.field(default_factory=list)
ret: Any = dataclasses.field(default=None)
location: Any = dataclasses.field(default=None)
def unknown_to_any(typename):
if escape.UNKNOWN in typename:
return 'typing.Any'
return typename
def unwrap_type(typ):
if isinstance(typ, (pytd.ClassType, pytd.NamedType)):
typ_name = typ.name
elif isinstance(typ, pytd.UnionType):
typ_name = 'Union[' + ', '.join(unwrap_type(t) for t in typ.type_list) + ']'
elif isinstance(typ, pytd.AnythingType):
typ_name = 'typing.Any'
else:
typ_name = pytd_utils.Print(typ)
return unknown_to_any(typ_name)
def get_function_params(pytd_fn):
"""Collect function param types from pytype."""
# We have turned call records on in the indexer, so a function will have a
# pytd signature for every tuple of call args. Here we iterate through those
# signatures and set every param's type to the union of every non-"unknown"
# call type for that param.
params = {}
for sig in pytd_fn.signatures:
for p in sig.params:
if p.name not in params:
params[p.name] = []
if escape.UNKNOWN not in str(p.type):
params[p.name].append(p.type)
for k in params:
params[k] = pytd_utils.JoinTypes(params[k])
return [(k, unwrap_type(v)) for k, v in params.items()]
| Function |
python | pydantic__pydantic | pydantic-core/tests/validators/test_union.py | {
"start": 29990,
"end": 31457
} | class ____:
class ModelA:
a: int
class ModelB(ModelA):
b: int
model_a_schema = core_schema.model_schema(
ModelA, core_schema.model_fields_schema(fields={'a': core_schema.model_field(core_schema.int_schema())})
)
model_b_schema = core_schema.model_schema(
ModelB,
core_schema.model_fields_schema(
fields={
'a': core_schema.model_field(core_schema.int_schema()),
'b': core_schema.model_field(core_schema.int_schema()),
}
),
)
@pytest.mark.parametrize('choices', permute_choices([model_a_schema, model_b_schema]))
def test_more_specific_data_matches_subclass(self, choices) -> None:
validator = SchemaValidator(core_schema.union_schema(choices))
assert isinstance(validator.validate_python({'a': 1}), self.ModelA)
assert isinstance(validator.validate_python({'a': 1, 'b': 2}), self.ModelB)
assert isinstance(validator.validate_python({'a': 1, 'b': 2}), self.ModelB)
# confirm that a model that matches in lax mode with 2 fields
# is preferred over a model that matches in strict mode with 1 field
assert isinstance(validator.validate_python({'a': '1', 'b': '2'}), self.ModelB)
assert isinstance(validator.validate_python({'a': '1', 'b': 2}), self.ModelB)
assert isinstance(validator.validate_python({'a': 1, 'b': '2'}), self.ModelB)
| TestSmartUnionWithSubclass |
python | getsentry__sentry | fixtures/safe_migrations_apps/bad_flow_add_column_with_notnull_app/models.py | {
"start": 31,
"end": 96
} | class ____(models.Model):
field = models.IntegerField()
| TestTable |
python | ray-project__ray | python/ray/_private/runtime_env/py_modules.py | {
"start": 6509,
"end": 9007
} | class ____(RuntimeEnvPlugin):
name = "py_modules"
def __init__(self, resources_dir: str, gcs_client: GcsClient):
self._resources_dir = os.path.join(resources_dir, "py_modules_files")
self._gcs_client = gcs_client
try_to_create_directory(self._resources_dir)
def _get_local_dir_from_uri(self, uri: str):
return get_local_dir_from_uri(uri, self._resources_dir)
def delete_uri(
self, uri: str, logger: Optional[logging.Logger] = default_logger
) -> int:
"""Delete URI and return the number of bytes deleted."""
logger.info("Got request to delete pymodule URI %s", uri)
local_dir = get_local_dir_from_uri(uri, self._resources_dir)
local_dir_size = get_directory_size_bytes(local_dir)
deleted = delete_package(uri, self._resources_dir)
if not deleted:
logger.warning(f"Tried to delete nonexistent URI: {uri}.")
return 0
return local_dir_size
def get_uris(self, runtime_env) -> List[str]:
return runtime_env.py_modules()
async def create(
self,
uri: str,
runtime_env: "RuntimeEnv", # noqa: F821
context: RuntimeEnvContext,
logger: Optional[logging.Logger] = default_logger,
) -> int:
module_dir = await download_and_unpack_package(
uri, self._resources_dir, self._gcs_client, logger=logger
)
if is_whl_uri(uri):
wheel_uri = module_dir
module_dir = self._get_local_dir_from_uri(uri)
await install_wheel_package(
wheel_uri=wheel_uri, target_dir=module_dir, logger=logger
)
return get_directory_size_bytes(module_dir)
def modify_context(
self,
uris: List[str],
runtime_env_dict: Dict,
context: RuntimeEnvContext,
logger: Optional[logging.Logger] = default_logger,
):
module_dirs = []
for uri in uris:
module_dir = self._get_local_dir_from_uri(uri)
if not module_dir.exists():
raise ValueError(
f"Local directory {module_dir} for URI {uri} does "
"not exist on the cluster. Something may have gone wrong while "
"downloading, unpacking or installing the py_modules files."
)
module_dirs.append(str(module_dir))
set_pythonpath_in_context(os.pathsep.join(module_dirs), context)
| PyModulesPlugin |
python | sqlalchemy__sqlalchemy | test/orm/test_naturalpks.py | {
"start": 22482,
"end": 25177
} | class ____(fixtures.MappedTest):
"""reverse the primary keys of two entities and ensure bookkeeping
succeeds."""
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"user",
metadata,
Column("code", Integer, autoincrement=False, primary_key=True),
Column("status", Integer, autoincrement=False, primary_key=True),
Column("username", String(50), nullable=False),
test_needs_acid=True,
)
@classmethod
def setup_classes(cls):
class User(cls.Comparable):
def __init__(self, code, status, username):
self.code = code
self.status = status
self.username = username
def test_reverse(self):
user, User = self.tables.user, self.classes.User
PUBLISHED, EDITABLE, ARCHIVED = 1, 2, 3
self.mapper_registry.map_imperatively(User, user)
session = fixture_session()
a_published = User(1, PUBLISHED, "a")
session.add(a_published)
session.commit()
a_editable = User(1, EDITABLE, "a")
session.add(a_editable)
session.commit()
# see also much more recent issue #4890 where we add a warning
# for almost this same case
# do the switch in both directions -
# one or the other should raise the error
# based on platform dictionary ordering
a_published.status = ARCHIVED
a_editable.status = PUBLISHED
session.commit()
assert session.get(User, [1, PUBLISHED]) is a_editable
assert session.get(User, [1, ARCHIVED]) is a_published
a_published.status = PUBLISHED
a_editable.status = EDITABLE
session.commit()
assert session.get(User, [1, PUBLISHED]) is a_published
assert session.get(User, [1, EDITABLE]) is a_editable
@testing.requires.savepoints
def test_reverse_savepoint(self):
user, User = self.tables.user, self.classes.User
PUBLISHED, EDITABLE, ARCHIVED = 1, 2, 3
self.mapper_registry.map_imperatively(User, user)
session = fixture_session()
a_published = User(1, PUBLISHED, "a")
session.add(a_published)
session.commit()
a_editable = User(1, EDITABLE, "a")
session.add(a_editable)
session.commit()
# testing #3108
nt1 = session.begin_nested()
a_published.status = ARCHIVED
a_editable.status = PUBLISHED
nt1.commit()
session.rollback()
eq_(a_published.status, PUBLISHED)
eq_(a_editable.status, EDITABLE)
| ReversePKsTest |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_sync_versions.py | {
"start": 49686,
"end": 54067
} | class ____(TestCase):
fixtures = ["eric", "test_data"]
def setUp(self):
self.user = User.objects.get(username="eric")
self.client.force_login(self.user)
self.pip = Project.objects.get(slug="pip")
# Run tests for .com
if settings.ALLOW_PRIVATE_REPOS:
self.org = get(
Organization,
name="testorg",
)
OrganizationOwner.objects.create(
owner=self.user,
organization=self.org,
)
self.org.projects.add(self.pip)
Version.objects.create(
project=self.pip,
identifier="origin/master",
verbose_name="master",
active=True,
machine=True,
type=BRANCH,
)
# When the project is saved, the RTD's ``latest`` version
# is created.
self.pip.save()
def test_user_defined_latest_version_tag(self):
# TODO: the ``latest`` versions are created
# as a BRANCH, then here we will have a
# ``latest_a`` version.
branches_data = [
{
"identifier": "origin/master",
"verbose_name": "master",
},
]
tags_data = [
# A new user-defined latest tag
{
"identifier": "1abc2def3",
"verbose_name": "latest",
},
]
sync_versions_task(
self.pip.pk,
branches_data=branches_data,
tags_data=tags_data,
)
# Did update to user-defined latest version
version_latest = self.pip.versions.get(slug="latest")
self.assertFalse(version_latest.machine)
self.assertTrue(version_latest.active)
self.assertEqual(
"1abc2def3",
version_latest.identifier,
)
# There aren't others latest slugs like latest_a
other_latest = self.pip.versions.filter(
slug__startswith="latest_",
)
self.assertFalse(other_latest.exists())
# Check that syncing again doesn't change anything from current state.
sync_versions_task(
self.pip.pk,
branches_data=branches_data,
tags_data=tags_data,
)
version_latest = self.pip.versions.get(slug="latest")
self.assertFalse(version_latest.machine)
self.assertTrue(version_latest.active)
self.assertEqual(
"1abc2def3",
version_latest.identifier,
)
other_latest = self.pip.versions.filter(
slug__startswith="latest_",
)
self.assertFalse(other_latest.exists())
def test_user_defined_latest_version_branch(self):
branches_data = [
{
"identifier": "origin/master",
"verbose_name": "master",
},
# A new user-defined latest branch
{
"identifier": "origin/latest",
"verbose_name": "latest",
},
]
sync_versions_task(
self.pip.pk,
branches_data=branches_data,
tags_data=[],
)
# Did update to user-defined latest version
version_latest = self.pip.versions.get(slug="latest")
self.assertFalse(version_latest.machine)
self.assertTrue(version_latest.active)
self.assertEqual(
"origin/latest",
version_latest.identifier,
)
# There aren't others latest slugs like latest_a
other_latest = self.pip.versions.filter(
slug__startswith="latest_",
)
self.assertFalse(other_latest.exists())
# Check that posting again doesn't change anything from current state.
sync_versions_task(
self.pip.pk,
branches_data=branches_data,
tags_data=[],
)
version_latest = self.pip.versions.get(slug="latest")
self.assertFalse(version_latest.machine)
self.assertTrue(version_latest.active)
self.assertEqual(
"origin/latest",
version_latest.identifier,
)
other_latest = self.pip.versions.filter(
slug__startswith="latest_",
)
self.assertFalse(other_latest.exists())
| TestLatestVersion |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_count.py | {
"start": 81,
"end": 1083
} | class ____:
def test_count(self):
# corner case
frame = DataFrame()
ct1 = frame.count(1)
assert isinstance(ct1, Series)
ct2 = frame.count(0)
assert isinstance(ct2, Series)
# GH#423
df = DataFrame(index=range(10))
result = df.count(1)
expected = Series(0, index=df.index)
tm.assert_series_equal(result, expected)
df = DataFrame(columns=range(10))
result = df.count(0)
expected = Series(0, index=df.columns)
tm.assert_series_equal(result, expected)
df = DataFrame()
result = df.count()
expected = Series(dtype="int64")
tm.assert_series_equal(result, expected)
def test_count_objects(self, float_string_frame):
dm = DataFrame(float_string_frame._series)
df = DataFrame(float_string_frame._series)
tm.assert_series_equal(dm.count(), df.count())
tm.assert_series_equal(dm.count(1), df.count(1))
| TestDataFrameCount |
python | apache__airflow | providers/redis/src/airflow/providers/redis/sensors/redis_pub_sub.py | {
"start": 1138,
"end": 2728
} | class ____(BaseSensorOperator):
"""
Redis sensor for reading a message from pub sub channels.
:param channels: The channels to be subscribed to (templated)
:param redis_conn_id: the redis connection id
"""
template_fields: Sequence[str] = ("channels",)
ui_color = "#f0eee4"
def __init__(self, *, channels: list[str] | str, redis_conn_id: str, **kwargs) -> None:
super().__init__(**kwargs)
self.channels = channels
self.redis_conn_id = redis_conn_id
@cached_property
def pubsub(self):
hook = RedisHook(redis_conn_id=self.redis_conn_id).get_conn().pubsub()
hook.subscribe(self.channels)
return hook
def poke(self, context: Context) -> bool:
"""
Check for message on subscribed channels and write to xcom the message with key ``message``.
An example of message ``{'type': 'message', 'pattern': None, 'channel': b'test', 'data': b'hello'}``
:param context: the context object
:return: ``True`` if message (with type 'message') is available or ``False`` if not
"""
self.log.info("RedisPubSubSensor checking for message on channels: %s", self.channels)
message = self.pubsub.get_message()
self.log.info("Message %s from channel %s", message, self.channels)
# Process only message types
if message and message["type"] == "message":
context["ti"].xcom_push(key="message", value=message)
self.pubsub.unsubscribe(self.channels)
return True
return False
| RedisPubSubSensor |
python | pytorch__pytorch | torch/utils/data/datapipes/_decorator.py | {
"start": 2347,
"end": 6515
} | class ____:
cls: type[IterDataPipe] | None = None
# TODO: Lambda for picking
deterministic_fn: Callable[..., bool]
def __init__(self, arg: type[IterDataPipe] | Callable[..., bool]) -> None:
# 1. Decorator doesn't have any argument
if isinstance(arg, type): # type: ignore[arg-type]
if not issubclass(arg, IterDataPipe): # type: ignore[arg-type]
raise TypeError(
"Only `IterDataPipe` can be decorated with `non_deterministic`"
f", but {arg.__name__} is found"
)
self.cls = arg # type: ignore[assignment]
# 2. Decorator has an argument of a function
# This class should behave differently given different inputs. Use this
# function to verify the determinism for each instance.
# When the function returns True, the instance is non-deterministic. Otherwise,
# the instance is a deterministic DataPipe.
elif isinstance(arg, Callable): # type:ignore[arg-type]
self.deterministic_fn = arg
else:
raise TypeError(f"{arg} can not be decorated by non_deterministic")
def __call__(self, *args, **kwargs):
global _determinism
# Decorate IterDataPipe
if self.cls is not None:
if _determinism:
raise TypeError(
f"{self.cls.__name__} is non-deterministic, but you set 'guaranteed_datapipes_determinism'. "
"You can turn off determinism for this DataPipe if that is acceptable "
"for your application"
)
return self.cls(*args, **kwargs) # type: ignore[call-arg]
# Decorate with a functional argument
if not (
isinstance(args[0], type) and issubclass(args[0], IterDataPipe) # type: ignore[arg-type]
):
raise TypeError(
f"Only `IterDataPipe` can be decorated, but {args[0].__name__} is found"
)
self.cls = args[0]
return self.deterministic_wrapper_fn
def deterministic_wrapper_fn(self, *args, **kwargs) -> IterDataPipe:
res = self.deterministic_fn(*args, **kwargs)
if not isinstance(res, bool):
raise TypeError(
"deterministic_fn of `non_deterministic` decorator is required "
f"to return a boolean value, but {type(res)} is found"
)
global _determinism
if _determinism and res:
raise TypeError(
f"{self.cls.__name__} is non-deterministic with the inputs, but you set " # type: ignore[union-attr]
"'guaranteed_datapipes_determinism'. You can turn off determinism "
"for this DataPipe if that is acceptable for your application"
)
return self.cls(*args, **kwargs) # type: ignore[call-arg, misc]
######################################################
# Type validation
######################################################
# Validate each argument of DataPipe with hint as a subtype of the hint.
def argument_validation(f):
signature = inspect.signature(f)
hints = get_type_hints(f)
@wraps(f)
def wrapper(*args, **kwargs):
bound = signature.bind(*args, **kwargs)
for argument_name, value in bound.arguments.items():
if argument_name in hints and isinstance(
hints[argument_name], _DataPipeMeta
):
hint = hints[argument_name]
if not isinstance(value, IterDataPipe):
raise TypeError(
f"Expected argument '{argument_name}' as a IterDataPipe, but found {type(value)}"
)
if not value.type.issubtype(hint.type):
raise TypeError(
f"Expected type of argument '{argument_name}' as a subtype of "
f"hint {hint.type}, but found {value.type}"
)
return f(*args, **kwargs)
return wrapper
# Default value is True
_runtime_validation_enabled: bool = True
| non_deterministic |
python | pypa__pip | tests/lib/__init__.py | {
"start": 43414,
"end": 44581
} | class ____(Protocol):
def __call__(
self,
tmpdir: pathlib.Path,
virtualenv: VirtualEnvironment | None = None,
environ: dict[AnyStr, AnyStr] | None = None,
) -> PipTestEnvironment: ...
CertFactory = Callable[[], str]
# -------------------------------------------------------------------------
# Accommodations for Windows path and URL changes in recent Python releases
# -------------------------------------------------------------------------
# Trailing slashes are now preserved on Windows, matching POSIX behaviour.
# BPO: https://github.com/python/cpython/issues/126212
does_pathname2url_preserve_trailing_slash = pathname2url("C:\\foo\\").endswith("/")
skip_needs_new_pathname2url_trailing_slash_behavior_win = pytest.mark.skipif(
sys.platform != "win32" or not does_pathname2url_preserve_trailing_slash,
reason="testing windows (pathname2url) behavior for newer CPython",
)
skip_needs_old_pathname2url_trailing_slash_behavior_win = pytest.mark.skipif(
sys.platform != "win32" or does_pathname2url_preserve_trailing_slash,
reason="testing windows (pathname2url) behavior for older CPython",
)
| ScriptFactory |
python | PrefectHQ__prefect | src/prefect/server/schemas/states.py | {
"start": 1980,
"end": 3030
} | class ____(PrefectBaseModel):
flow_run_id: Optional[UUID] = None
task_run_id: Optional[UUID] = None
# for task runs that represent subflows, the subflow's run ID
child_flow_run_id: Optional[UUID] = None
scheduled_time: Optional[DateTime] = None
cache_key: Optional[str] = None
cache_expiration: Optional[DateTime] = None
deferred: Optional[bool] = False
untrackable_result: bool = False
pause_timeout: Optional[DateTime] = None
pause_reschedule: bool = False
pause_key: Optional[str] = None
run_input_keyset: Optional[dict[str, str]] = None
refresh_cache: Optional[bool] = None
retriable: Optional[bool] = None
transition_id: Optional[UUID] = None
task_parameters_id: Optional[UUID] = None
# Captures the trace_id and span_id of the span where this state was created
traceparent: Optional[str] = None
# The ID of the lease that is currently holding the deployment concurrency slot
# for this run.
deployment_concurrency_lease_id: Optional[UUID] = None
| StateDetails |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/callbackProtocol1.py | {
"start": 114,
"end": 830
} | class ____(Protocol):
def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]:
return []
def good_cb(*vals: bytes, maxlen: int | None = None) -> list[bytes]:
return []
def bad_cb1(*vals: bytes, maxlen: int | None, maxitems: int | None) -> list[bytes]:
return []
def bad_cb2(*vals: bytes) -> list[bytes]:
return []
def bad_cb3(*vals: bytes, maxlen: str | None) -> list[bytes]:
return []
var1: TestClass1 = good_cb
# This should generate an error because maxitems is unmatched.
var1 = bad_cb1
# This should generate an error because maxlen is unmatched.
var1 = bad_cb2
# This should generate an error because maxlen is the wrong type.
var1 = bad_cb3
| TestClass1 |
python | joke2k__faker | faker/providers/company/fi_FI/__init__.py | {
"start": 45,
"end": 2067
} | class ____(CompanyProvider):
formats = (
"{{last_name}} {{company_suffix}}",
"{{last_name}} {{last_name}} {{company_suffix}}",
"{{last_name}} {{last_name}} {{company_suffix}}",
"{{last_name}}",
)
company_suffixes = (
"As Oy",
"Tmi",
"Oy",
"Oyj",
"Ky",
"Osk",
"ry",
)
def company_business_id(self) -> str:
"""
Returns Finnish company Business Identity Code (y-tunnus).
Format is 8 digits - e.g. FI99999999,[8] last digit is a check
digit utilizing MOD 11-2. The first digit is zero for some old
organizations. This function provides current codes starting with
non-zero.
"""
def calculate_checksum(number: str) -> str:
"""Calculate the checksum using mod 11,2 method"""
factors = [7, 9, 10, 5, 8, 4, 2]
sum_ = 0
for x, y in zip(number, factors):
sum_ = sum_ + int(x) * y
if sum_ % 11 == 1:
raise ValueError("Checksum 1 is invalid")
if sum_ % 11 == 0:
return "0"
else:
return str(11 - sum_ % 11)
while True:
first_digit = str(self.random_digit_not_null())
body = first_digit + self.bothify("######")
try:
cs = calculate_checksum(body)
except ValueError:
continue
return body + "-" + str(cs)
def company_vat(self) -> str:
"""
Returns Finnish VAT identification number (Arvonlisaveronumero).
This can be calculated from company business identity code by
adding prefix "FI" and removing dash before checksum.
"""
def convert_to_vat(business_id: str) -> str:
"""
Convert business id to VATIN
"""
return "FI" + business_id.replace("-", "")
return convert_to_vat(self.company_business_id())
| Provider |
python | pennersr__django-allauth | tests/apps/socialaccount/test_adapter.py | {
"start": 311,
"end": 2105
} | class ____(DefaultSocialAccountAdapter):
def generate_state_param(self, state: dict) -> str:
return f"prefix-{super().generate_state_param(state)}"
def test_generate_state_param(settings, client, db, google_provider_settings):
settings.SOCIALACCOUNT_ADAPTER = (
"tests.apps.socialaccount.test_adapter.PrefixStateSocialAccountAdapter"
)
resp = client.post(reverse("google_login"))
parsed = urlparse(resp["location"])
query = parse_qs(parsed.query)
state = query["state"][0]
assert len(state) == len("prefix-") + statekit.STATE_ID_LENGTH
assert state.startswith("prefix-")
def test_list_db_based_apps(db, settings):
app = SocialApp.objects.create(
provider="saml", provider_id="urn:idp-identity-id", client_id="org-slug"
)
app.sites.add(Site.objects.get_current())
apps = get_adapter().list_apps(None, provider="saml", client_id="org-slug")
assert app.pk in [a.pk for a in apps]
def test_list_settings_based_apps(db, settings):
settings.SOCIALACCOUNT_PROVIDERS = {
"saml": {
"APPS": [
{
"provider_id": "urn:idp-entity-id",
"client_id": "org-slug",
}
]
}
}
apps = get_adapter().list_apps(None, provider="saml", client_id="org-slug")
assert len(apps) == 1
app = apps[0]
assert not app.pk
assert app.client_id == "org-slug"
def test_get_signup_form_initial_data(sociallogin_factory):
sociallogin = sociallogin_factory(email="a@b.com")
# it should pick up sociallogin.email_addresses
sociallogin.user.email = ""
initial_data = get_adapter().get_signup_form_initial_data(sociallogin)
assert initial_data["email"] == "a@b.com"
| PrefixStateSocialAccountAdapter |
python | coleifer__peewee | tests/base_models.py | {
"start": 1523,
"end": 1606
} | class ____(TestModel):
b = ForeignKeyField(B, backref='cs')
c = TextField()
| C |
python | numba__numba | numba/core/serialize.py | {
"start": 4779,
"end": 5406
} | class ____(abc.ABC):
"""A mixin class for objects that should be reduced by the NumbaPickler
instead of the standard pickler.
"""
# Subclass MUST override the below methods
@abc.abstractmethod
def _reduce_states(self):
raise NotImplementedError
@classmethod
@abc.abstractmethod
def _rebuild(cls, **kwargs):
raise NotImplementedError
# Subclass can override the below methods
def _reduce_class(self):
return self.__class__
# Private methods
def __reduce__(self):
return custom_reduce(self._reduce_class(), self._reduce_states())
| ReduceMixin |
python | getsentry__sentry | src/sentry/releases/endpoints/organization_release_details.py | {
"start": 3690,
"end": 11741
} | class ____:
@staticmethod
def __get_prev_release_date_query_q_and_order_by(release):
"""
Method that takes a release and returns a dictionary containing a date query Q expression
and order by columns required to fetch previous release to that passed in release on date
sorting
"""
return {
"date_query_q": Q(date_added__gt=release.date_added)
| Q(date_added=release.date_added, id__gt=release.id),
"order_by": ["date_added", "id"],
}
@staticmethod
def __get_next_release_date_query_q_and_order_by(release):
"""
Method that takes a release and returns a dictionary containing a date query Q expression
and order by columns required to fetch next release to that passed in release on date
sorting
"""
return {
"date_query_q": Q(date_added__lt=release.date_added)
| Q(date_added=release.date_added, id__lt=release.id),
"order_by": ["-date_added", "-id"],
}
@staticmethod
def __get_release_according_to_filters_and_order_by_for_date_sort(
org,
filter_params,
date_query_q,
order_by,
status_filter,
query,
):
"""
Helper function that executes a query on Release table based on different filters
provided as inputs and orders that query based on `order_by` input provided
Inputs:-
* org: Organization object
* filter_params:
* date_query_q: List that contains the Q expressions needed to sort based on date
* order_by: Contains columns that are used for ordering to sort based on date
* status_filter: represents ReleaseStatus i.e. open, archived
* query
Returns:-
Queryset that contains one element that represents either next or previous release
based on the inputs
"""
queryset = Release.objects.filter(
date_query_q,
organization=org,
projects__id__in=filter_params["project_id"],
)
# Add status filter
queryset = add_status_filter_to_queryset(queryset, status_filter)
# Add query filter
queryset = add_query_filter_to_queryset(queryset, query)
# Add env filter
queryset = add_environment_to_queryset(queryset, filter_params)
# Orderby passed cols and limit to 1
queryset = queryset.order_by(*order_by)[:1]
return queryset
def get_adjacent_releases_to_current_release(
self,
release,
org,
filter_params,
stats_period,
sort,
status_filter,
query,
):
"""
Method that returns the prev and next release to a current release based on different
sort options
Inputs:-
* release: current release object
* org: organization object
* filter_params
* stats_period
* sort: sort option i.e. date, sessions, users, crash_free_users and crash_free_sessions
* status_filter
* query
Returns:-
A dictionary of two keys `prev_release_version` and `next_release_version` representing
previous release and next release respectively
"""
if sort == "date":
release_common_filters = {
"org": org,
"filter_params": filter_params,
"status_filter": status_filter,
"query": query,
}
# Get previous queryset of current release
prev_release_list = self.__get_release_according_to_filters_and_order_by_for_date_sort(
**release_common_filters,
**self.__get_prev_release_date_query_q_and_order_by(release),
)
# Get next queryset of current release
next_release_list = self.__get_release_according_to_filters_and_order_by_for_date_sort(
**release_common_filters,
**self.__get_next_release_date_query_q_and_order_by(release),
)
else:
raise InvalidSortException
prev_release_version = None
if len(prev_release_list) > 0:
prev_release_version = prev_release_list[0].version
next_release_version = None
if len(next_release_list) > 0:
next_release_version = next_release_list[0].version
# This is reversed on purpose and the reason for that is that the prev and next releases
# are computed in the same order as the releases list page and so for example if you have a
# releases list ordered by date_created, that looks like this
# * Release 3.0.0 -> Created last
# * Release 2.0.0 -> Created before last
# * Release 1.0.0 -> Created first
# Then the prev and next for Release 2.0.0 would be Release 3.0.0 (more recent) and Release
# 1.0.0 (less recent) respectively. This would however result in non-intuitive behaviour
# in the UI because when you click on "<" (prev) you expect to go back to an "older"
# release, but prev here will give you a more recent release as this list is ordered
# in DESC order, and the same case can be made for when you click on ">" or next.
return {
"next_release_version": prev_release_version,
"prev_release_version": next_release_version,
}
@staticmethod
def __get_top_of_queryset_release_version_based_on_order_by(org, proj_and_env_dict, order_by):
"""
Helper function that executes a query on Release table orders that query based on `order_by`
input provided
Inputs:-
* org: Organization object
* proj_and_env_dict: contains only two keys project_id and environment
* order_by: Contains columns that are used for ordering to sort based on date
Returns:-
Release version of the top element of the queryset returned through ordering the Release
table by the order_by input
"""
queryset = Release.objects.filter(
organization=org, projects__id__in=proj_and_env_dict["project_id"]
)
queryset = add_environment_to_queryset(queryset, proj_and_env_dict)
release = queryset.order_by(*order_by).first()
if not release:
return None
return release.version
def get_first_and_last_releases(self, org, environment, project_id, sort):
"""
Method that returns the first and last release based on `date_added`
Inputs:-
* org: organization object
* environment
* project_id
* sort: sort option i.e. date, sessions, users, crash_free_users and crash_free_sessions
Returns:-
A dictionary of two keys `first_release_version` and `last_release_version` representing
the first ever created release and the last ever created releases respectively
"""
first_release_version = None
last_release_version = None
if sort == "date":
proj_and_env_dict = {"project_id": project_id}
if environment is not None:
proj_and_env_dict["environment"] = environment
first_release_version = self.__get_top_of_queryset_release_version_based_on_order_by(
org=org, proj_and_env_dict=proj_and_env_dict, order_by=["date_added", "id"]
)
last_release_version = self.__get_top_of_queryset_release_version_based_on_order_by(
org=org, proj_and_env_dict=proj_and_env_dict, order_by=["-date_added", "-id"]
)
return {
"first_release_version": first_release_version,
"last_release_version": last_release_version,
}
@extend_schema(tags=["Releases"])
@region_silo_endpoint
| OrganizationReleaseDetailsPaginationMixin |
python | plotly__plotly.py | plotly/graph_objs/densitymapbox/colorbar/title/_font.py | {
"start": 233,
"end": 9944
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "densitymapbox.colorbar.title"
_path_str = "densitymapbox.colorbar.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
@property
def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser can only apply a font if it is
available on the system where it runs. Provide multiple font
families, separated by commas, to indicate the order in which
to apply fonts if they aren't available.
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
@property
def lineposition(self):
"""
Sets the kind of decoration line(s) with text, such as an
"under", "over" or "through" as well as combinations e.g.
"under+over", etc.
The 'lineposition' property is a flaglist and may be specified
as a string containing:
- Any combination of ['under', 'over', 'through'] joined with '+' characters
(e.g. 'under+over')
OR exactly one of ['none'] (e.g. 'none')
Returns
-------
Any
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = val
@property
def shadow(self):
"""
Sets the shape and color of the shadow behind text. "auto"
places minimal shadow and applies contrast text font color. See
https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow
for additional options.
The 'shadow' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = val
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def style(self):
"""
Sets whether a font should be styled with a normal or italic
face from its family.
The 'style' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'italic']
Returns
-------
Any
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = val
@property
def textcase(self):
"""
Sets capitalization of text. It can be used to make text appear
in all-uppercase or all-lowercase, or with each word
capitalized.
The 'textcase' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'word caps', 'upper', 'lower']
Returns
-------
Any
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = val
@property
def variant(self):
"""
Sets the variant of the font.
The 'variant' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'small-caps', 'all-small-caps',
'all-petite-caps', 'petite-caps', 'unicase']
Returns
-------
Any
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = val
@property
def weight(self):
"""
Sets the weight (or boldness) of the font.
The 'weight' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 1000]
OR exactly one of ['normal', 'bold'] (e.g. 'bold')
Returns
-------
int
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
@property
def _prop_descriptions(self):
return """\
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
"""
def __init__(
self,
arg=None,
color=None,
family=None,
lineposition=None,
shadow=None,
size=None,
style=None,
textcase=None,
variant=None,
weight=None,
**kwargs,
):
"""
Construct a new Font object
Sets this color bar's title font.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.densitymapbox.
colorbar.title.Font`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
Returns
-------
Font
"""
super().__init__("font")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.densitymapbox.colorbar.title.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.densitymapbox.colorbar.title.Font`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("family", arg, family)
self._set_property("lineposition", arg, lineposition)
self._set_property("shadow", arg, shadow)
self._set_property("size", arg, size)
self._set_property("style", arg, style)
self._set_property("textcase", arg, textcase)
self._set_property("variant", arg, variant)
self._set_property("weight", arg, weight)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Font |
python | django__django | tests/prefetch_related/models.py | {
"start": 2348,
"end": 2591
} | class ____(models.Model):
# Intentionally does not have a related name.
book = models.ForeignKey(BookWithYear, models.CASCADE, null=True)
notes = models.TextField(null=True, blank=True)
# Models for default manager tests
| BookReview |
python | doocs__leetcode | solution/0300-0399/0357.Count Numbers with Unique Digits/Solution.py | {
"start": 0,
"end": 534
} | class ____:
def countNumbersWithUniqueDigits(self, n: int) -> int:
@cache
def dfs(i: int, mask: int, lead: bool) -> int:
if i < 0:
return 1
ans = 0
for j in range(10):
if mask >> j & 1:
continue
if lead and j == 0:
ans += dfs(i - 1, mask, True)
else:
ans += dfs(i - 1, mask | 1 << j, False)
return ans
return dfs(n - 1, 0, True)
| Solution |
python | optuna__optuna | optuna/pruners/_median.py | {
"start": 58,
"end": 3384
} | class ____(PercentilePruner):
"""Pruner using the median stopping rule.
Prune if the trial's best intermediate result is worse than median of intermediate results of
previous trials at the same step. It stops unpromising trials early based on the
intermediate results compared against the median of previous completed trials.
The pruner handles NaN values in the following manner:
1. If all intermediate values of the current trial are NaN, the trial will be pruned.
2. During the median calculation across completed trials, NaN values are ignored.
Only valid numeric values are considered.
Example:
We minimize an objective function with the median stopping rule.
.. testcode::
import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split
import optuna
X, y = load_iris(return_X_y=True)
X_train, X_valid, y_train, y_valid = train_test_split(X, y)
classes = np.unique(y)
def objective(trial):
alpha = trial.suggest_float("alpha", 0.0, 1.0)
clf = SGDClassifier(alpha=alpha)
n_train_iter = 100
for step in range(n_train_iter):
clf.partial_fit(X_train, y_train, classes=classes)
intermediate_value = clf.score(X_valid, y_valid)
trial.report(intermediate_value, step)
if trial.should_prune():
raise optuna.TrialPruned()
return clf.score(X_valid, y_valid)
study = optuna.create_study(
direction="maximize",
pruner=optuna.pruners.MedianPruner(
n_startup_trials=5, n_warmup_steps=30, interval_steps=10
),
)
study.optimize(objective, n_trials=20)
Args:
n_startup_trials:
Pruning is disabled until the given number of trials finish in the same study.
n_warmup_steps:
Pruning is disabled until the trial exceeds the given number of step. Note that
this feature assumes that ``step`` starts at zero.
interval_steps:
Interval in number of steps between the pruning checks, offset by the warmup steps.
If no value has been reported at the time of a pruning check, that particular check
will be postponed until a value is reported.
n_min_trials:
Minimum number of reported trial results at a step to judge whether to prune.
If the number of reported intermediate values from all trials at the current step
is less than ``n_min_trials``, the trial will not be pruned. This can be used to ensure
that a minimum number of trials are run to completion without being pruned.
"""
def __init__(
self,
n_startup_trials: int = 5,
n_warmup_steps: int = 0,
interval_steps: int = 1,
*,
n_min_trials: int = 1,
) -> None:
super().__init__(
50.0, n_startup_trials, n_warmup_steps, interval_steps, n_min_trials=n_min_trials
)
| MedianPruner |
python | django__django | django/contrib/admin/widgets.py | {
"start": 13260,
"end": 14079
} | class ____(forms.URLInput):
template_name = "admin/widgets/url.html"
def __init__(self, attrs=None, validator_class=URLValidator):
super().__init__(attrs={"class": "vURLField", **(attrs or {})})
self.validator = validator_class()
def get_context(self, name, value, attrs):
try:
self.validator(value if value else "")
url_valid = True
except ValidationError:
url_valid = False
context = super().get_context(name, value, attrs)
context["current_label"] = _("Currently:")
context["change_label"] = _("Change:")
context["widget"]["href"] = (
smart_urlquote(context["widget"]["value"]) if url_valid else ""
)
context["url_valid"] = url_valid
return context
| AdminURLFieldWidget |
python | pandas-dev__pandas | asv_bench/benchmarks/timeseries.py | {
"start": 6986,
"end": 7439
} | class ____:
params = [True, False]
param_names = ["monotonic"]
def setup(self, monotonic):
N = 10**5
idx = date_range(start="1/1/2000", periods=N, freq="s")
self.s = Series(np.random.randn(N), index=idx)
if not monotonic:
self.s = self.s.sample(frac=1)
def time_sort_index(self, monotonic):
self.s.sort_index()
def time_get_slice(self, monotonic):
self.s[:10000]
| SortIndex |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.