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
|
EpistasisLab__tpot
|
tpot/builtin_modules/arithmetictransformer.py
|
{
"start": 13452,
"end": 14082
}
|
class ____(TransformerMixin, BaseEstimator):
def __init__(self):
"""
A transformer that returns an array of zeros.
"""
pass
def fit(self, X, y=None):
return self
def transform(self, X):
transformed_X = np.array(self.transform_helper(np.array(X)))
if transformed_X.dtype != float:
transformed_X = transformed_X.astype(float)
return transformed_X
def transform_helper(self, X):
X = np.array(X)
if len(X.shape) == 1:
X = np.expand_dims(X,0)
return np.zeros((X.shape[0],1))
|
ZeroTransformer
|
python
|
django__django
|
tests/migrations/test_migrations_plan/0003_third.py
|
{
"start": 43,
"end": 449
}
|
class ____(migrations.Migration):
dependencies = [
("migrations", "0002_second"),
]
operations = [
migrations.CreateModel(
"Author",
[
("id", models.AutoField(primary_key=True)),
],
),
migrations.RunSQL(
["SELECT * FROM migrations_author"], ["SELECT * FROM migrations_book"]
),
]
|
Migration
|
python
|
gevent__gevent
|
src/gevent/testing/util.py
|
{
"start": 15061,
"end": 17572
}
|
class ____(object):
"""
Something that uses the ``examples/`` directory
from the root of the gevent distribution.
The `cwd` property is set to the root of the gevent distribution.
"""
#: Arguments to pass to the example file.
example_args = []
before_delay = 3
after_delay = 0.5
#: Path of the example Python file, relative to `cwd`
example = None # subclasses define this to be the path to the server.py
#: Keyword arguments to pass to the start or run method.
start_kwargs = None
def find_setup_py(self):
"Return the directory containing setup.py"
return search_for_setup_py(
a_file=__file__,
a_class=type(self)
)
@property
def cwd(self):
try:
root = self.find_setup_py()
except NoSetupPyFound as e:
raise unittest.SkipTest("Unable to locate file/dir to run: %s" % (e,))
return os.path.join(root, 'examples')
@property
def setenv(self):
"""
Returns a dictionary of environment variables to set for the
child in addition to (or replacing) the ones already in the
environment.
Since the child is run in `cwd`, relative paths in ``PYTHONPATH``
need to be converted to absolute paths.
"""
abs_pythonpath = absolute_pythonpath()
return {'PYTHONPATH': abs_pythonpath} if abs_pythonpath else None
def _start(self, meth):
if getattr(self, 'args', None):
raise AssertionError("Invalid test", self, self.args)
if getattr(self, 'server', None):
raise AssertionError("Invalid test", self, self.server)
try:
# These could be or are properties that can raise
server = self.example
server_dir = self.cwd
except NoSetupPyFound as e:
raise unittest.SkipTest("Unable to locate file/dir to run: %s" % (e,))
kwargs = self.start_kwargs or {}
setenv = self.setenv
if setenv:
if 'setenv' in kwargs:
kwargs['setenv'].update(setenv)
else:
kwargs['setenv'] = setenv
return meth(
[sys.executable, '-W', 'ignore', '-u', server] + self.example_args,
cwd=server_dir,
**kwargs
)
def start_example(self):
return self._start(meth=start)
def run_example(self):# run() is a unittest method.
return self._start(meth=run)
|
ExampleMixin
|
python
|
fluentpython__example-code-2e
|
15-more-types/cafeteria/cafeteria.py
|
{
"start": 251,
"end": 436
}
|
class ____(Generic[T_co]):
def __init__(self, beverage: T_co) -> None:
self.beverage = beverage
def dispense(self) -> T_co:
return self.beverage
|
BeverageDispenser
|
python
|
apache__airflow
|
airflow-core/src/airflow/ti_deps/deps/ready_to_reschedule.py
|
{
"start": 1084,
"end": 3833
}
|
class ____(BaseTIDep):
"""Determines whether a task is ready to be rescheduled."""
NAME = "Ready To Reschedule"
IGNORABLE = True
IS_TASK_DEP = True
RESCHEDULEABLE_STATES = {TaskInstanceState.UP_FOR_RESCHEDULE, None}
@provide_session
def _get_dep_statuses(self, ti, session, dep_context):
"""
Determine whether a task is ready to be rescheduled.
Only tasks in NONE state with at least one row in task_reschedule table are
handled by this dependency class, otherwise this dependency is considered as passed.
This dependency fails if the latest reschedule request's reschedule date is still
in the future.
"""
if (
# Mapped sensors don't have the reschedule property (it can only be calculated after unmapping),
# so we don't check them here. They are handled below by checking TaskReschedule instead.
ti.map_index < 0 and not getattr(ti.task, "reschedule", False)
):
yield self._passing_status(reason="Task is not in reschedule mode.")
return
if dep_context.ignore_in_reschedule_period:
yield self._passing_status(
reason="The context specified that being in a reschedule period was permitted."
)
return
if ti.state not in self.RESCHEDULEABLE_STATES:
yield self._passing_status(
reason="The task instance is not in State_UP_FOR_RESCHEDULE or NONE state."
)
return
next_reschedule_date = session.scalar(
TaskReschedule.stmt_for_task_instance(ti, descending=True)
.with_only_columns(TaskReschedule.reschedule_date)
.limit(1)
)
if not next_reschedule_date:
# Because mapped sensors don't have the reschedule property, here's the last resort
# and we need a slightly different passing reason
if ti.map_index >= 0:
yield self._passing_status(reason="The task is mapped and not in reschedule mode")
return
yield self._passing_status(reason="There is no reschedule request for this task instance.")
return
now = timezone.utcnow()
if now >= next_reschedule_date:
yield self._passing_status(reason="Task instance id ready for reschedule.")
return
yield self._failing_status(
reason=(
"Task is not ready for reschedule yet but will be rescheduled automatically. "
f"Current date is {now.isoformat()} and task will be "
f"rescheduled at {next_reschedule_date.isoformat()}."
)
)
|
ReadyToRescheduleDep
|
python
|
huggingface__transformers
|
src/transformers/models/perception_lm/modular_perception_lm.py
|
{
"start": 5768,
"end": 12779
}
|
class ____(LlavaModel):
_checkpoint_conversion_mapping = {}
def __init__(self, config: PerceptionLMConfig):
super().__init__(config)
self.vision_tower = AutoModel.from_config(config.vision_config)
self.multi_modal_projector = PerceptionLMMultiModalProjector(config)
self.language_model = AutoModel.from_config(config.text_config)
def get_image_features(
self,
pixel_values: torch.FloatTensor,
**kwargs,
):
"""
Obtains image last hidden states from the vision tower and apply multimodal projection.
Args:
pixel_values (`torch.FloatTensor]` of shape `(batch_size, num_tiles, channels, height, width)`)
The tensors corresponding to the input images.
Returns:
image_features (`torch.Tensor`): Image feature tensor of shape `(num_tiles, num_patches, embed_dim)`).
"""
image_outputs = self.vision_tower(pixel_values.flatten(0, 1))
image_outputs = image_outputs.last_hidden_state
if self.config.vision_use_cls_token:
image_outputs = image_outputs[:, 1:, :]
image_features = self.multi_modal_projector(image_outputs)
return image_features
def get_placeholder_mask(
self,
input_ids: torch.LongTensor,
inputs_embeds: torch.FloatTensor,
image_features: Optional[torch.FloatTensor] = None,
video_features: Optional[torch.FloatTensor] = None,
):
"""
Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
equal to the length of multimodal features. If the lengths are different, an error is raised.
"""
if input_ids is None:
special_image_mask = inputs_embeds == self.get_input_embeddings()(
torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
)
special_image_mask = special_image_mask.all(-1)
special_video_mask = inputs_embeds == self.get_input_embeddings()(
torch.tensor(self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device)
)
special_video_mask = special_video_mask.all(-1)
else:
special_image_mask = input_ids == self.config.image_token_id
special_video_mask = input_ids == self.config.video_token_id
n_image_tokens = special_image_mask.sum()
special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
if image_features is not None and inputs_embeds[special_image_mask].numel() != image_features.numel():
raise ValueError(
f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {image_features.size()[:-1].numel()}"
)
n_video_tokens = special_video_mask.sum()
special_video_mask = special_video_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
if video_features is not None and inputs_embeds[special_video_mask].numel() != video_features.numel():
raise ValueError(
f"Videos features and image tokens do not match: tokens: {n_video_tokens}, features {video_features.size()[:-1].numel()}"
)
return special_image_mask, special_video_mask
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.FloatTensor] = None,
pixel_values_videos: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
**lm_kwargs,
) -> Union[tuple, PerceptionLMModelOutputWithPast]:
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
)
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if (pixel_values is not None or pixel_values_videos is not None) and inputs_embeds is not None:
raise ValueError(
"You cannot specify both (pixel_values or pixel_values_videos) and inputs_embeds at the same time, and must specify either one"
)
if inputs_embeds is None:
inputs_embeds = self.get_input_embeddings()(input_ids)
image_features = None
if pixel_values is not None:
image_features = self.get_image_features(pixel_values=pixel_values)
image_features = image_features.to(inputs_embeds.device, dtype=inputs_embeds.dtype)
special_image_mask, _ = self.get_placeholder_mask(
input_ids, inputs_embeds=inputs_embeds, image_features=image_features
)
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
video_features = None
if pixel_values_videos is not None:
video_features = self.get_image_features(pixel_values=pixel_values_videos)
video_features = video_features.to(inputs_embeds.device, dtype=inputs_embeds.dtype)
_, special_video_mask = self.get_placeholder_mask(
input_ids, inputs_embeds=inputs_embeds, video_features=video_features
)
inputs_embeds = inputs_embeds.masked_scatter(special_video_mask, video_features)
outputs = self.language_model(
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=True,
cache_position=cache_position,
logits_to_keep=logits_to_keep,
**lm_kwargs,
)
return PerceptionLMModelOutputWithPast(
last_hidden_state=outputs.last_hidden_state,
hidden_states=outputs.hidden_states,
past_key_values=outputs.past_key_values,
attentions=outputs.attentions,
image_hidden_states=image_features if pixel_values is not None else None,
video_hidden_states=(video_features if pixel_values_videos is not None else None),
)
@auto_docstring
|
PerceptionLMModel
|
python
|
neetcode-gh__leetcode
|
python/0036-valid-sudoku.py
|
{
"start": 0,
"end": 749
}
|
class ____:
def isValidSudoku(self, board: List[List[str]]) -> bool:
cols = collections.defaultdict(set)
rows = collections.defaultdict(set)
squares = collections.defaultdict(set) # key = (r /3, c /3)
for r in range(9):
for c in range(9):
if board[r][c] == ".":
continue
if (
board[r][c] in rows[r]
or board[r][c] in cols[c]
or board[r][c] in squares[(r // 3, c // 3)]
):
return False
cols[c].add(board[r][c])
rows[r].add(board[r][c])
squares[(r // 3, c // 3)].add(board[r][c])
return True
|
Solution
|
python
|
getsentry__sentry
|
src/sentry/sentry_apps/api/parsers/sentry_app.py
|
{
"start": 2026,
"end": 2498
}
|
class ____(serializers.URLField):
def to_internal_value(self, url):
# The Django URLField doesn't distinguish between different types of
# invalid URLs, so do any manual checks here to give the User a better
# error message.
if url and not url.startswith("http"):
raise ValidationError("URL must start with http[s]://")
return url
@extend_schema_serializer(exclude_fields=["popularity", "features", "status"])
|
URLField
|
python
|
langchain-ai__langchain
|
libs/standard-tests/langchain_tests/unit_tests/embeddings.py
|
{
"start": 734,
"end": 4597
}
|
class ____(EmbeddingsTests):
"""Base class for embeddings unit tests.
Test subclasses must implement the `embeddings_class` property to specify the
embeddings model to be tested. You can also override the
`embedding_model_params` property to specify initialization parameters.
```python
from typing import Type
from langchain_tests.unit_tests import EmbeddingsUnitTests
from my_package.embeddings import MyEmbeddingsModel
class TestMyEmbeddingsModelUnit(EmbeddingsUnitTests):
@property
def embeddings_class(self) -> Type[MyEmbeddingsModel]:
# Return the embeddings model class to test here
return MyEmbeddingsModel
@property
def embedding_model_params(self) -> dict:
# Return initialization parameters for the model.
return {"model": "model-001"}
```
!!! note
API references for individual test methods include troubleshooting tips.
Testing initialization from environment variables
Overriding the `init_from_env_params` property will enable additional tests
for initialization from environment variables. See below for details.
??? note "`init_from_env_params`"
This property is used in unit tests to test initialization from
environment variables. It should return a tuple of three dictionaries
that specify the environment variables, additional initialization args,
and expected instance attributes to check.
Defaults to empty dicts. If not overridden, the test is skipped.
```python
@property
def init_from_env_params(self) -> Tuple[dict, dict, dict]:
return (
{
"MY_API_KEY": "api_key",
},
{
"model": "model-001",
},
{
"my_api_key": "api_key",
},
)
```
"""
def test_init(self) -> None:
"""Test model initialization.
??? note "Troubleshooting"
If this test fails, ensure that `embedding_model_params` is specified
and the model can be initialized from those params.
"""
model = self.embeddings_class(**self.embedding_model_params)
assert model is not None
@property
def init_from_env_params(self) -> tuple[dict, dict, dict]:
"""Init from env params.
This property is used in unit tests to test initialization from environment
variables. It should return a tuple of three dictionaries that specify the
environment variables, additional initialization args, and expected instance
attributes to check.
"""
return {}, {}, {}
def test_init_from_env(self) -> None:
"""Test initialization from environment variables.
Relies on the `init_from_env_params` property.
Test is skipped if that property is not set.
??? note "Troubleshooting"
If this test fails, ensure that `init_from_env_params` is specified
correctly and that model parameters are properly set from environment
variables during initialization.
"""
env_params, embeddings_params, expected_attrs = self.init_from_env_params
if env_params:
with mock.patch.dict(os.environ, env_params):
model = self.embeddings_class(**embeddings_params)
assert model is not None
for k, expected in expected_attrs.items():
actual = getattr(model, k)
if isinstance(actual, SecretStr):
actual = actual.get_secret_value()
assert actual == expected
|
EmbeddingsUnitTests
|
python
|
kamyu104__LeetCode-Solutions
|
Python/query-kth-smallest-trimmed-number.py
|
{
"start": 58,
"end": 1108
}
|
class ____(object):
def smallestTrimmedNumbers(self, nums, queries):
"""
:type nums: List[str]
:type queries: List[List[int]]
:rtype: List[int]
"""
max_t = max(t for _, t in queries)
lookup = [[] for _ in xrange(max_t+1)]
for i, (k, t) in enumerate(queries):
lookup[t].append((k, i))
result = [0]*len(queries)
idxs = range(len(nums))
for l in xrange(1, max_t+1):
cnt = [0]*10
for i in idxs:
d = int(nums[i][-l])
cnt[d] += 1
for d in xrange(9):
cnt[d+1] += cnt[d]
new_idxs = [0]*len(nums)
for i in reversed(idxs):
d = int(nums[i][-l])
cnt[d] -= 1
new_idxs[cnt[d]] = i
idxs = new_idxs
for k, i in lookup[l]:
result[i] = idxs[k-1]
return result
# Time: O(q * n * t) on average
# Space: O(n + q)
import random
# quick select
|
Solution
|
python
|
ray-project__ray
|
python/ray/serve/tests/unit/test_proxy_state.py
|
{
"start": 949,
"end": 1159
}
|
class ____:
def __init__(self, *args, **kwargs):
pass
def ready(self):
return json.dumps(["mock_worker_id", "mock_log_file_path"])
def check_health(self):
pass
|
FakeProxyActor
|
python
|
PrefectHQ__prefect
|
src/prefect/cli/transfer/_migratable_resources/deployments.py
|
{
"start": 947,
"end": 10191
}
|
class ____(MigratableResource[DeploymentResponse]):
_instances: dict[uuid.UUID, Self] = {}
def __init__(self, deployment: DeploymentResponse):
self.source_deployment = deployment
self.destination_deployment: DeploymentResponse | None = None
self._dependencies: dict[uuid.UUID, MigratableProtocol] = {}
@property
def source_id(self) -> uuid.UUID:
return self.source_deployment.id
@property
def destination_id(self) -> uuid.UUID | None:
return self.destination_deployment.id if self.destination_deployment else None
@classmethod
async def construct(cls, obj: DeploymentResponse) -> Self:
if obj.id in cls._instances:
return cls._instances[obj.id]
instance = cls(obj)
cls._instances[obj.id] = instance
return instance
@classmethod
async def get_instance(
cls, id: uuid.UUID
) -> "MigratableResource[DeploymentResponse] | None":
if id in cls._instances:
return cls._instances[id]
return None
async def get_dependencies(self) -> "list[MigratableProtocol]":
if self._dependencies:
return list(self._dependencies.values())
async with get_client() as client:
if dependency := await MigratableFlow.get_instance(
id=self.source_deployment.flow_id
):
self._dependencies[self.source_deployment.flow_id] = dependency
else:
flow = await client.read_flow(self.source_deployment.flow_id)
self._dependencies[
self.source_deployment.flow_id
] = await construct_migratable_resource(flow)
if self.source_deployment.work_queue_id is not None:
if dependency := await MigratableWorkQueue.get_instance(
id=self.source_deployment.work_queue_id
):
self._dependencies[self.source_deployment.work_queue_id] = (
dependency
)
else:
work_queue = await client.read_work_queue(
self.source_deployment.work_queue_id
)
self._dependencies[
work_queue.id
] = await construct_migratable_resource(work_queue)
if self.source_deployment.work_pool_name is not None:
if dependency := await MigratableWorkPool.get_instance_by_name(
name=self.source_deployment.work_pool_name
):
self._dependencies[dependency.source_id] = dependency
else:
work_pool = await client.read_work_pool(
self.source_deployment.work_pool_name
)
self._dependencies[
work_pool.id
] = await construct_migratable_resource(work_pool)
if self.source_deployment.storage_document_id is not None:
if dependency := await MigratableBlockDocument.get_instance(
id=self.source_deployment.storage_document_id
):
self._dependencies[self.source_deployment.storage_document_id] = (
dependency
)
else:
storage_document = await client.read_block_document(
self.source_deployment.storage_document_id
)
self._dependencies[
storage_document.id
] = await construct_migratable_resource(storage_document)
if self.source_deployment.infrastructure_document_id is not None:
if dependency := await MigratableBlockDocument.get_instance(
id=self.source_deployment.infrastructure_document_id
):
self._dependencies[
self.source_deployment.infrastructure_document_id
] = dependency
else:
infrastructure_document = await client.read_block_document(
self.source_deployment.infrastructure_document_id
)
self._dependencies[
infrastructure_document.id
] = await construct_migratable_resource(infrastructure_document)
if self.source_deployment.pull_steps:
# TODO: Figure out how to find block document references in pull steps
pass
return list(self._dependencies.values())
async def migrate(self) -> None:
async with get_client() as client:
try:
if (
destination_flow_id := getattr(
self._dependencies.get(self.source_deployment.flow_id),
"destination_id",
None,
)
) is None:
raise ValueError("Unable to find destination flow")
if (
self.source_deployment.storage_document_id
and (
destination_storage_document_id := getattr(
self._dependencies.get(
self.source_deployment.storage_document_id
),
"destination_id",
None,
)
)
is None
):
raise ValueError("Unable to find destination storage document")
else:
destination_storage_document_id = None
if (
self.source_deployment.infrastructure_document_id
and (
destination_infrastructure_document_id := getattr(
self._dependencies.get(
self.source_deployment.infrastructure_document_id
),
"destination_id",
None,
)
)
is None
):
raise ValueError(
"Unable to find destination infrastructure document"
)
else:
destination_infrastructure_document_id = None
destination_deployment_id = await client.create_deployment(
flow_id=destination_flow_id,
name=self.source_deployment.name,
version=self.source_deployment.version,
version_info=self.source_deployment.version_info,
schedules=[
DeploymentScheduleCreate(
schedule=schedule.schedule,
active=schedule.active,
max_scheduled_runs=schedule.max_scheduled_runs,
parameters=schedule.parameters,
slug=schedule.slug,
)
for schedule in self.source_deployment.schedules
],
concurrency_limit=self.source_deployment.concurrency_limit,
concurrency_options=self.source_deployment.concurrency_options,
parameters=self.source_deployment.parameters,
description=self.source_deployment.description,
work_queue_name=self.source_deployment.work_queue_name,
work_pool_name=self.source_deployment.work_pool_name,
tags=self.source_deployment.tags,
storage_document_id=destination_storage_document_id,
path=self.source_deployment.path,
entrypoint=self.source_deployment.entrypoint,
infrastructure_document_id=destination_infrastructure_document_id,
parameter_openapi_schema=self.source_deployment.parameter_openapi_schema,
paused=self.source_deployment.paused,
pull_steps=self.source_deployment.pull_steps,
enforce_parameter_schema=self.source_deployment.enforce_parameter_schema,
job_variables=self.source_deployment.job_variables,
branch=self.source_deployment.branch,
base=self.source_deployment.base,
root=self.source_deployment.root,
)
self.destination_deployment = await client.read_deployment(
destination_deployment_id
)
except ObjectLimitReached:
raise TransferSkipped("Deployment limit reached (upgrade tier)")
except ObjectAlreadyExists:
self.destination_deployment = await client.read_deployment(
self.source_deployment.id
)
raise TransferSkipped("Already exists")
|
MigratableDeployment
|
python
|
PyCQA__pylint
|
pylint/reporters/reports_handler_mix_in.py
|
{
"start": 754,
"end": 3304
}
|
class ____:
"""A mix-in class containing all the reports and stats manipulation
related methods for the main lint class.
"""
def __init__(self) -> None:
self._reports: ReportsDict = collections.defaultdict(list)
self._reports_state: dict[str, bool] = {}
def report_order(self) -> MutableSequence[BaseChecker]:
"""Return a list of reporters."""
return list(self._reports)
def register_report(
self, reportid: str, r_title: str, r_cb: ReportsCallable, checker: BaseChecker
) -> None:
"""Register a report.
:param reportid: The unique identifier for the report
:param r_title: The report's title
:param r_cb: The method to call to make the report
:param checker: The checker defining the report
"""
reportid = reportid.upper()
self._reports[checker].append((reportid, r_title, r_cb))
def deregister_reports(self, checker: BaseChecker) -> None:
"""De-register all reports for a checker."""
for r_id, r_title, r_cb in checker.reports:
self._reports[checker].remove((r_id, r_title, r_cb))
def enable_report(self, reportid: str) -> None:
"""Enable the report of the given id."""
reportid = reportid.upper()
self._reports_state[reportid] = True
def disable_report(self, reportid: str) -> None:
"""Disable the report of the given id."""
reportid = reportid.upper()
self._reports_state[reportid] = False
def report_is_enabled(self, reportid: str) -> bool:
"""Is the report associated to the given identifier enabled ?"""
return self._reports_state.get(reportid, True)
def make_reports( # type: ignore[misc] # ReportsHandlerMixIn is always mixed with PyLinter
self: PyLinter,
stats: LinterStats,
old_stats: LinterStats | None,
) -> Section:
"""Render registered reports."""
sect = Section("Report", f"{self.stats.statement} statements analysed.")
for checker in self.report_order():
for reportid, r_title, r_cb in self._reports[checker]:
if not self.report_is_enabled(reportid):
continue
report_sect = Section(r_title)
try:
r_cb(report_sect, stats, old_stats)
except EmptyReportError:
continue
report_sect.report_id = reportid
sect.append(report_sect)
return sect
|
ReportsHandlerMixIn
|
python
|
PyCQA__pylint
|
tests/functional/i/implicit/implicit_flag_alias.py
|
{
"start": 369,
"end": 509
}
|
class ____(ExplicitUnionFlags): # [invalid-enum-extension]
"""Class with flags that overlap a superclass"""
RWX = 7
|
SubclassUnionFlags
|
python
|
great-expectations__great_expectations
|
contrib/experimental/great_expectations_experimental/rule_based_profiler/data_assistant/statistics_data_assistant.py
|
{
"start": 1343,
"end": 32260
}
|
class ____(DataAssistant):
"""
StatisticsDataAssistant provides metrics for dataset exploration purposes.
Fundamentally, StatisticsDataAssistant is "OnboardingDataAssistant minus Expectations -- only Metrics", the intended
usecase being obtaining description of data via metrics as well as comparing metrics between sub-sampeled datasets
to determine the smallest dataset, whose statistics represent the overall data distribution sufficiantly adequately.
"""
__alias__: str = "statistics"
def __init__(
self,
name: str,
validator: Validator,
) -> None:
super().__init__(
name=name,
validator=validator,
)
def get_variables(self) -> Optional[Dict[str, Any]]:
"""
Returns:
Optional "variables" configuration attribute name/value pairs (overrides), commonly-used in Builder objects.
"""
return None
def get_rules(self) -> Optional[List[Rule]]:
"""
Returns:
Optional custom list of "Rule" objects implementing particular "DataAssistant" functionality.
"""
total_count_metric_multi_batch_parameter_builder_for_evaluations: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.get_table_row_count_metric_multi_batch_parameter_builder()
column_integrity_rule: Rule = self._build_column_integrity_rule(
total_count_metric_multi_batch_parameter_builder_for_evaluations=total_count_metric_multi_batch_parameter_builder_for_evaluations
)
numeric_columns_rule: Rule = self._build_numeric_columns_rule()
datetime_columns_rule: Rule = self._build_datetime_columns_rule()
text_columns_rule: Rule = self._build_text_columns_rule()
categorical_columns_rule: Rule = self._build_categorical_columns_rule()
return [
column_integrity_rule,
numeric_columns_rule,
datetime_columns_rule,
text_columns_rule,
categorical_columns_rule,
]
def _build_data_assistant_result(
self, data_assistant_result: DataAssistantResult
) -> DataAssistantResult:
return StatisticsDataAssistantResult(
_batch_id_to_batch_identifier_display_name_map=data_assistant_result._batch_id_to_batch_identifier_display_name_map,
profiler_config=data_assistant_result.profiler_config,
profiler_execution_time=data_assistant_result.profiler_execution_time,
rule_domain_builder_execution_time=data_assistant_result.rule_domain_builder_execution_time,
rule_execution_time=data_assistant_result.rule_execution_time,
rule_exception_tracebacks=data_assistant_result.rule_exception_tracebacks,
metrics_by_domain=data_assistant_result.metrics_by_domain,
expectation_configurations=data_assistant_result.expectation_configurations,
citation=data_assistant_result.citation,
)
@staticmethod
def _build_table_rule() -> Rule:
"""
This method builds "Rule" object focused on emitting "ParameterBuilder" objects for table "Domain" type metrics.
"""
# Step-1: Instantiate "TableDomainBuilder" object.
table_domain_builder: DomainBuilder = TableDomainBuilder(
data_context=None,
)
# Step-2: Declare "ParameterBuilder" for every metric of interest.
table_row_count_metric_multi_batch_parameter_builder_for_metrics: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.get_table_row_count_metric_multi_batch_parameter_builder()
table_columns_metric_multi_batch_parameter_builder_for_metrics: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.get_table_columns_metric_multi_batch_parameter_builder()
# Step-3: Declare "ParameterBuilder" configurations for all additional statistics needed.
suite_parameter_builder_configs: Optional[List[ParameterBuilderConfig]] = [
ParameterBuilderConfig(
**table_row_count_metric_multi_batch_parameter_builder_for_metrics.to_json_dict()
),
]
table_row_count_range_parameter_builder_for_validations: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.build_numeric_metric_range_multi_batch_parameter_builder(
metric_name=None,
suffix=None,
metric_value_kwargs=None,
suite_parameter_builder_configs=suite_parameter_builder_configs,
)
mean_table_columns_set_match_multi_batch_parameter_builder_for_validations = (
MeanTableColumnsSetMatchMultiBatchParameterBuilder(
name="column_names_set_estimator",
metric_domain_kwargs=DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME,
metric_value_kwargs=None,
suite_parameter_builder_configs=None,
)
)
# Step-4: Instantiate and return "Rule" object, comprised of "variables", "domain_builder", "parameter_builders", and "expectation_configuration_builders" components.
variables: dict = {
"false_positive_rate": 0.05,
"estimator": "bootstrap",
"n_resamples": 9999,
"random_seed": None,
"quantile_statistic_interpolation_method": "nearest",
"quantile_bias_correction": False,
"quantile_bias_std_error_ratio_threshold": None,
"include_estimator_samples_histogram_in_details": False,
"truncate_values": {
"lower_bound": 0,
"upper_bound": None,
},
"round_decimals": 0,
"exact_match": None,
"success_ratio": 1.0,
}
parameter_builders: List[ParameterBuilder] = [
table_row_count_metric_multi_batch_parameter_builder_for_metrics,
table_columns_metric_multi_batch_parameter_builder_for_metrics,
table_row_count_range_parameter_builder_for_validations,
mean_table_columns_set_match_multi_batch_parameter_builder_for_validations,
]
rule = Rule(
name="table_rule",
variables=variables,
domain_builder=table_domain_builder,
parameter_builders=parameter_builders,
expectation_configuration_builders=None,
)
return rule
@staticmethod
def _build_column_integrity_rule(
total_count_metric_multi_batch_parameter_builder_for_evaluations: Optional[
ParameterBuilder
] = None,
) -> Rule:
"""
This method builds "Rule" object focused on emitting "map" style column integrity metrics.
"""
# Step-1: Instantiate "ColumnDomainBuilder" for selecting all columns.
every_column_domain_builder: DomainBuilder = ColumnDomainBuilder(
include_column_names=None,
exclude_column_names=None,
include_column_name_suffixes=None,
exclude_column_name_suffixes=None,
semantic_type_filter_module_name=None,
semantic_type_filter_class_name=None,
include_semantic_types=None,
exclude_semantic_types=None,
data_context=None,
)
# Step-2: Declare "ParameterBuilder" for every metric of interest.
column_values_nonnull_unexpected_count_metric_multi_batch_parameter_builder_for_metrics: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.get_column_values_nonnull_unexpected_count_metric_multi_batch_parameter_builder()
# Step-3: Declare "ParameterBuilder" configurations for all additional statistics needed.
suite_parameter_builder_configs: Optional[List[ParameterBuilderConfig]]
if total_count_metric_multi_batch_parameter_builder_for_evaluations is None:
total_count_metric_multi_batch_parameter_builder_for_evaluations = DataAssistant.commonly_used_parameter_builders.get_table_row_count_metric_multi_batch_parameter_builder()
column_values_nonnull_unexpected_count_metric_multi_batch_parameter_builder_for_evaluations = column_values_nonnull_unexpected_count_metric_multi_batch_parameter_builder_for_metrics
suite_parameter_builder_configs: Optional[List[ParameterBuilderConfig]] = [
ParameterBuilderConfig(
**total_count_metric_multi_batch_parameter_builder_for_evaluations.to_json_dict()
),
ParameterBuilderConfig(
**column_values_nonnull_unexpected_count_metric_multi_batch_parameter_builder_for_evaluations.to_json_dict()
),
]
map_metric_name: str
map_metric_name = "column_values.unique"
column_values_unique_mean_unexpected_value_multi_batch_parameter_builder_for_validations = MeanUnexpectedMapMetricMultiBatchParameterBuilder(
name=f"{map_metric_name}.unexpected_value",
map_metric_name=map_metric_name,
total_count_parameter_builder_name=total_count_metric_multi_batch_parameter_builder_for_evaluations.name,
null_count_parameter_builder_name=column_values_nonnull_unexpected_count_metric_multi_batch_parameter_builder_for_evaluations.name,
metric_domain_kwargs=DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME,
metric_value_kwargs=None,
suite_parameter_builder_configs=suite_parameter_builder_configs,
data_context=None,
)
map_metric_name = "column_values.null"
column_values_null_mean_unexpected_value_multi_batch_parameter_builder_for_validations = MeanUnexpectedMapMetricMultiBatchParameterBuilder(
name=f"{map_metric_name}.unexpected_value",
map_metric_name=map_metric_name,
total_count_parameter_builder_name=total_count_metric_multi_batch_parameter_builder_for_evaluations.name,
null_count_parameter_builder_name=column_values_nonnull_unexpected_count_metric_multi_batch_parameter_builder_for_evaluations.name,
metric_domain_kwargs=DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME,
metric_value_kwargs=None,
suite_parameter_builder_configs=suite_parameter_builder_configs,
data_context=None,
)
map_metric_name = "column_values.nonnull"
column_values_nonnull_mean_unexpected_value_multi_batch_parameter_builder_for_validations = MeanUnexpectedMapMetricMultiBatchParameterBuilder(
name=f"{map_metric_name}.unexpected_value",
map_metric_name=map_metric_name,
total_count_parameter_builder_name=total_count_metric_multi_batch_parameter_builder_for_evaluations.name,
null_count_parameter_builder_name=column_values_nonnull_unexpected_count_metric_multi_batch_parameter_builder_for_evaluations.name,
metric_domain_kwargs=DOMAIN_KWARGS_PARAMETER_FULLY_QUALIFIED_NAME,
metric_value_kwargs=None,
suite_parameter_builder_configs=suite_parameter_builder_configs,
data_context=None,
)
# Step-4: Instantiate and return "Rule" object, comprised of "variables", "domain_builder", "parameter_builders", and "expectation_configuration_builders" components.
variables: dict = {
"success_ratio": 7.5e-1,
}
parameter_builders: List[ParameterBuilder] = [
column_values_unique_mean_unexpected_value_multi_batch_parameter_builder_for_validations,
column_values_null_mean_unexpected_value_multi_batch_parameter_builder_for_validations,
column_values_nonnull_mean_unexpected_value_multi_batch_parameter_builder_for_validations,
]
rule = Rule(
name="column_integrity_rule",
variables=variables,
domain_builder=every_column_domain_builder,
parameter_builders=parameter_builders,
expectation_configuration_builders=None,
)
return rule
@staticmethod
def _build_numeric_columns_rule() -> Rule:
"""
This method builds "Rule" object focused on emitting "ParameterBuilder" objects for numeric columns "Domain" type metrics.
"""
# Step-1: Instantiate "ColumnDomainBuilder" for selecting numeric columns (but not "ID-type" columns).
numeric_column_type_domain_builder: DomainBuilder = ColumnDomainBuilder(
include_column_names=None,
exclude_column_names=None,
include_column_name_suffixes=None,
exclude_column_name_suffixes=[
"_id",
"_ID",
],
semantic_type_filter_module_name=None,
semantic_type_filter_class_name=None,
include_semantic_types=[
SemanticDomainTypes.NUMERIC,
],
exclude_semantic_types=[
SemanticDomainTypes.IDENTIFIER,
],
data_context=None,
)
# Step-2: Declare "ParameterBuilder" for every metric of interest.
column_min_metric_multi_batch_parameter_builder_for_metrics: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.get_column_min_metric_multi_batch_parameter_builder()
column_max_metric_multi_batch_parameter_builder_for_metrics: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.get_column_max_metric_multi_batch_parameter_builder()
column_quantile_values_metric_multi_batch_parameter_builder_for_metrics: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.get_column_quantile_values_metric_multi_batch_parameter_builder()
column_median_metric_multi_batch_parameter_builder_for_metrics: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.get_column_median_metric_multi_batch_parameter_builder()
column_mean_metric_multi_batch_parameter_builder_for_metrics: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.get_column_mean_metric_multi_batch_parameter_builder()
column_standard_deviation_metric_multi_batch_parameter_builder_for_metrics: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.get_column_standard_deviation_metric_multi_batch_parameter_builder()
# Step-3: Declare "ParameterBuilder" configurations for all additional statistics needed.
suite_parameter_builder_configs: Optional[List[ParameterBuilderConfig]]
suite_parameter_builder_configs = [
ParameterBuilderConfig(
**column_min_metric_multi_batch_parameter_builder_for_metrics.to_json_dict()
),
]
column_min_values_range_parameter_builder_for_validations: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.build_numeric_metric_range_multi_batch_parameter_builder(
metric_name=None,
suffix=None,
metric_value_kwargs=None,
suite_parameter_builder_configs=suite_parameter_builder_configs,
)
suite_parameter_builder_configs = [
ParameterBuilderConfig(
**column_max_metric_multi_batch_parameter_builder_for_metrics.to_json_dict()
),
]
column_max_values_range_parameter_builder_for_validations: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.build_numeric_metric_range_multi_batch_parameter_builder(
metric_name=None,
suffix=None,
metric_value_kwargs=None,
suite_parameter_builder_configs=suite_parameter_builder_configs,
)
suite_parameter_builder_configs = [
ParameterBuilderConfig(
**column_quantile_values_metric_multi_batch_parameter_builder_for_metrics.to_json_dict()
),
]
column_quantile_values_range_parameter_builder_for_validations: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.build_numeric_metric_range_multi_batch_parameter_builder(
metric_name=None,
suffix=None,
metric_value_kwargs={
"quantiles": f"{VARIABLES_KEY}quantiles",
"allow_relative_error": f"{VARIABLES_KEY}allow_relative_error",
},
suite_parameter_builder_configs=suite_parameter_builder_configs,
)
suite_parameter_builder_configs = [
ParameterBuilderConfig(
**column_median_metric_multi_batch_parameter_builder_for_metrics.to_json_dict()
),
]
column_median_values_range_parameter_builder_for_validations: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.build_numeric_metric_range_multi_batch_parameter_builder(
metric_name=None,
suffix=None,
metric_value_kwargs=None,
suite_parameter_builder_configs=suite_parameter_builder_configs,
)
suite_parameter_builder_configs = [
ParameterBuilderConfig(
**column_mean_metric_multi_batch_parameter_builder_for_metrics.to_json_dict()
),
]
column_mean_values_range_parameter_builder_for_validations: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.build_numeric_metric_range_multi_batch_parameter_builder(
metric_name=None,
suffix=None,
metric_value_kwargs=None,
suite_parameter_builder_configs=suite_parameter_builder_configs,
)
suite_parameter_builder_configs = [
ParameterBuilderConfig(
**column_standard_deviation_metric_multi_batch_parameter_builder_for_metrics.to_json_dict()
),
]
column_standard_deviation_values_range_parameter_builder_for_validations: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.build_numeric_metric_range_multi_batch_parameter_builder(
metric_name=None,
suffix=None,
metric_value_kwargs=None,
suite_parameter_builder_configs=suite_parameter_builder_configs,
)
# Step-4: Instantiate and return "Rule" object, comprised of "variables", "domain_builder", "parameter_builders", and "expectation_configuration_builders" components.
variables: dict = {
"mostly": 1.0,
"strict_min": False,
"strict_max": False,
"quantiles": [
0.25,
0.5,
0.75,
],
"allow_relative_error": False,
"false_positive_rate": 0.05,
"estimator": "bootstrap",
"n_resamples": 9999,
"random_seed": None,
"quantile_statistic_interpolation_method": "nearest",
"quantile_bias_correction": False,
"quantile_bias_std_error_ratio_threshold": None,
"include_estimator_samples_histogram_in_details": False,
"truncate_values": {
"lower_bound": None,
"upper_bound": None,
},
"round_decimals": 15,
}
parameter_builders: List[ParameterBuilder] = [
column_min_values_range_parameter_builder_for_validations,
column_max_values_range_parameter_builder_for_validations,
column_quantile_values_range_parameter_builder_for_validations,
column_median_values_range_parameter_builder_for_validations,
column_mean_values_range_parameter_builder_for_validations,
column_standard_deviation_values_range_parameter_builder_for_validations,
]
rule = Rule(
name="numeric_columns_rule",
variables=variables,
domain_builder=numeric_column_type_domain_builder,
parameter_builders=parameter_builders,
expectation_configuration_builders=None,
)
return rule
@staticmethod
def _build_datetime_columns_rule() -> Rule:
"""
This method builds "Rule" object focused on emitting "ParameterBuilder" objects for datetime columns "Domain" type metrics.
"""
# Step-1: Instantiate "ColumnDomainBuilder" for selecting proper datetime columns (not "datetime-looking" text).
datetime_column_type_domain_builder: DomainBuilder = ColumnDomainBuilder(
include_column_names=None,
exclude_column_names=None,
include_column_name_suffixes=None,
exclude_column_name_suffixes=None,
semantic_type_filter_module_name=None,
semantic_type_filter_class_name=None,
include_semantic_types=[
SemanticDomainTypes.DATETIME,
],
exclude_semantic_types=[
SemanticDomainTypes.TEXT,
],
data_context=None,
)
# Step-2: Declare "ParameterBuilder" for every metric of interest.
column_min_metric_multi_batch_parameter_builder_for_metrics: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.get_column_min_metric_multi_batch_parameter_builder()
column_max_metric_multi_batch_parameter_builder_for_metrics: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.get_column_max_metric_multi_batch_parameter_builder()
# Step-3: Declare "ParameterBuilder" configurations for all additional statistics needed.
suite_parameter_builder_configs: Optional[List[ParameterBuilderConfig]]
suite_parameter_builder_configs = [
ParameterBuilderConfig(
**column_min_metric_multi_batch_parameter_builder_for_metrics.to_json_dict()
),
]
column_min_values_range_parameter_builder_for_validations: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.build_numeric_metric_range_multi_batch_parameter_builder(
metric_name=None,
suffix=None,
metric_value_kwargs=None,
suite_parameter_builder_configs=suite_parameter_builder_configs,
)
suite_parameter_builder_configs = [
ParameterBuilderConfig(
**column_max_metric_multi_batch_parameter_builder_for_metrics.to_json_dict()
),
]
column_max_values_range_parameter_builder_for_validations: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.build_numeric_metric_range_multi_batch_parameter_builder(
metric_name=None,
suffix=None,
metric_value_kwargs=None,
suite_parameter_builder_configs=suite_parameter_builder_configs,
)
# Step-4: Instantiate and return "Rule" object, comprised of "variables", "domain_builder", "parameter_builders", and "expectation_configuration_builders" components.
variables: dict = {
"mostly": 1.0,
"strict_min": False,
"strict_max": False,
"false_positive_rate": 0.05,
"estimator": "bootstrap",
"n_resamples": 9999,
"random_seed": None,
"quantile_statistic_interpolation_method": "nearest",
"quantile_bias_correction": False,
"quantile_bias_std_error_ratio_threshold": None,
"include_estimator_samples_histogram_in_details": False,
"truncate_values": {
"lower_bound": None,
"upper_bound": None,
},
"round_decimals": 1,
}
parameter_builders: List[ParameterBuilder] = [
column_min_values_range_parameter_builder_for_validations,
column_max_values_range_parameter_builder_for_validations,
]
rule = Rule(
name="datetime_columns_rule",
variables=variables,
domain_builder=datetime_column_type_domain_builder,
parameter_builders=parameter_builders,
expectation_configuration_builders=None,
)
return rule
@staticmethod
def _build_text_columns_rule() -> Rule:
# Step-1: Instantiate "ColumnDomainBuilder" for selecting proper text columns.
text_column_type_domain_builder: DomainBuilder = ColumnDomainBuilder(
include_column_names=None,
exclude_column_names=None,
include_column_name_suffixes=None,
exclude_column_name_suffixes=None,
semantic_type_filter_module_name=None,
semantic_type_filter_class_name=None,
include_semantic_types=[
SemanticDomainTypes.TEXT,
],
exclude_semantic_types=[
SemanticDomainTypes.NUMERIC,
SemanticDomainTypes.DATETIME,
],
data_context=None,
)
# Step-2: Declare "ParameterBuilder" for every metric of interest.
column_min_length_metric_multi_batch_parameter_builder_for_metrics: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.get_column_min_length_metric_multi_batch_parameter_builder()
column_max_length_metric_multi_batch_parameter_builder_for_metrics: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.get_column_max_length_metric_multi_batch_parameter_builder()
# Step-3: Declare "ParameterBuilder" configurations for all additional statistics needed.
suite_parameter_builder_configs: Optional[List[ParameterBuilderConfig]]
suite_parameter_builder_configs = [
ParameterBuilderConfig(
**column_min_length_metric_multi_batch_parameter_builder_for_metrics.to_json_dict()
),
]
column_min_length_range_parameter_builder_for_validations: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.build_numeric_metric_range_multi_batch_parameter_builder(
metric_name=None,
suffix=None,
metric_value_kwargs=None,
suite_parameter_builder_configs=suite_parameter_builder_configs,
)
suite_parameter_builder_configs = [
ParameterBuilderConfig(
**column_max_length_metric_multi_batch_parameter_builder_for_metrics.to_json_dict()
),
]
column_max_length_range_parameter_builder_for_validations: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.build_numeric_metric_range_multi_batch_parameter_builder(
metric_name=None,
suffix=None,
metric_value_kwargs=None,
suite_parameter_builder_configs=suite_parameter_builder_configs,
)
# Step-4: Instantiate and return "Rule" object, comprised of "variables", "domain_builder", "parameter_builders", and "expectation_configuration_builders" components.
variables: dict = {
"mostly": 1.0,
"strict_min": False,
"strict_max": False,
"false_positive_rate": 0.05,
"estimator": "bootstrap",
"n_resamples": 9999,
"random_seed": None,
"quantile_statistic_interpolation_method": "nearest",
"quantile_bias_correction": False,
"quantile_bias_std_error_ratio_threshold": None,
"include_estimator_samples_histogram_in_details": False,
"truncate_values": {
"lower_bound": 0,
"upper_bound": None,
},
"round_decimals": 0,
"success_ratio": 7.5e-1,
}
parameter_builders: List[ParameterBuilder] = [
column_min_length_range_parameter_builder_for_validations,
column_max_length_range_parameter_builder_for_validations,
]
rule = Rule(
name="text_columns_rule",
variables=variables,
domain_builder=text_column_type_domain_builder,
parameter_builders=parameter_builders,
expectation_configuration_builders=None,
)
return rule
@staticmethod
def _build_categorical_columns_rule() -> Rule:
"""
This method builds "Rule" object focused on emitting "ParameterBuilder" objects for categorical columns "Domain" type metrics.
"""
# Step-1: Instantiate "CategoricalColumnDomainBuilder" for selecting columns containing "FEW" discrete values.
categorical_column_type_domain_builder: DomainBuilder = ColumnDomainBuilder(
include_column_names=None,
exclude_column_names=None,
include_column_name_suffixes=None,
exclude_column_name_suffixes=[
"_id",
],
semantic_type_filter_module_name=None,
semantic_type_filter_class_name=None,
include_semantic_types=[
SemanticDomainTypes.LOGIC,
SemanticDomainTypes.TEXT,
],
exclude_semantic_types=[
SemanticDomainTypes.BINARY,
SemanticDomainTypes.CURRENCY,
SemanticDomainTypes.IDENTIFIER,
],
data_context=None,
)
# Step-2: Declare "ParameterBuilder" for every metric of interest.
# Step-3: Declare "ParameterBuilder" configurations for all additional statistics needed.
column_unique_proportion_range_parameter_builder_for_validations: ParameterBuilder = DataAssistant.commonly_used_parameter_builders.build_numeric_metric_range_multi_batch_parameter_builder(
metric_name="column.unique_proportion",
suffix=None,
metric_value_kwargs=None,
)
# Step-4: Instantiate and return "Rule" object, comprised of "variables", "domain_builder", "parameter_builders", and "expectation_configuration_builders" components.
variables: dict = {
"cardinality_limit_mode": CardinalityLimitMode.FEW.name,
"mostly": 1.0,
"strict_min": False,
"strict_max": False,
"false_positive_rate": 0.05,
"estimator": "bootstrap",
"n_resamples": 9999,
"random_seed": None,
"quantile_statistic_interpolation_method": "nearest",
"quantile_bias_correction": False,
"quantile_bias_std_error_ratio_threshold": None,
"include_estimator_samples_histogram_in_details": False,
"truncate_values": {
"lower_bound": 0.0,
"upper_bound": None,
},
"round_decimals": 15,
}
parameter_builders: List[ParameterBuilder] = [
column_unique_proportion_range_parameter_builder_for_validations,
]
rule = Rule(
name="categorical_columns_rule",
variables=variables,
domain_builder=categorical_column_type_domain_builder,
parameter_builders=parameter_builders,
expectation_configuration_builders=None,
)
return rule
|
StatisticsDataAssistant
|
python
|
getsentry__sentry
|
src/sentry/auth/providers/saml2/jumpcloud/provider.py
|
{
"start": 80,
"end": 177
}
|
class ____(GenericSAML2Provider):
name = "Jumpcloud"
key = "jumpcloud"
|
JumpcloudSAML2Provider
|
python
|
dask__dask
|
dask/array/core.py
|
{
"start": 3199,
"end": 44342
}
|
class ____(Warning):
"""A warning given when bad chunking may cause poor performance"""
def getter(a, b, asarray=True, lock=None):
if isinstance(b, tuple) and any(x is None for x in b):
b2 = tuple(x for x in b if x is not None)
b3 = tuple(
None if x is None else slice(None, None)
for x in b
if not isinstance(x, Integral)
)
return getter(a, b2, asarray=asarray, lock=lock)[b3]
if lock:
lock.acquire()
try:
c = a[b]
# Below we special-case `np.matrix` to force a conversion to
# `np.ndarray` and preserve original Dask behavior for `getter`,
# as for all purposes `np.matrix` is array-like and thus
# `is_arraylike` evaluates to `True` in that case.
if asarray and (not is_arraylike(c) or isinstance(c, np.matrix)):
c = np.asarray(c)
finally:
if lock:
lock.release()
return c
def getter_nofancy(a, b, asarray=True, lock=None):
"""A simple wrapper around ``getter``.
Used to indicate to the optimization passes that the backend doesn't
support fancy indexing.
"""
return getter(a, b, asarray=asarray, lock=lock)
def getter_inline(a, b, asarray=True, lock=None):
"""A getter function that optimizations feel comfortable inlining
Slicing operations with this function may be inlined into a graph, such as
in the following rewrite
**Before**
>>> a = x[:10] # doctest: +SKIP
>>> b = a + 1 # doctest: +SKIP
>>> c = a * 2 # doctest: +SKIP
**After**
>>> b = x[:10] + 1 # doctest: +SKIP
>>> c = x[:10] * 2 # doctest: +SKIP
This inlining can be relevant to operations when running off of disk.
"""
return getter(a, b, asarray=asarray, lock=lock)
from dask.array.optimization import fuse_slice, optimize
# __array_function__ dict for mapping aliases and mismatching names
_HANDLED_FUNCTIONS = {}
def implements(*numpy_functions):
"""Register an __array_function__ implementation for dask.array.Array
Register that a function implements the API of a NumPy function (or several
NumPy functions in case of aliases) which is handled with
``__array_function__``.
Parameters
----------
\\*numpy_functions : callables
One or more NumPy functions that are handled by ``__array_function__``
and will be mapped by `implements` to a `dask.array` function.
"""
def decorator(dask_func):
for numpy_function in numpy_functions:
_HANDLED_FUNCTIONS[numpy_function] = dask_func
return dask_func
return decorator
def _should_delegate(self, other) -> bool:
"""Check whether Dask should delegate to the other.
This implementation follows NEP-13:
https://numpy.org/neps/nep-0013-ufunc-overrides.html#behavior-in-combination-with-python-s-binary-operations
"""
if hasattr(other, "__array_ufunc__") and other.__array_ufunc__ is None:
return True
elif (
hasattr(other, "__array_ufunc__")
and not is_valid_array_chunk(other)
# don't delegate to our own parent classes
and not isinstance(self, type(other))
and type(self) is not type(other)
):
return True
elif (
not hasattr(other, "__array_ufunc__")
and hasattr(other, "__array_priority__")
and other.__array_priority__ > self.__array_priority__
):
return True
return False
def check_if_handled_given_other(f):
"""Check if method is handled by Dask given type of other
Ensures proper deferral to upcast types in dunder operations without
assuming unknown types are automatically downcast types.
"""
@wraps(f)
def wrapper(self, other):
if _should_delegate(self, other):
return NotImplemented
else:
return f(self, other)
return wrapper
def slices_from_chunks(chunks):
"""Translate chunks tuple to a set of slices in product order
>>> slices_from_chunks(((2, 2), (3, 3, 3))) # doctest: +NORMALIZE_WHITESPACE
[(slice(0, 2, None), slice(0, 3, None)),
(slice(0, 2, None), slice(3, 6, None)),
(slice(0, 2, None), slice(6, 9, None)),
(slice(2, 4, None), slice(0, 3, None)),
(slice(2, 4, None), slice(3, 6, None)),
(slice(2, 4, None), slice(6, 9, None))]
"""
cumdims = [cached_cumsum(bds, initial_zero=True) for bds in chunks]
slices = [
[slice(s, s + dim) for s, dim in zip(starts, shapes)]
for starts, shapes in zip(cumdims, chunks)
]
return list(product(*slices))
def graph_from_arraylike(
arr, # Any array-like which supports slicing
chunks,
shape,
name,
getitem=getter,
lock=False,
asarray=True,
dtype=None,
inline_array=False,
) -> HighLevelGraph:
"""
HighLevelGraph for slicing chunks from an array-like according to a chunk pattern.
If ``inline_array`` is True, this make a Blockwise layer of slicing tasks where the
array-like is embedded into every task.,
If ``inline_array`` is False, this inserts the array-like as a standalone value in
a MaterializedLayer, then generates a Blockwise layer of slicing tasks that refer
to it.
>>> dict(graph_from_arraylike(arr, chunks=(2, 3), shape=(4, 6), name="X", inline_array=True)) # doctest: +SKIP
{(arr, 0, 0): (getter, arr, (slice(0, 2), slice(0, 3))),
(arr, 1, 0): (getter, arr, (slice(2, 4), slice(0, 3))),
(arr, 1, 1): (getter, arr, (slice(2, 4), slice(3, 6))),
(arr, 0, 1): (getter, arr, (slice(0, 2), slice(3, 6)))}
>>> dict( # doctest: +SKIP
graph_from_arraylike(arr, chunks=((2, 2), (3, 3)), shape=(4,6), name="X", inline_array=False)
)
{"original-X": arr,
('X', 0, 0): (getter, 'original-X', (slice(0, 2), slice(0, 3))),
('X', 1, 0): (getter, 'original-X', (slice(2, 4), slice(0, 3))),
('X', 1, 1): (getter, 'original-X', (slice(2, 4), slice(3, 6))),
('X', 0, 1): (getter, 'original-X', (slice(0, 2), slice(3, 6)))}
"""
chunks = normalize_chunks(chunks, shape, dtype=dtype)
out_ind = tuple(range(len(shape)))
if (
has_keyword(getitem, "asarray")
and has_keyword(getitem, "lock")
and (not asarray or lock)
):
kwargs = {"asarray": asarray, "lock": lock}
else:
# Common case, drop extra parameters
kwargs = {}
if inline_array:
layer = core_blockwise(
getitem,
name,
out_ind,
arr,
None,
ArraySliceDep(chunks),
out_ind,
numblocks={},
_data_producer=True,
**kwargs,
)
return HighLevelGraph.from_collections(name, layer)
else:
original_name = f"original-{name}"
layers = {}
layers[original_name] = MaterializedLayer({original_name: arr})
layers[name] = core_blockwise(
getitem,
name,
out_ind,
TaskRef(original_name),
None,
ArraySliceDep(chunks),
out_ind,
numblocks={},
_data_producer=True,
**kwargs,
)
deps = {
original_name: set(),
name: {original_name},
}
return HighLevelGraph(layers, deps)
def dotmany(A, B, leftfunc=None, rightfunc=None, **kwargs):
"""Dot product of many aligned chunks
>>> x = np.array([[1, 2], [1, 2]])
>>> y = np.array([[10, 20], [10, 20]])
>>> dotmany([x, x, x], [y, y, y])
array([[ 90, 180],
[ 90, 180]])
Optionally pass in functions to apply to the left and right chunks
>>> dotmany([x, x, x], [y, y, y], rightfunc=np.transpose)
array([[150, 150],
[150, 150]])
"""
if leftfunc:
A = map(leftfunc, A)
if rightfunc:
B = map(rightfunc, B)
return sum(map(partial(np.dot, **kwargs), A, B))
def _concatenate2(arrays, axes=None):
"""Recursively concatenate nested lists of arrays along axes
Each entry in axes corresponds to each level of the nested list. The
length of axes should correspond to the level of nesting of arrays.
If axes is an empty list or tuple, return arrays, or arrays[0] if
arrays is a list.
>>> x = np.array([[1, 2], [3, 4]])
>>> _concatenate2([x, x], axes=[0])
array([[1, 2],
[3, 4],
[1, 2],
[3, 4]])
>>> _concatenate2([x, x], axes=[1])
array([[1, 2, 1, 2],
[3, 4, 3, 4]])
>>> _concatenate2([[x, x], [x, x]], axes=[0, 1])
array([[1, 2, 1, 2],
[3, 4, 3, 4],
[1, 2, 1, 2],
[3, 4, 3, 4]])
Supports Iterators
>>> _concatenate2(iter([x, x]), axes=[1])
array([[1, 2, 1, 2],
[3, 4, 3, 4]])
Special Case
>>> _concatenate2([x, x], axes=())
array([[1, 2],
[3, 4]])
"""
if axes is None:
axes = []
if axes == ():
if isinstance(arrays, list):
return arrays[0]
else:
return arrays
if isinstance(arrays, Iterator):
arrays = list(arrays)
if not isinstance(arrays, (list, tuple)):
return arrays
if len(axes) > 1:
arrays = [_concatenate2(a, axes=axes[1:]) for a in arrays]
concatenate = concatenate_lookup.dispatch(
type(max(arrays, key=lambda x: getattr(x, "__array_priority__", 0)))
)
if isinstance(arrays[0], dict):
# Handle concatenation of `dict`s, used as a replacement for structured
# arrays when that's not supported by the array library (e.g., CuPy).
keys = list(arrays[0].keys())
assert all(list(a.keys()) == keys for a in arrays)
ret = dict()
for k in keys:
ret[k] = concatenate(list(a[k] for a in arrays), axis=axes[0])
return ret
else:
return concatenate(arrays, axis=axes[0])
def apply_infer_dtype(func, args, kwargs, funcname, suggest_dtype="dtype", nout=None):
"""
Tries to infer output dtype of ``func`` for a small set of input arguments.
Parameters
----------
func: Callable
Function for which output dtype is to be determined
args: List of array like
Arguments to the function, which would usually be used. Only attributes
``ndim`` and ``dtype`` are used.
kwargs: dict
Additional ``kwargs`` to the ``func``
funcname: String
Name of calling function to improve potential error messages
suggest_dtype: None/False or String
If not ``None`` adds suggestion to potential error message to specify a dtype
via the specified kwarg. Defaults to ``'dtype'``.
nout: None or Int
``None`` if function returns single output, integer if many.
Defaults to ``None``.
Returns
-------
: dtype or List of dtype
One or many dtypes (depending on ``nout``)
"""
from dask.array.utils import meta_from_array
# make sure that every arg is an evaluated array
args = [
(
np.zeros_like(meta_from_array(x), shape=((1,) * x.ndim), dtype=x.dtype)
if is_arraylike(x)
else x
)
for x in args
]
try:
with np.errstate(all="ignore"):
o = func(*args, **kwargs)
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
tb = "".join(traceback.format_tb(exc_traceback))
suggest = (
(
f"Please specify the dtype explicitly using the `{suggest_dtype}` kwarg.\n\n"
)
if suggest_dtype
else ""
)
msg = (
f"`dtype` inference failed in `{funcname}`.\n\n"
f"{suggest}"
"Original error is below:\n"
"------------------------\n"
f"{e!r}\n\n"
"Traceback:\n"
"---------\n"
f"{tb}"
)
else:
msg = None
if msg is not None:
raise ValueError(msg)
return getattr(o, "dtype", type(o)) if nout is None else tuple(e.dtype for e in o)
def normalize_arg(x):
"""Normalize user provided arguments to blockwise or map_blocks
We do a few things:
1. If they are string literals that might collide with blockwise_token then we
quote them
2. IF they are large (as defined by sizeof) then we put them into the
graph on their own by using dask.delayed
"""
if is_dask_collection(x):
return x
elif isinstance(x, str) and re.match(r"_\d+", x):
return delayed(x)
elif isinstance(x, list) and len(x) >= 10:
return delayed(x)
elif sizeof(x) > 1e6:
return delayed(x)
else:
return x
def _pass_extra_kwargs(func, keys, *args, **kwargs):
"""Helper for :func:`dask.array.map_blocks` to pass `block_info` or `block_id`.
For each element of `keys`, a corresponding element of args is changed
to a keyword argument with that key, before all arguments re passed on
to `func`.
"""
kwargs.update(zip(keys, args))
return func(*args[len(keys) :], **kwargs)
def map_blocks(
func,
*args,
name=None,
token=None,
dtype=None,
chunks=None,
drop_axis=None,
new_axis=None,
enforce_ndim=False,
meta=None,
**kwargs,
):
"""Map a function across all blocks of a dask array.
Note that ``map_blocks`` will attempt to automatically determine the output
array type by calling ``func`` on 0-d versions of the inputs. Please refer to
the ``meta`` keyword argument below if you expect that the function will not
succeed when operating on 0-d arrays.
Parameters
----------
func : callable
Function to apply to every block in the array.
If ``func`` accepts ``block_info=`` or ``block_id=``
as keyword arguments, these will be passed dictionaries
containing information about input and output chunks/arrays
during computation. See examples for details.
args : dask arrays or other objects
dtype : np.dtype, optional
The ``dtype`` of the output array. It is recommended to provide this.
If not provided, will be inferred by applying the function to a small
set of fake data.
chunks : tuple, optional
Chunk shape of resulting blocks if the function does not preserve
shape. If not provided, the resulting array is assumed to have the same
block structure as the first input array.
drop_axis : number or iterable, optional
Dimensions lost by the function.
new_axis : number or iterable, optional
New dimensions created by the function. Note that these are applied
after ``drop_axis`` (if present). The size of each chunk along this
dimension will be set to 1. Please specify ``chunks`` if the individual
chunks have a different size.
enforce_ndim : bool, default False
Whether to enforce at runtime that the dimensionality of the array
produced by ``func`` actually matches that of the array returned by
``map_blocks``.
If True, this will raise an error when there is a mismatch.
token : string, optional
The key prefix to use for the output array. If not provided, will be
determined from the function name.
name : string, optional
The key name to use for the output array. Note that this fully
specifies the output key name, and must be unique. If not provided,
will be determined by a hash of the arguments.
meta : array-like, optional
The ``meta`` of the output array, when specified is expected to be an
array of the same type and dtype of that returned when calling ``.compute()``
on the array returned by this function. When not provided, ``meta`` will be
inferred by applying the function to a small set of fake data, usually a
0-d array. It's important to ensure that ``func`` can successfully complete
computation without raising exceptions when 0-d is passed to it, providing
``meta`` will be required otherwise. If the output type is known beforehand
(e.g., ``np.ndarray``, ``cupy.ndarray``), an empty array of such type dtype
can be passed, for example: ``meta=np.array((), dtype=np.int32)``.
**kwargs :
Other keyword arguments to pass to function. Values must be constants
(not dask.arrays)
See Also
--------
dask.array.map_overlap : Generalized operation with overlap between neighbors.
dask.array.blockwise : Generalized operation with control over block alignment.
Examples
--------
>>> import dask.array as da
>>> x = da.arange(6, chunks=3)
>>> x.map_blocks(lambda x: x * 2).compute()
array([ 0, 2, 4, 6, 8, 10])
The ``da.map_blocks`` function can also accept multiple arrays.
>>> d = da.arange(5, chunks=2)
>>> e = da.arange(5, chunks=2)
>>> f = da.map_blocks(lambda a, b: a + b**2, d, e)
>>> f.compute()
array([ 0, 2, 6, 12, 20])
If the function changes shape of the blocks then you must provide chunks
explicitly.
>>> y = x.map_blocks(lambda x: x[::2], chunks=((2, 2),))
You have a bit of freedom in specifying chunks. If all of the output chunk
sizes are the same, you can provide just that chunk size as a single tuple.
>>> a = da.arange(18, chunks=(6,))
>>> b = a.map_blocks(lambda x: x[:3], chunks=(3,))
If the function changes the dimension of the blocks you must specify the
created or destroyed dimensions.
>>> b = a.map_blocks(lambda x: x[None, :, None], chunks=(1, 6, 1),
... new_axis=[0, 2])
If ``chunks`` is specified but ``new_axis`` is not, then it is inferred to
add the necessary number of axes on the left.
Note that ``map_blocks()`` will concatenate chunks along axes specified by
the keyword parameter ``drop_axis`` prior to applying the function.
This is illustrated in the figure below:
.. image:: /images/map_blocks_drop_axis.png
Due to memory-size-constraints, it is often not advisable to use ``drop_axis``
on an axis that is chunked. In that case, it is better not to use
``map_blocks`` but rather
``dask.array.reduction(..., axis=dropped_axes, concatenate=False)`` which
maintains a leaner memory footprint while it drops any axis.
Map_blocks aligns blocks by block positions without regard to shape. In the
following example we have two arrays with the same number of blocks but
with different shape and chunk sizes.
>>> x = da.arange(1000, chunks=(100,))
>>> y = da.arange(100, chunks=(10,))
The relevant attribute to match is numblocks.
>>> x.numblocks
(10,)
>>> y.numblocks
(10,)
If these match (up to broadcasting rules) then we can map arbitrary
functions across blocks
>>> def func(a, b):
... return np.array([a.max(), b.max()])
>>> da.map_blocks(func, x, y, chunks=(2,), dtype='i8')
dask.array<func, shape=(20,), dtype=int64, chunksize=(2,), chunktype=numpy.ndarray>
>>> _.compute()
array([ 99, 9, 199, 19, 299, 29, 399, 39, 499, 49, 599, 59, 699,
69, 799, 79, 899, 89, 999, 99])
Your block function can get information about where it is in the array by
accepting a special ``block_info`` or ``block_id`` keyword argument.
During computation, they will contain information about each of the input
and output chunks (and dask arrays) relevant to each call of ``func``.
>>> def func(block_info=None):
... pass
This will receive the following information:
>>> block_info # doctest: +SKIP
{0: {'shape': (1000,),
'num-chunks': (10,),
'chunk-location': (4,),
'array-location': [(400, 500)]},
None: {'shape': (1000,),
'num-chunks': (10,),
'chunk-location': (4,),
'array-location': [(400, 500)],
'chunk-shape': (100,),
'dtype': dtype('float64')}}
The keys to the ``block_info`` dictionary indicate which is the input and
output Dask array:
- **Input Dask array(s):** ``block_info[0]`` refers to the first input Dask array.
The dictionary key is ``0`` because that is the argument index corresponding
to the first input Dask array.
In cases where multiple Dask arrays have been passed as input to the function,
you can access them with the number corresponding to the input argument,
eg: ``block_info[1]``, ``block_info[2]``, etc.
(Note that if you pass multiple Dask arrays as input to map_blocks,
the arrays must match each other by having matching numbers of chunks,
along corresponding dimensions up to broadcasting rules.)
- **Output Dask array:** ``block_info[None]`` refers to the output Dask array,
and contains information about the output chunks.
The output chunk shape and dtype may may be different than the input chunks.
For each dask array, ``block_info`` describes:
- ``shape``: the shape of the full Dask array,
- ``num-chunks``: the number of chunks of the full array in each dimension,
- ``chunk-location``: the chunk location (for example the fourth chunk over
in the first dimension), and
- ``array-location``: the array location within the full Dask array
(for example the slice corresponding to ``40:50``).
In addition to these, there are two extra parameters described by
``block_info`` for the output array (in ``block_info[None]``):
- ``chunk-shape``: the output chunk shape, and
- ``dtype``: the output dtype.
These features can be combined to synthesize an array from scratch, for
example:
>>> def func(block_info=None):
... loc = block_info[None]['array-location'][0]
... return np.arange(loc[0], loc[1])
>>> da.map_blocks(func, chunks=((4, 4),), dtype=np.float64)
dask.array<func, shape=(8,), dtype=float64, chunksize=(4,), chunktype=numpy.ndarray>
>>> _.compute()
array([0, 1, 2, 3, 4, 5, 6, 7])
``block_id`` is similar to ``block_info`` but contains only the ``chunk_location``:
>>> def func(block_id=None):
... pass
This will receive the following information:
>>> block_id # doctest: +SKIP
(4, 3)
You may specify the key name prefix of the resulting task in the graph with
the optional ``token`` keyword argument.
>>> x.map_blocks(lambda x: x + 1, name='increment')
dask.array<increment, shape=(1000,), dtype=int64, chunksize=(100,), chunktype=numpy.ndarray>
For functions that may not handle 0-d arrays, it's also possible to specify
``meta`` with an empty array matching the type of the expected result. In
the example below, ``func`` will result in an ``IndexError`` when computing
``meta``:
>>> rng = da.random.default_rng()
>>> da.map_blocks(lambda x: x[2], rng.random(5), meta=np.array(()))
dask.array<lambda, shape=(5,), dtype=float64, chunksize=(5,), chunktype=numpy.ndarray>
Similarly, it's possible to specify a non-NumPy array to ``meta``, and provide
a ``dtype``:
>>> import cupy # doctest: +SKIP
>>> rng = da.random.default_rng(cupy.random.default_rng()) # doctest: +SKIP
>>> dt = np.float32
>>> da.map_blocks(lambda x: x[2], rng.random(5, dtype=dt), meta=cupy.array((), dtype=dt)) # doctest: +SKIP
dask.array<lambda, shape=(5,), dtype=float32, chunksize=(5,), chunktype=cupy.ndarray>
"""
if drop_axis is None:
drop_axis = []
if not callable(func):
msg = (
"First argument must be callable function, not %s\n"
"Usage: da.map_blocks(function, x)\n"
" or: da.map_blocks(function, x, y, z)"
)
raise TypeError(msg % type(func).__name__)
token = f"{token or funcname(func)}"
new_axes = {}
if isinstance(drop_axis, Number):
drop_axis = [drop_axis]
if isinstance(new_axis, Number):
new_axis = [new_axis] # TODO: handle new_axis
arrs = [a for a in args if isinstance(a, Array)]
argpairs = []
for a in args:
if isinstance(a, Array):
argpairs.append((a, tuple(range(a.ndim))[::-1]))
elif isinstance(a, BlockwiseDep):
argpairs.append((a, tuple(range(args[0].ndim))[::-1]))
else:
argpairs.append((a, None))
if arrs:
out_ind = tuple(range(max(a.ndim for a in arrs)))[::-1]
else:
out_ind = ()
original_kwargs = kwargs
if dtype is None and meta is None:
try:
meta = compute_meta(func, dtype, *args, **kwargs)
except Exception:
pass
dtype = apply_infer_dtype(func, args, original_kwargs, "map_blocks")
if drop_axis:
ndim_out = len(out_ind)
if any(i < -ndim_out or i >= ndim_out for i in drop_axis):
raise ValueError(
f"drop_axis out of range (drop_axis={drop_axis}, "
f"but output is {ndim_out}d)."
)
drop_axis = [i % ndim_out for i in drop_axis]
out_ind = tuple(x for i, x in enumerate(out_ind) if i not in drop_axis)
if new_axis is None and chunks is not None and len(out_ind) < len(chunks):
new_axis = range(len(chunks) - len(out_ind))
if new_axis:
# new_axis = [x + len(drop_axis) for x in new_axis]
out_ind = list(out_ind)
for ax in sorted(new_axis):
n = len(out_ind) + len(drop_axis)
out_ind.insert(ax, n)
if chunks is not None:
new_axes[n] = chunks[ax]
else:
new_axes[n] = 1
out_ind = tuple(out_ind)
if max(new_axis) > max(out_ind):
raise ValueError("New_axis values do not fill in all dimensions")
if chunks is not None:
if len(chunks) != len(out_ind):
raise ValueError(
f"Provided chunks have {len(chunks)} dims; expected {len(out_ind)} dims"
)
adjust_chunks = dict(zip(out_ind, chunks))
else:
adjust_chunks = None
if enforce_ndim:
out = blockwise(
apply_and_enforce,
out_ind,
*concat(argpairs),
expected_ndim=len(out_ind),
_func=func,
name=name,
token=token,
new_axes=new_axes,
dtype=dtype,
concatenate=True,
align_arrays=False,
adjust_chunks=adjust_chunks,
meta=meta,
**kwargs,
)
else:
out = blockwise(
func,
out_ind,
*concat(argpairs),
name=name,
token=token,
new_axes=new_axes,
dtype=dtype,
concatenate=True,
align_arrays=False,
adjust_chunks=adjust_chunks,
meta=meta,
**kwargs,
)
extra_argpairs = []
extra_names = []
# If func has block_id as an argument, construct an object to inject it.
if has_keyword(func, "block_id"):
extra_argpairs.append((ArrayBlockIdDep(out.chunks), out_ind))
extra_names.append("block_id")
if has_keyword(func, "_overlap_trim_info"):
# Internal for map overlap to reduce size of graph
num_chunks = out.numblocks
block_id_dict = {
block_id: (block_id, num_chunks)
for block_id in product(*(range(len(c)) for c in out.chunks))
}
extra_argpairs.append((ArrayValuesDep(out.chunks, block_id_dict), out_ind))
extra_names.append("_overlap_trim_info")
# If func has block_info as an argument, construct a dict of block info
# objects and prepare to inject it.
if has_keyword(func, "block_info"):
starts = {}
num_chunks = {}
shapes = {}
for i, (arg, in_ind) in enumerate(argpairs):
if in_ind is not None:
shapes[i] = arg.shape
if drop_axis:
# We concatenate along dropped axes, so we need to treat them
# as if there is only a single chunk.
starts[i] = [
(
cached_cumsum(arg.chunks[j], initial_zero=True)
if ind in out_ind
else [0, arg.shape[j]]
)
for j, ind in enumerate(in_ind)
]
num_chunks[i] = tuple(len(s) - 1 for s in starts[i])
else:
starts[i] = [
cached_cumsum(c, initial_zero=True) for c in arg.chunks
]
num_chunks[i] = arg.numblocks
out_starts = [cached_cumsum(c, initial_zero=True) for c in out.chunks]
block_info_dict = {}
for block_id in product(*(range(len(c)) for c in out.chunks)):
# Get position of chunk, indexed by axis labels
location = {out_ind[i]: loc for i, loc in enumerate(block_id)}
info = {}
for i, shape in shapes.items():
# Compute chunk key in the array, taking broadcasting into
# account. We don't directly know which dimensions are
# broadcast, but any dimension with only one chunk can be
# treated as broadcast.
arr_k = tuple(
location.get(ind, 0) if num_chunks[i][j] > 1 else 0
for j, ind in enumerate(argpairs[i][1])
)
info[i] = {
"shape": shape,
"num-chunks": num_chunks[i],
"array-location": [
(starts[i][ij][j], starts[i][ij][j + 1])
for ij, j in enumerate(arr_k)
],
"chunk-location": arr_k,
}
info[None] = {
"shape": out.shape,
"num-chunks": out.numblocks,
"array-location": [
(out_starts[ij][j], out_starts[ij][j + 1])
for ij, j in enumerate(block_id)
],
"chunk-location": block_id,
"chunk-shape": tuple(
out.chunks[ij][j] for ij, j in enumerate(block_id)
),
"dtype": dtype,
}
block_info_dict[block_id] = info
extra_argpairs.append((ArrayValuesDep(out.chunks, block_info_dict), out_ind))
extra_names.append("block_info")
if extra_argpairs:
# Rewrite the Blockwise layer. It would be nice to find a way to
# avoid doing it twice, but it's currently needed to determine
# out.chunks from the first pass. Since it constructs a Blockwise
# rather than an expanded graph, it shouldn't be too expensive.
out = blockwise(
_pass_extra_kwargs,
out_ind,
func,
None,
tuple(extra_names),
None,
*concat(extra_argpairs),
*concat(argpairs),
name=out.name,
dtype=out.dtype,
concatenate=True,
align_arrays=False,
adjust_chunks=dict(zip(out_ind, out.chunks)),
meta=meta,
**kwargs,
)
return out
def apply_and_enforce(*args, **kwargs):
"""Apply a function, and enforce the output.ndim to match expected_ndim
Ensures the output has the expected dimensionality."""
func = kwargs.pop("_func")
expected_ndim = kwargs.pop("expected_ndim")
out = func(*args, **kwargs)
if getattr(out, "ndim", 0) != expected_ndim:
out_ndim = getattr(out, "ndim", 0)
raise ValueError(
f"Dimension mismatch: expected output of {func} "
f"to have dims = {expected_ndim}. Got {out_ndim} instead."
)
return out
def broadcast_chunks(*chunkss):
"""Construct a chunks tuple that broadcasts many chunks tuples
>>> a = ((5, 5),)
>>> b = ((5, 5),)
>>> broadcast_chunks(a, b)
((5, 5),)
>>> a = ((10, 10, 10), (5, 5),)
>>> b = ((5, 5),)
>>> broadcast_chunks(a, b)
((10, 10, 10), (5, 5))
>>> a = ((10, 10, 10), (5, 5),)
>>> b = ((1,), (5, 5),)
>>> broadcast_chunks(a, b)
((10, 10, 10), (5, 5))
>>> a = ((10, 10, 10), (5, 5),)
>>> b = ((3, 3,), (5, 5),)
>>> broadcast_chunks(a, b)
Traceback (most recent call last):
...
ValueError: Chunks do not align: [(10, 10, 10), (3, 3)]
"""
if not chunkss:
return ()
elif len(chunkss) == 1:
return chunkss[0]
n = max(map(len, chunkss))
chunkss2 = [((1,),) * (n - len(c)) + c for c in chunkss]
result = []
for i in range(n):
step1 = [c[i] for c in chunkss2]
if all(c == (1,) for c in step1):
step2 = step1
else:
step2 = [c for c in step1 if c != (1,)]
if len(set(step2)) != 1:
raise ValueError(f"Chunks do not align: {step2}")
result.append(step2[0])
return tuple(result)
def store(
sources: Array | Collection[Array],
targets: ArrayLike | Delayed | Collection[ArrayLike | Delayed],
lock: bool | Lock = True,
regions: tuple[slice, ...] | Collection[tuple[slice, ...]] | None = None,
compute: bool = True,
return_stored: bool = False,
load_stored: bool | None = None,
**kwargs,
):
"""Store dask arrays in array-like objects, overwrite data in target
This stores dask arrays into object that supports numpy-style setitem
indexing. It stores values chunk by chunk so that it does not have to
fill up memory. For best performance you can align the block size of
the storage target with the block size of your array.
If your data fits in memory then you may prefer calling
``np.array(myarray)`` instead.
Parameters
----------
sources: Array or collection of Arrays
targets: array-like or Delayed or collection of array-likes and/or Delayeds
These should support setitem syntax ``target[10:20] = ...``.
If sources is a single item, targets must be a single item; if sources is a
collection of arrays, targets must be a matching collection.
lock: boolean or threading.Lock, optional
Whether or not to lock the data stores while storing.
Pass True (lock each file individually), False (don't lock) or a
particular :class:`threading.Lock` object to be shared among all writes.
regions: tuple of slices or collection of tuples of slices, optional
Each ``region`` tuple in ``regions`` should be such that
``target[region].shape = source.shape``
for the corresponding source and target in sources and targets,
respectively. If this is a tuple, the contents will be assumed to be
slices, so do not provide a tuple of tuples.
compute: boolean, optional
If true compute immediately; return :class:`dask.delayed.Delayed` otherwise.
return_stored: boolean, optional
Optionally return the stored result (default False).
load_stored: boolean, optional
Optionally return the stored result, loaded in to memory (default None).
If None, ``load_stored`` is True if ``return_stored`` is True and
``compute`` is False. *This is an advanced option.*
When False, store will return the appropriate ``target`` for each chunk that is stored.
Directly computing this result is not what you want.
Instead, you can use the returned ``target`` to execute followup operations to the store.
kwargs:
Parameters passed to compute/persist (only used if compute=True)
Returns
-------
If return_stored=True
tuple of Arrays
If return_stored=False and compute=True
None
If return_stored=False and compute=False
Delayed
Examples
--------
>>> import h5py # doctest: +SKIP
>>> f = h5py.File('myfile.hdf5', mode='a') # doctest: +SKIP
>>> dset = f.create_dataset('/data', shape=x.shape,
... chunks=x.chunks,
... dtype='f8') # doctest: +SKIP
>>> store(x, dset) # doctest: +SKIP
Alternatively store many arrays at the same time
>>> store([x, y, z], [dset1, dset2, dset3]) # doctest: +SKIP
"""
if isinstance(sources, Array):
sources = [sources]
# There's no way to test that targets is a single array-like.
# We need to trust the user.
targets = [targets] # type: ignore[list-item]
targets = cast("Collection[ArrayLike | Delayed]", targets)
if any(not isinstance(s, Array) for s in sources):
raise ValueError("All sources must be dask array objects")
if len(sources) != len(targets):
raise ValueError(
f"Different number of sources [{len(sources)}] and targets [{len(targets)}]"
)
if isinstance(regions, tuple) or regions is None:
regions_list = [regions] * len(sources)
else:
regions_list = list(regions)
if len(sources) != len(regions_list):
raise ValueError(
f"Different number of sources [{len(sources)}] and "
f"targets [{len(targets)}] than regions [{len(regions_list)}]"
)
del regions
if load_stored is None:
load_stored = return_stored and not compute
if lock is True:
lock = get_scheduler_lock(collection=Array, scheduler=kwargs.get("scheduler"))
arrays = []
for s, t, r in zip(sources, targets, regions_list):
slices = ArraySliceDep(s.chunks)
arrays.append(
s.map_blocks(
load_store_chunk, # type: ignore[arg-type]
t,
# Note: slices / BlockwiseDep have to be passed by arg, not by kwarg
slices,
region=r,
lock=lock,
return_stored=return_stored,
load_stored=load_stored,
token="store-map",
meta=s._meta,
)
)
if compute:
if not return_stored:
import dask
dask.compute(arrays, **kwargs)
return None
else:
stored_persisted = persist(*arrays, **kwargs)
arrays = []
for s, r in zip(stored_persisted, regions_list):
slices = ArraySliceDep(s.chunks)
arrays.append(
s.map_blocks(
load_chunk, # type: ignore[arg-type]
# Note: slices / BlockwiseDep have to be passed by arg, not by kwarg
slices,
lock=lock,
region=r,
meta=s._meta,
)
)
if len(arrays) == 1:
return arrays[0]
return tuple(arrays)
def blockdims_from_blockshape(shape, chunks):
"""
>>> blockdims_from_blockshape((10, 10), (4, 3))
((4, 4, 2), (3, 3, 3, 1))
>>> blockdims_from_blockshape((10, 0), (4, 0))
((4, 4, 2), (0,))
"""
if chunks is None:
raise TypeError("Must supply chunks= keyword argument")
if shape is None:
raise TypeError("Must supply shape= keyword argument")
if np.isnan(sum(shape)) or np.isnan(sum(chunks)):
raise ValueError(
f"Array chunk sizes are unknown. shape: {shape}, chunks: {chunks}{unknown_chunk_message}"
)
if not all(map(is_integer, chunks)):
raise ValueError("chunks can only contain integers.")
if not all(map(is_integer, shape)):
raise ValueError("shape can only contain integers.")
shape = tuple(map(int, shape))
chunks = tuple(map(int, chunks))
return tuple(
((bd,) * (d // bd) + ((d % bd,) if d % bd else ()) if d else (0,))
for d, bd in zip(shape, chunks)
)
def finalize(results):
if not results:
return concatenate3(results)
results2 = results
while isinstance(results2, (tuple, list)):
if len(results2) > 1:
return concatenate3(results)
else:
results2 = results2[0]
results = unpack_singleton(results)
# Single chunk. There is a risk that the result holds a buffer stored in the
# graph or on a process-local Worker. Deep copy to make sure that nothing can
# accidentally write back to it.
try:
return results.copy() # numpy, sparse, scipy.sparse (any version)
except AttributeError:
# Not an Array API object
return results
CHUNKS_NONE_ERROR_MESSAGE = """
You must specify a chunks= keyword argument.
This specifies the chunksize of your array blocks.
See the following documentation page for details:
https://docs.dask.org/en/latest/array-creation.html#chunks
""".strip()
|
PerformanceWarning
|
python
|
apache__airflow
|
providers/google/src/airflow/providers/google/cloud/hooks/dataproc.py
|
{
"start": 2441,
"end": 7148
}
|
class ____:
"""A helper class for building Dataproc job."""
def __init__(
self,
project_id: str,
task_id: str,
cluster_name: str,
job_type: str,
properties: dict[str, str] | None = None,
) -> None:
name = f"{task_id.replace('.', '_')}_{uuid.uuid4()!s:.8}"
self.job_type = job_type
self.job: dict[str, Any] = {
"job": {
"reference": {"project_id": project_id, "job_id": name},
"placement": {"cluster_name": cluster_name},
"labels": {"airflow-version": "v" + airflow_version.replace(".", "-").replace("+", "-")},
job_type: {},
}
}
if properties is not None:
self.job["job"][job_type]["properties"] = properties
def add_labels(self, labels: dict | None = None) -> None:
"""
Set labels for Dataproc job.
:param labels: Labels for the job query.
"""
if labels:
self.job["job"]["labels"].update(labels)
def add_variables(self, variables: dict | None = None) -> None:
"""
Set variables for Dataproc job.
:param variables: Variables for the job query.
"""
if variables is not None:
self.job["job"][self.job_type]["script_variables"] = variables
def add_args(self, args: list[str] | None = None) -> None:
"""
Set args for Dataproc job.
:param args: Args for the job query.
"""
if args is not None:
self.job["job"][self.job_type]["args"] = args
def add_query(self, query: str | list[str]) -> None:
"""
Add query for Dataproc job.
:param query: query for the job.
"""
queries = self.job["job"][self.job_type].setdefault("query_list", {"queries": []})["queries"]
if isinstance(query, str):
queries.append(query)
elif isinstance(query, list):
queries.extend(query)
def add_query_uri(self, query_uri: str) -> None:
"""
Set query uri for Dataproc job.
:param query_uri: URI for the job query.
"""
self.job["job"][self.job_type]["query_file_uri"] = query_uri
def add_jar_file_uris(self, jars: list[str] | None = None) -> None:
"""
Set jars uris for Dataproc job.
:param jars: List of jars URIs
"""
if jars is not None:
self.job["job"][self.job_type]["jar_file_uris"] = jars
def add_archive_uris(self, archives: list[str] | None = None) -> None:
"""
Set archives uris for Dataproc job.
:param archives: List of archives URIs
"""
if archives is not None:
self.job["job"][self.job_type]["archive_uris"] = archives
def add_file_uris(self, files: list[str] | None = None) -> None:
"""
Set file uris for Dataproc job.
:param files: List of files URIs
"""
if files is not None:
self.job["job"][self.job_type]["file_uris"] = files
def add_python_file_uris(self, pyfiles: list[str] | None = None) -> None:
"""
Set python file uris for Dataproc job.
:param pyfiles: List of python files URIs
"""
if pyfiles is not None:
self.job["job"][self.job_type]["python_file_uris"] = pyfiles
def set_main(self, main_jar: str | None = None, main_class: str | None = None) -> None:
"""
Set Dataproc main class.
:param main_jar: URI for the main file.
:param main_class: Name of the main class.
:raises: ValueError
"""
if main_class is not None and main_jar is not None:
raise ValueError("Set either main_jar or main_class")
if main_jar:
self.job["job"][self.job_type]["main_jar_file_uri"] = main_jar
else:
self.job["job"][self.job_type]["main_class"] = main_class
def set_python_main(self, main: str) -> None:
"""
Set Dataproc main python file uri.
:param main: URI for the python main file.
"""
self.job["job"][self.job_type]["main_python_file_uri"] = main
def set_job_name(self, name: str) -> None:
"""
Set Dataproc job name.
Job name is sanitized, replacing dots by underscores.
:param name: Job name.
"""
sanitized_name = f"{name.replace('.', '_')}_{uuid.uuid4()!s:.8}"
self.job["job"]["reference"]["job_id"] = sanitized_name
def build(self) -> dict:
"""
Return Dataproc job.
:return: Dataproc job
"""
return self.job
|
DataProcJobBuilder
|
python
|
jmcnamara__XlsxWriter
|
xlsxwriter/test/comparison/test_chart_bar04.py
|
{
"start": 315,
"end": 2165
}
|
class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_bar04.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()
chart1 = workbook.add_chart({"type": "bar"})
chart2 = workbook.add_chart({"type": "bar"})
chart1.axis_ids = [64446848, 64448384]
chart2.axis_ids = [85389696, 85391232]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet1.write_column("A1", data[0])
worksheet1.write_column("B1", data[1])
worksheet1.write_column("C1", data[2])
chart1.add_series(
{
"categories": "=Sheet1!$A$1:$A$5",
"values": "=Sheet1!$B$1:$B$5",
}
)
chart1.add_series(
{
"categories": "=Sheet1!$A$1:$A$5",
"values": "=Sheet1!$C$1:$C$5",
}
)
worksheet1.insert_chart("E9", chart1)
worksheet2.write_column("A1", data[0])
worksheet2.write_column("B1", data[1])
worksheet2.write_column("C1", data[2])
chart2.add_series(
{
"categories": "=Sheet2!$A$1:$A$5",
"values": "=Sheet2!$B$1:$B$5",
}
)
chart2.add_series(
{
"categories": "=Sheet2!$A$1:$A$5",
"values": "=Sheet2!$C$1:$C$5",
}
)
worksheet2.insert_chart("E9", chart2)
workbook.close()
self.assertExcelEqual()
|
TestCompareXLSXFiles
|
python
|
mlflow__mlflow
|
mlflow/system_metrics/metrics/base_metrics_monitor.py
|
{
"start": 94,
"end": 780
}
|
class ____(abc.ABC):
"""Base class of system metrics monitor."""
def __init__(self):
self._metrics = defaultdict(list)
@abc.abstractmethod
def collect_metrics(self):
"""Method to collect metrics.
Subclass should implement this method to collect metrics and store in `self._metrics`.
"""
@abc.abstractmethod
def aggregate_metrics(self):
"""Method to aggregate metrics.
Subclass should implement this method to aggregate the metrics and return it in a dict.
"""
@property
def metrics(self):
return self._metrics
def clear_metrics(self):
self._metrics.clear()
|
BaseMetricsMonitor
|
python
|
apache__airflow
|
airflow-core/tests/unit/ti_deps/deps/test_pool_slots_available_dep.py
|
{
"start": 1229,
"end": 3039
}
|
class ____:
def setup_method(self):
db.clear_db_pools()
with create_session() as session:
test_pool = Pool(pool="test_pool", include_deferred=False)
test_includes_deferred_pool = Pool(pool="test_includes_deferred_pool", include_deferred=True)
session.add_all([test_pool, test_includes_deferred_pool])
session.commit()
def teardown_method(self):
db.clear_db_pools()
@patch("airflow.models.Pool.open_slots", return_value=0)
def test_pooled_task_reached_concurrency(self, mock_open_slots):
ti = Mock(pool="test_pool", pool_slots=1)
assert not PoolSlotsAvailableDep().is_met(ti=ti)
@patch("airflow.models.Pool.open_slots", return_value=1)
def test_pooled_task_pass(self, mock_open_slots):
ti = Mock(pool="test_pool", pool_slots=1)
assert PoolSlotsAvailableDep().is_met(ti=ti)
@patch("airflow.models.Pool.open_slots", return_value=0)
def test_running_pooled_task_pass(self, mock_open_slots):
for state in EXECUTION_STATES:
ti = Mock(pool="test_pool", state=state, pool_slots=1)
assert PoolSlotsAvailableDep().is_met(ti=ti)
@patch("airflow.models.Pool.open_slots", return_value=0)
def test_deferred_pooled_task_pass(self, mock_open_slots):
ti = Mock(pool="test_includes_deferred_pool", state=TaskInstanceState.DEFERRED, pool_slots=1)
assert PoolSlotsAvailableDep().is_met(ti=ti)
ti_to_fail = Mock(pool="test_pool", state=TaskInstanceState.DEFERRED, pool_slots=1)
assert not PoolSlotsAvailableDep().is_met(ti=ti_to_fail)
def test_task_with_nonexistent_pool(self):
ti = Mock(pool="nonexistent_pool", pool_slots=1)
assert not PoolSlotsAvailableDep().is_met(ti=ti)
|
TestPoolSlotsAvailableDep
|
python
|
cherrypy__cherrypy
|
cherrypy/process/plugins.py
|
{
"start": 8186,
"end": 12151
}
|
class ____(SimplePlugin):
"""Drop privileges. uid/gid arguments not available on Windows.
Special thanks to `Gavin Baker
<http://antonym.org/2005/12/dropping-privileges-in-python.html>`_.
"""
def __init__(self, bus, umask=None, uid=None, gid=None):
"""Initialize the privilege dropping plugin."""
SimplePlugin.__init__(self, bus)
self.finalized = False
self.uid = uid
self.gid = gid
self.umask = umask
@property
def uid(self):
"""The uid under which to run.
Availability: Unix.
"""
return self._uid
@uid.setter
def uid(self, val):
if val is not None:
if pwd is None:
self.bus.log(
'pwd module not available; ignoring uid.',
level=30,
)
val = None
elif isinstance(val, text_or_bytes):
val = pwd.getpwnam(val)[2]
self._uid = val
@property
def gid(self):
"""The gid under which to run.
Availability: Unix.
"""
return self._gid
@gid.setter
def gid(self, val):
if val is not None:
if grp is None:
self.bus.log(
'grp module not available; ignoring gid.',
level=30,
)
val = None
elif isinstance(val, text_or_bytes):
val = grp.getgrnam(val)[2]
self._gid = val
@property
def umask(self):
"""The default permission mode for newly created files and directories.
Usually expressed in octal format, for example, ``0644``.
Availability: Unix, Windows.
"""
return self._umask
@umask.setter
def umask(self, val):
if val is not None:
try:
os.umask
except AttributeError:
self.bus.log(
'umask function not available; ignoring umask.',
level=30,
)
val = None
self._umask = val
def start(self):
"""Drop the process privileges."""
# uid/gid
def current_ids():
"""Return the current (uid, gid) if available."""
name, group = None, None
if pwd:
name = pwd.getpwuid(os.getuid())[0]
if grp:
group = grp.getgrgid(os.getgid())[0]
return name, group
if self.finalized:
if not (self.uid is None and self.gid is None):
self.bus.log(
'Already running as uid: %r gid: %r' % current_ids(),
)
else:
if self.uid is None and self.gid is None:
if pwd or grp:
self.bus.log('uid/gid not set', level=30)
else:
self.bus.log('Started as uid: %r gid: %r' % current_ids())
if self.gid is not None:
os.setgid(self.gid)
os.setgroups([])
if self.uid is not None:
os.setuid(self.uid)
self.bus.log('Running as uid: %r gid: %r' % current_ids())
# umask
if self.finalized:
if self.umask is not None:
self.bus.log('umask already set to: %03o' % self.umask)
else:
if self.umask is None:
self.bus.log('umask not set', level=30)
else:
old_umask = os.umask(self.umask)
self.bus.log(
'umask old: %03o, new: %03o' % (old_umask, self.umask),
)
self.finalized = True
# This is slightly higher than the priority for server.start
# in order to facilitate the most common use: starting on a low
# port (which requires root) and then dropping to another user.
start.priority = 77
|
DropPrivileges
|
python
|
doocs__leetcode
|
solution/2000-2099/2089.Find Target Indices After Sorting Array/Solution.py
|
{
"start": 0,
"end": 170
}
|
class ____:
def targetIndices(self, nums: List[int], target: int) -> List[int]:
nums.sort()
return [i for i, v in enumerate(nums) if v == target]
|
Solution
|
python
|
huggingface__transformers
|
tests/fsdp/test_context_parallel.py
|
{
"start": 1125,
"end": 7748
}
|
class ____(TestCasePlus):
"""Test Trainer with Torch context parallelism enabled via accelerate's ParallelismConfig."""
@require_torch_multi_accelerator
@require_accelerate
@slow
@run_first
def test_cp_equivalence(self):
"""Test that CP produces the same losses as without CP."""
# Shared setup
world_size = 2
script_path = __file__
# Step 1: Run with CP enabled (cp_size=world_size)
cp_yes_output_dir = Path(self.get_auto_remove_tmp_dir()).resolve()
cp_yes_config_path = cp_yes_output_dir / "context_parallel_config.yaml"
cp_yes_losses_path = cp_yes_output_dir / "cp_yes_losses.json"
# Write config file inline (self-contained test)
with open(cp_yes_config_path, "w") as f:
f.write(
f"""distributed_type: FSDP
fsdp_config:
fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
fsdp_state_dict_type: SHARDED_STATE_DICT
fsdp_version: 2
mixed_precision: bf16
num_processes: {world_size}
parallelism_config:
parallelism_config_dp_replicate_size: 1
parallelism_config_dp_shard_size: 1
parallelism_config_tp_size: 1
parallelism_config_cp_size: {world_size}
parallelism_config_cp_comm_strategy: alltoall
"""
)
cmd_cp_yes = f"""
accelerate launch
--config_file {cp_yes_config_path}
{script_path}
--output_dir {cp_yes_output_dir}
--report_to none
--max_steps 10
--per_device_train_batch_size 1
--gradient_accumulation_steps 1
--logging_steps 1
--remove_unused_columns False
--seed 42
--loss_output_file {cp_yes_losses_path}
""".split()
execute_subprocess_async(cmd_cp_yes, env=self.get_env())
# Step 2: Run without CP (FSDP with num_processes=1, no parallelism_config)
cp_no_output_dir = Path(self.get_auto_remove_tmp_dir()).resolve()
cp_no_config_path = cp_no_output_dir / "context_parallel_config.yaml"
cp_no_losses_path = cp_no_output_dir / "cp_no_losses.json"
# Write config file inline (self-contained test)
with open(cp_no_config_path, "w") as f:
f.write(
"""distributed_type: FSDP
fsdp_config:
fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
fsdp_state_dict_type: SHARDED_STATE_DICT
fsdp_transformer_layer_cls_to_wrap: LlamaDecoderLayer
fsdp_version: 2
mixed_precision: bf16
num_processes: 1
"""
)
cmd_cp_no = f"""
accelerate launch
--config_file {cp_no_config_path}
{script_path}
--output_dir {cp_no_output_dir}
--report_to none
--max_steps 10
--per_device_train_batch_size 1
--gradient_accumulation_steps 1
--logging_steps 1
--remove_unused_columns False
--seed 42
--loss_output_file {cp_no_losses_path}
""".split()
execute_subprocess_async(cmd_cp_no, env=self.get_env())
# Compare losses - should be very close since CP just splits sequence computation
with open(cp_yes_losses_path) as f:
cp_yes_losses = json.load(f)
with open(cp_no_losses_path) as f:
cp_no_losses = json.load(f)
assert len(cp_yes_losses) == len(cp_no_losses), (
f"Different number of losses: CP has {len(cp_yes_losses)}, no-CP has {len(cp_no_losses)}"
)
# CP should produce very similar results (small numerical differences expected)
# The differences come from:
# - Different gradient reduction patterns in distributed training
# - BF16 mixed precision accumulated differences
# - Sequence splitting and gathering in CP mode
cp_yes_losses_tensor = torch.tensor(cp_yes_losses)
cp_no_losses_tensor = torch.tensor(cp_no_losses)
# Use torch.testing.assert_close with rtol=2% and atol=0.02
# Testing shows actual differences are typically <1.5%
torch.testing.assert_close(
cp_yes_losses_tensor,
cp_no_losses_tensor,
rtol=2e-2, # 2% relative tolerance
atol=2e-2, # 0.02 absolute tolerance
msg=f"CP losses {cp_yes_losses} do not match non-CP losses {cp_no_losses}",
)
if __name__ == "__main__":
# Parse custom arguments (not TrainingArguments parameters)
loss_output_file = None
if "--loss_output_file" in sys.argv:
idx = sys.argv.index("--loss_output_file")
loss_output_file = sys.argv[idx + 1]
sys.argv.pop(idx)
sys.argv.pop(idx)
parser = HfArgumentParser((TrainingArguments,))
training_args = parser.parse_args_into_dataclasses()[0]
# Use SmolLM (small Llama-based model that works with CP)
model_name = "HuggingFaceTB/SmolLM-135M"
tokenizer = AutoTokenizer.from_pretrained(model_name)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
model = AutoModelForCausalLM.from_pretrained(
model_name,
attn_implementation="sdpa", # CP requires SDPA
)
# Create simple dataset: just tokenize some text
texts = [
"The quick brown fox jumps over the lazy dog. " * 10,
"Hello world, this is a test sentence for training. " * 10,
] * 4 # 8 samples total
def tokenize_function(examples):
return tokenizer(examples, max_length=128, truncation=True, padding="max_length")
train_dataset = [tokenize_function(text) for text in texts]
# Use standard DataCollatorForLanguageModeling for causal LM
# pad_to_multiple_of=4 ensures sequences are divisible by cp_size * 2 (for cp_size=2)
# Trainer will automatically generate position_ids and shift_labels as needed
data_collator = DataCollatorForLanguageModeling(
tokenizer=tokenizer,
mlm=False, # Causal language modeling
pad_to_multiple_of=4,
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
data_collator=data_collator,
)
# Train for a few steps
trainer.train()
# Verify training completed
assert trainer.state.global_step > 0, "Training should have completed at least one step"
# Save losses to file if requested (for equivalence testing)
if loss_output_file and training_args.process_index == 0:
losses = [log["loss"] for log in trainer.state.log_history if "loss" in log]
with open(loss_output_file, "w") as f:
json.dump(losses, f)
|
TestContextParallel
|
python
|
microsoft__pyright
|
packages/pyright-internal/src/tests/samples/constructor14.py
|
{
"start": 537,
"end": 756
}
|
class ____(Generic[T_contra]):
def __init__(self, callback: Callback[T_contra]) -> None:
self._callback: Callback[T_contra] = callback
def copy(self) -> Self:
return type(self)(self._callback)
|
Thing
|
python
|
apache__airflow
|
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dags.py
|
{
"start": 2441,
"end": 8814
}
|
class ____:
"""Common class for /dags related unit tests."""
@staticmethod
def _clear_db():
clear_db_connections()
clear_db_runs()
clear_db_dags()
clear_db_assets()
clear_db_serialized_dags()
def _create_deactivated_paused_dag(self, session=None):
dag_model = DagModel(
dag_id=DAG3_ID,
bundle_name="dag_maker",
relative_fileloc="dag_del_1.py",
fileloc="/tmp/dag_del_1.py",
timetable_summary="2 2 * * *",
is_stale=True,
is_paused=True,
owners="test_owner,another_test_owner",
next_dagrun=datetime(2021, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
)
dagrun_failed = DagRun(
dag_id=DAG3_ID,
run_id="run1",
logical_date=datetime(2018, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
start_date=DAG3_START_DATE_1,
run_type=DagRunType.SCHEDULED,
state=DagRunState.FAILED,
triggered_by=DagRunTriggeredByType.TEST,
)
dagrun_success = DagRun(
dag_id=DAG3_ID,
run_id="run2",
logical_date=datetime(2019, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
start_date=DAG3_START_DATE_2,
run_type=DagRunType.MANUAL,
state=DagRunState.SUCCESS,
triggered_by=DagRunTriggeredByType.TEST,
)
session.add(dag_model)
session.add(dagrun_failed)
session.add(dagrun_success)
def _create_dag_tags(self, session=None):
session.add(DagTag(dag_id=DAG1_ID, name="tag_2"))
session.add(DagTag(dag_id=DAG2_ID, name="tag_1"))
session.add(DagTag(dag_id=DAG3_ID, name="tag_1"))
def _create_asset_test_data(self, session=None):
"""Create test assets and asset-scheduled DAGs."""
# Create assets
asset1 = AssetModel(uri="test://asset1", name="test_asset_1", group="test-group")
asset2 = AssetModel(uri="s3://bucket/dataset", name="dataset_asset", group="test-group")
asset3 = AssetModel(uri="test://scheduled_asset", name="scheduled_asset", group="test-group")
session.add_all([asset1, asset2, asset3])
session.commit()
# Create a DAG with asset-based scheduling
asset_scheduled_dag = DagModel(
dag_id=ASSET_SCHEDULED_DAG_ID,
bundle_name="dag_maker",
relative_fileloc="asset_scheduled_dag.py",
fileloc="/tmp/asset_scheduled_dag.py",
timetable_summary="Asset",
timetable_description="Triggered by assets",
is_stale=False,
is_paused=False,
owners="airflow",
asset_expression={"any": [{"uri": "test://scheduled_asset"}]},
max_active_tasks=16,
max_active_runs=16,
max_consecutive_failed_dag_runs=0,
has_task_concurrency_limits=False,
has_import_errors=False,
)
# Create DAGs with asset dependencies
asset_dep_dag = DagModel(
dag_id=ASSET_DEP_DAG_ID,
bundle_name="dag_maker",
relative_fileloc="asset_dep_dag.py",
fileloc="/tmp/asset_dep_dag.py",
timetable_summary="Asset",
timetable_description="Triggered by assets",
is_stale=False,
is_paused=False,
owners="airflow",
asset_expression={"any": [{"uri": "test://asset1"}]},
max_active_tasks=16,
max_active_runs=16,
max_consecutive_failed_dag_runs=0,
has_task_concurrency_limits=False,
has_import_errors=False,
)
asset_dep_dag2 = DagModel(
dag_id=ASSET_DEP_DAG2_ID,
bundle_name="dag_maker",
relative_fileloc="asset_dep_dag2.py",
fileloc="/tmp/asset_dep_dag2.py",
timetable_summary="Asset",
timetable_description="Triggered by assets",
is_stale=False,
is_paused=False,
owners="airflow",
asset_expression={"any": [{"uri": "s3://bucket/dataset"}]},
max_active_tasks=16,
max_active_runs=16,
max_consecutive_failed_dag_runs=0,
has_task_concurrency_limits=False,
has_import_errors=False,
)
session.add_all([asset_scheduled_dag, asset_dep_dag, asset_dep_dag2])
session.commit()
# Create asset dependencies
asset_ref1 = DagScheduleAssetReference(dag_id=ASSET_DEP_DAG_ID, asset_id=asset1.id)
asset_ref2 = DagScheduleAssetReference(dag_id=ASSET_DEP_DAG2_ID, asset_id=asset2.id)
asset_ref3 = DagScheduleAssetReference(dag_id=ASSET_SCHEDULED_DAG_ID, asset_id=asset3.id)
session.add_all([asset_ref1, asset_ref2, asset_ref3])
session.commit()
@pytest.fixture(autouse=True)
def setup(self, dag_maker, session) -> None:
self._clear_db()
with dag_maker(
DAG1_ID,
dag_display_name=DAG1_DISPLAY_NAME,
schedule=None,
start_date=DAG1_START_DATE,
doc_md="details",
default_args={
"depends_on_past": False,
"retries": 1,
"retry_delay": timedelta(minutes=5),
},
params={"foo": 1},
tags=["example"],
):
EmptyOperator(task_id=TASK_ID)
dag_maker.create_dagrun(state=DagRunState.FAILED)
with dag_maker(
DAG2_ID,
schedule=None,
start_date=DAG2_START_DATE,
doc_md="details",
default_args={
"depends_on_past": False,
"retries": 1,
"retry_delay": timedelta(minutes=5),
},
params={"foo": 1},
max_active_tasks=16,
max_active_runs=16,
):
EmptyOperator(task_id=TASK_ID)
self._create_deactivated_paused_dag(session)
self._create_dag_tags(session)
dag_maker.sync_dagbag_to_db()
dag_maker.dag_model.last_parse_duration = 0.24
dag_maker.dag_model.has_task_concurrency_limits = True
session.merge(dag_maker.dag_model)
session.commit()
def teardown_method(self) -> None:
self._clear_db()
|
TestDagEndpoint
|
python
|
sqlalchemy__sqlalchemy
|
test/orm/test_lockmode.py
|
{
"start": 1860,
"end": 4652
}
|
class ____(_fixtures.FixtureTest):
__sparse_driver_backend__ = True
# test against the major backends. We are naming specific databases
# here rather than using requirements rules since the behavior of
# "FOR UPDATE" as well as "OF" is very specific to each DB, and we need
# to run the query differently based on backend.
@classmethod
def setup_mappers(cls):
User, users = cls.classes.User, cls.tables.users
Address, addresses = cls.classes.Address, cls.tables.addresses
cls.mapper_registry.map_imperatively(
User, users, properties={"addresses": relationship(Address)}
)
cls.mapper_registry.map_imperatively(Address, addresses)
def test_inner_joinedload_w_limit(self):
User = self.classes.User
sess = fixture_session()
q = (
sess.query(User)
.options(joinedload(User.addresses, innerjoin=True))
.with_for_update()
.limit(1)
)
if testing.against("oracle"):
assert_raises_message(exc.DatabaseError, "ORA-02014", q.all)
else:
q.all()
sess.close()
def test_inner_joinedload_wo_limit(self):
User = self.classes.User
sess = fixture_session()
sess.query(User).options(
joinedload(User.addresses, innerjoin=True)
).with_for_update().all()
sess.close()
def test_outer_joinedload_w_limit(self):
User = self.classes.User
sess = fixture_session()
q = sess.query(User).options(
joinedload(User.addresses, innerjoin=False)
)
if testing.against("postgresql"):
q = q.with_for_update(of=User)
else:
q = q.with_for_update()
q = q.limit(1)
if testing.against("oracle"):
assert_raises_message(exc.DatabaseError, "ORA-02014", q.all)
else:
q.all()
sess.close()
def test_outer_joinedload_wo_limit(self):
User = self.classes.User
sess = fixture_session()
q = sess.query(User).options(
joinedload(User.addresses, innerjoin=False)
)
if testing.against("postgresql"):
q = q.with_for_update(of=User)
else:
q = q.with_for_update()
q.all()
sess.close()
def test_join_w_subquery(self):
User = self.classes.User
Address = self.classes.Address
sess = fixture_session()
q1 = sess.query(User).with_for_update().subquery()
sess.query(q1).join(Address).all()
sess.close()
def test_plain(self):
User = self.classes.User
sess = fixture_session()
sess.query(User).with_for_update().all()
sess.close()
|
BackendTest
|
python
|
pallets__click
|
src/click/testing.py
|
{
"start": 6336,
"end": 19102
}
|
class ____:
"""The CLI runner provides functionality to invoke a Click command line
script for unittesting purposes in a isolated environment. This only
works in single-threaded systems without any concurrency as it changes the
global interpreter state.
:param charset: the character set for the input and output data.
:param env: a dictionary with environment variables for overriding.
:param echo_stdin: if this is set to `True`, then reading from `<stdin>` writes
to `<stdout>`. This is useful for showing examples in
some circumstances. Note that regular prompts
will automatically echo the input.
:param catch_exceptions: Whether to catch any exceptions other than
``SystemExit`` when running :meth:`~CliRunner.invoke`.
.. versionchanged:: 8.2
Added the ``catch_exceptions`` parameter.
.. versionchanged:: 8.2
``mix_stderr`` parameter has been removed.
"""
def __init__(
self,
charset: str = "utf-8",
env: cabc.Mapping[str, str | None] | None = None,
echo_stdin: bool = False,
catch_exceptions: bool = True,
) -> None:
self.charset = charset
self.env: cabc.Mapping[str, str | None] = env or {}
self.echo_stdin = echo_stdin
self.catch_exceptions = catch_exceptions
def get_default_prog_name(self, cli: Command) -> str:
"""Given a command object it will return the default program name
for it. The default is the `name` attribute or ``"root"`` if not
set.
"""
return cli.name or "root"
def make_env(
self, overrides: cabc.Mapping[str, str | None] | None = None
) -> cabc.Mapping[str, str | None]:
"""Returns the environment overrides for invoking a script."""
rv = dict(self.env)
if overrides:
rv.update(overrides)
return rv
@contextlib.contextmanager
def isolation(
self,
input: str | bytes | t.IO[t.Any] | None = None,
env: cabc.Mapping[str, str | None] | None = None,
color: bool = False,
) -> cabc.Iterator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]:
"""A context manager that sets up the isolation for invoking of a
command line tool. This sets up `<stdin>` with the given input data
and `os.environ` with the overrides from the given dictionary.
This also rebinds some internals in Click to be mocked (like the
prompt functionality).
This is automatically done in the :meth:`invoke` method.
:param input: the input stream to put into `sys.stdin`.
:param env: the environment overrides as dictionary.
:param color: whether the output should contain color codes. The
application can still override this explicitly.
.. versionadded:: 8.2
An additional output stream is returned, which is a mix of
`<stdout>` and `<stderr>` streams.
.. versionchanged:: 8.2
Always returns the `<stderr>` stream.
.. versionchanged:: 8.0
`<stderr>` is opened with ``errors="backslashreplace"``
instead of the default ``"strict"``.
.. versionchanged:: 4.0
Added the ``color`` parameter.
"""
bytes_input = make_input_stream(input, self.charset)
echo_input = None
old_stdin = sys.stdin
old_stdout = sys.stdout
old_stderr = sys.stderr
old_forced_width = formatting.FORCED_WIDTH
formatting.FORCED_WIDTH = 80
env = self.make_env(env)
stream_mixer = StreamMixer()
if self.echo_stdin:
bytes_input = echo_input = t.cast(
t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout)
)
sys.stdin = text_input = _NamedTextIOWrapper(
bytes_input, encoding=self.charset, name="<stdin>", mode="r"
)
if self.echo_stdin:
# Force unbuffered reads, otherwise TextIOWrapper reads a
# large chunk which is echoed early.
text_input._CHUNK_SIZE = 1 # type: ignore
sys.stdout = _NamedTextIOWrapper(
stream_mixer.stdout, encoding=self.charset, name="<stdout>", mode="w"
)
sys.stderr = _NamedTextIOWrapper(
stream_mixer.stderr,
encoding=self.charset,
name="<stderr>",
mode="w",
errors="backslashreplace",
)
@_pause_echo(echo_input) # type: ignore
def visible_input(prompt: str | None = None) -> str:
sys.stdout.write(prompt or "")
try:
val = next(text_input).rstrip("\r\n")
except StopIteration as e:
raise EOFError() from e
sys.stdout.write(f"{val}\n")
sys.stdout.flush()
return val
@_pause_echo(echo_input) # type: ignore
def hidden_input(prompt: str | None = None) -> str:
sys.stdout.write(f"{prompt or ''}\n")
sys.stdout.flush()
try:
return next(text_input).rstrip("\r\n")
except StopIteration as e:
raise EOFError() from e
@_pause_echo(echo_input) # type: ignore
def _getchar(echo: bool) -> str:
char = sys.stdin.read(1)
if echo:
sys.stdout.write(char)
sys.stdout.flush()
return char
default_color = color
def should_strip_ansi(
stream: t.IO[t.Any] | None = None, color: bool | None = None
) -> bool:
if color is None:
return not default_color
return not color
old_visible_prompt_func = termui.visible_prompt_func
old_hidden_prompt_func = termui.hidden_prompt_func
old__getchar_func = termui._getchar
old_should_strip_ansi = utils.should_strip_ansi # type: ignore
old__compat_should_strip_ansi = _compat.should_strip_ansi
termui.visible_prompt_func = visible_input
termui.hidden_prompt_func = hidden_input
termui._getchar = _getchar
utils.should_strip_ansi = should_strip_ansi # type: ignore
_compat.should_strip_ansi = should_strip_ansi
old_env = {}
try:
for key, value in env.items():
old_env[key] = os.environ.get(key)
if value is None:
try:
del os.environ[key]
except Exception:
pass
else:
os.environ[key] = value
yield (stream_mixer.stdout, stream_mixer.stderr, stream_mixer.output)
finally:
for key, value in old_env.items():
if value is None:
try:
del os.environ[key]
except Exception:
pass
else:
os.environ[key] = value
sys.stdout = old_stdout
sys.stderr = old_stderr
sys.stdin = old_stdin
termui.visible_prompt_func = old_visible_prompt_func
termui.hidden_prompt_func = old_hidden_prompt_func
termui._getchar = old__getchar_func
utils.should_strip_ansi = old_should_strip_ansi # type: ignore
_compat.should_strip_ansi = old__compat_should_strip_ansi
formatting.FORCED_WIDTH = old_forced_width
def invoke(
self,
cli: Command,
args: str | cabc.Sequence[str] | None = None,
input: str | bytes | t.IO[t.Any] | None = None,
env: cabc.Mapping[str, str | None] | None = None,
catch_exceptions: bool | None = None,
color: bool = False,
**extra: t.Any,
) -> Result:
"""Invokes a command in an isolated environment. The arguments are
forwarded directly to the command line script, the `extra` keyword
arguments are passed to the :meth:`~clickpkg.Command.main` function of
the command.
This returns a :class:`Result` object.
:param cli: the command to invoke
:param args: the arguments to invoke. It may be given as an iterable
or a string. When given as string it will be interpreted
as a Unix shell command. More details at
:func:`shlex.split`.
:param input: the input data for `sys.stdin`.
:param env: the environment overrides.
:param catch_exceptions: Whether to catch any other exceptions than
``SystemExit``. If :data:`None`, the value
from :class:`CliRunner` is used.
:param extra: the keyword arguments to pass to :meth:`main`.
:param color: whether the output should contain color codes. The
application can still override this explicitly.
.. versionadded:: 8.2
The result object has the ``output_bytes`` attribute with
the mix of ``stdout_bytes`` and ``stderr_bytes``, as the user would
see it in its terminal.
.. versionchanged:: 8.2
The result object always returns the ``stderr_bytes`` stream.
.. versionchanged:: 8.0
The result object has the ``return_value`` attribute with
the value returned from the invoked command.
.. versionchanged:: 4.0
Added the ``color`` parameter.
.. versionchanged:: 3.0
Added the ``catch_exceptions`` parameter.
.. versionchanged:: 3.0
The result object has the ``exc_info`` attribute with the
traceback if available.
"""
exc_info = None
if catch_exceptions is None:
catch_exceptions = self.catch_exceptions
with self.isolation(input=input, env=env, color=color) as outstreams:
return_value = None
exception: BaseException | None = None
exit_code = 0
if isinstance(args, str):
args = shlex.split(args)
try:
prog_name = extra.pop("prog_name")
except KeyError:
prog_name = self.get_default_prog_name(cli)
try:
return_value = cli.main(args=args or (), prog_name=prog_name, **extra)
except SystemExit as e:
exc_info = sys.exc_info()
e_code = t.cast("int | t.Any | None", e.code)
if e_code is None:
e_code = 0
if e_code != 0:
exception = e
if not isinstance(e_code, int):
sys.stdout.write(str(e_code))
sys.stdout.write("\n")
e_code = 1
exit_code = e_code
except Exception as e:
if not catch_exceptions:
raise
exception = e
exit_code = 1
exc_info = sys.exc_info()
finally:
sys.stdout.flush()
sys.stderr.flush()
stdout = outstreams[0].getvalue()
stderr = outstreams[1].getvalue()
output = outstreams[2].getvalue()
return Result(
runner=self,
stdout_bytes=stdout,
stderr_bytes=stderr,
output_bytes=output,
return_value=return_value,
exit_code=exit_code,
exception=exception,
exc_info=exc_info, # type: ignore
)
@contextlib.contextmanager
def isolated_filesystem(
self, temp_dir: str | os.PathLike[str] | None = None
) -> cabc.Iterator[str]:
"""A context manager that creates a temporary directory and
changes the current working directory to it. This isolates tests
that affect the contents of the CWD to prevent them from
interfering with each other.
:param temp_dir: Create the temporary directory under this
directory. If given, the created directory is not removed
when exiting.
.. versionchanged:: 8.0
Added the ``temp_dir`` parameter.
"""
cwd = os.getcwd()
dt = tempfile.mkdtemp(dir=temp_dir)
os.chdir(dt)
try:
yield dt
finally:
os.chdir(cwd)
if temp_dir is None:
import shutil
try:
shutil.rmtree(dt)
except OSError:
pass
|
CliRunner
|
python
|
getsentry__sentry
|
src/sentry/monitors/endpoints/project_monitor_details.py
|
{
"start": 875,
"end": 3181
}
|
class ____(ProjectMonitorEndpoint, MonitorDetailsMixin):
publish_status = {
"DELETE": ApiPublishStatus.PUBLIC,
"GET": ApiPublishStatus.PUBLIC,
"PUT": ApiPublishStatus.PUBLIC,
}
owner = ApiOwner.CRONS
@extend_schema(
operation_id="Retrieve a Monitor for a Project",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
GlobalParams.PROJECT_ID_OR_SLUG,
MonitorParams.MONITOR_ID_OR_SLUG,
],
responses={
200: MonitorSerializer,
401: RESPONSE_UNAUTHORIZED,
403: RESPONSE_FORBIDDEN,
404: RESPONSE_NOT_FOUND,
},
)
def get(self, request: Request, project, monitor) -> Response:
"""
Retrieves details for a monitor.
"""
return self.get_monitor(request, project, monitor)
@extend_schema(
operation_id="Update a Monitor for a Project",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
GlobalParams.PROJECT_ID_OR_SLUG,
MonitorParams.MONITOR_ID_OR_SLUG,
],
request=MonitorValidator,
responses={
200: MonitorSerializer,
400: RESPONSE_BAD_REQUEST,
401: RESPONSE_UNAUTHORIZED,
403: RESPONSE_FORBIDDEN,
404: RESPONSE_NOT_FOUND,
},
)
def put(self, request: AuthenticatedHttpRequest, project, monitor) -> Response:
"""
Update a monitor.
"""
return self.update_monitor(request, project, monitor)
@extend_schema(
operation_id="Delete a Monitor or Monitor Environments for a Project",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
GlobalParams.PROJECT_ID_OR_SLUG,
MonitorParams.MONITOR_ID_OR_SLUG,
GlobalParams.ENVIRONMENT,
],
request=MonitorValidator,
responses={
202: RESPONSE_ACCEPTED,
401: RESPONSE_UNAUTHORIZED,
403: RESPONSE_FORBIDDEN,
404: RESPONSE_NOT_FOUND,
},
)
def delete(self, request: Request, project, monitor) -> Response:
"""
Delete a monitor or monitor environments.
"""
return self.delete_monitor(request, project, monitor)
|
ProjectMonitorDetailsEndpoint
|
python
|
getsentry__sentry
|
tests/sentry/seer/autofix/test_autofix.py
|
{
"start": 44329,
"end": 49246
}
|
class ____(TestCase):
def test_get_github_username_for_user_with_github(self) -> None:
"""Tests getting GitHub username from ExternalActor with GitHub provider."""
from sentry.integrations.models.external_actor import ExternalActor
from sentry.integrations.types import ExternalProviders
user = self.create_user()
organization = self.create_organization()
# Create an ExternalActor with GitHub provider
ExternalActor.objects.create(
user_id=user.id,
organization=organization,
provider=ExternalProviders.GITHUB.value,
external_name="@testuser",
external_id="12345",
integration_id=1,
)
username = _get_github_username_for_user(user, organization.id)
assert username == "testuser"
def test_get_github_username_for_user_with_github_enterprise(self) -> None:
"""Tests getting GitHub username from ExternalActor with GitHub Enterprise provider."""
from sentry.integrations.models.external_actor import ExternalActor
from sentry.integrations.types import ExternalProviders
user = self.create_user()
organization = self.create_organization()
# Create an ExternalActor with GitHub Enterprise provider
ExternalActor.objects.create(
user_id=user.id,
organization=organization,
provider=ExternalProviders.GITHUB_ENTERPRISE.value,
external_name="@gheuser",
external_id="67890",
integration_id=2,
)
username = _get_github_username_for_user(user, organization.id)
assert username == "gheuser"
def test_get_github_username_for_user_without_at_prefix(self) -> None:
"""Tests getting GitHub username when external_name doesn't have @ prefix."""
from sentry.integrations.models.external_actor import ExternalActor
from sentry.integrations.types import ExternalProviders
user = self.create_user()
organization = self.create_organization()
# Create an ExternalActor without @ prefix
ExternalActor.objects.create(
user_id=user.id,
organization=organization,
provider=ExternalProviders.GITHUB.value,
external_name="noprefixuser",
external_id="11111",
integration_id=3,
)
username = _get_github_username_for_user(user, organization.id)
assert username == "noprefixuser"
def test_get_github_username_for_user_no_mapping(self) -> None:
"""Tests that None is returned when user has no GitHub mapping."""
user = self.create_user()
organization = self.create_organization()
username = _get_github_username_for_user(user, organization.id)
assert username is None
def test_get_github_username_for_user_non_github_provider(self) -> None:
"""Tests that None is returned when user only has non-GitHub external actors."""
from sentry.integrations.models.external_actor import ExternalActor
from sentry.integrations.types import ExternalProviders
user = self.create_user()
organization = self.create_organization()
# Create an ExternalActor with Slack provider (should be ignored)
ExternalActor.objects.create(
user_id=user.id,
organization=organization,
provider=ExternalProviders.SLACK.value,
external_name="@slackuser",
external_id="slack123",
integration_id=4,
)
username = _get_github_username_for_user(user, organization.id)
assert username is None
def test_get_github_username_for_user_multiple_mappings(self) -> None:
"""Tests that most recent GitHub mapping is used when multiple exist."""
from sentry.integrations.models.external_actor import ExternalActor
from sentry.integrations.types import ExternalProviders
user = self.create_user()
organization = self.create_organization()
# Create older mapping
ExternalActor.objects.create(
user_id=user.id,
organization=organization,
provider=ExternalProviders.GITHUB.value,
external_name="@olduser",
external_id="old123",
integration_id=5,
date_added=before_now(days=10),
)
# Create newer mapping
ExternalActor.objects.create(
user_id=user.id,
organization=organization,
provider=ExternalProviders.GITHUB.value,
external_name="@newuser",
external_id="new456",
integration_id=6,
date_added=before_now(days=1),
)
username = _get_github_username_for_user(user, organization.id)
assert username == "newuser"
|
TestGetGithubUsernameForUser
|
python
|
numpy__numpy
|
numpy/f2py/tests/test_symbolic.py
|
{
"start": 450,
"end": 18561
}
|
class ____(util.F2PyTest):
def test_eliminate_quotes(self):
def worker(s):
r, d = eliminate_quotes(s)
s1 = insert_quotes(r, d)
assert s1 == s
for kind in ["", "mykind_"]:
worker(kind + '"1234" // "ABCD"')
worker(kind + '"1234" // ' + kind + '"ABCD"')
worker(kind + "\"1234\" // 'ABCD'")
worker(kind + '"1234" // ' + kind + "'ABCD'")
worker(kind + '"1\\"2\'AB\'34"')
worker("a = " + kind + "'1\\'2\"AB\"34'")
def test_sanity(self):
x = as_symbol("x")
y = as_symbol("y")
z = as_symbol("z")
assert x.op == Op.SYMBOL
assert repr(x) == "Expr(Op.SYMBOL, 'x')"
assert x == x
assert x != y
assert hash(x) is not None
n = as_number(123)
m = as_number(456)
assert n.op == Op.INTEGER
assert repr(n) == "Expr(Op.INTEGER, (123, 4))"
assert n == n
assert n != m
assert hash(n) is not None
fn = as_number(12.3)
fm = as_number(45.6)
assert fn.op == Op.REAL
assert repr(fn) == "Expr(Op.REAL, (12.3, 4))"
assert fn == fn
assert fn != fm
assert hash(fn) is not None
c = as_complex(1, 2)
c2 = as_complex(3, 4)
assert c.op == Op.COMPLEX
assert repr(c) == ("Expr(Op.COMPLEX, (Expr(Op.INTEGER, (1, 4)),"
" Expr(Op.INTEGER, (2, 4))))")
assert c == c
assert c != c2
assert hash(c) is not None
s = as_string("'123'")
s2 = as_string('"ABC"')
assert s.op == Op.STRING
assert repr(s) == "Expr(Op.STRING, (\"'123'\", 1))", repr(s)
assert s == s
assert s != s2
a = as_array((n, m))
b = as_array((n, ))
assert a.op == Op.ARRAY
assert repr(a) == ("Expr(Op.ARRAY, (Expr(Op.INTEGER, (123, 4)),"
" Expr(Op.INTEGER, (456, 4))))")
assert a == a
assert a != b
t = as_terms(x)
u = as_terms(y)
assert t.op == Op.TERMS
assert repr(t) == "Expr(Op.TERMS, {Expr(Op.SYMBOL, 'x'): 1})"
assert t == t
assert t != u
assert hash(t) is not None
v = as_factors(x)
w = as_factors(y)
assert v.op == Op.FACTORS
assert repr(v) == "Expr(Op.FACTORS, {Expr(Op.SYMBOL, 'x'): 1})"
assert v == v
assert w != v
assert hash(v) is not None
t = as_ternary(x, y, z)
u = as_ternary(x, z, y)
assert t.op == Op.TERNARY
assert t == t
assert t != u
assert hash(t) is not None
e = as_eq(x, y)
f = as_lt(x, y)
assert e.op == Op.RELATIONAL
assert e == e
assert e != f
assert hash(e) is not None
def test_tostring_fortran(self):
x = as_symbol("x")
y = as_symbol("y")
z = as_symbol("z")
n = as_number(123)
m = as_number(456)
a = as_array((n, m))
c = as_complex(n, m)
assert str(x) == "x"
assert str(n) == "123"
assert str(a) == "[123, 456]"
assert str(c) == "(123, 456)"
assert str(Expr(Op.TERMS, {x: 1})) == "x"
assert str(Expr(Op.TERMS, {x: 2})) == "2 * x"
assert str(Expr(Op.TERMS, {x: -1})) == "-x"
assert str(Expr(Op.TERMS, {x: -2})) == "-2 * x"
assert str(Expr(Op.TERMS, {x: 1, y: 1})) == "x + y"
assert str(Expr(Op.TERMS, {x: -1, y: -1})) == "-x - y"
assert str(Expr(Op.TERMS, {x: 2, y: 3})) == "2 * x + 3 * y"
assert str(Expr(Op.TERMS, {x: -2, y: 3})) == "-2 * x + 3 * y"
assert str(Expr(Op.TERMS, {x: 2, y: -3})) == "2 * x - 3 * y"
assert str(Expr(Op.FACTORS, {x: 1})) == "x"
assert str(Expr(Op.FACTORS, {x: 2})) == "x ** 2"
assert str(Expr(Op.FACTORS, {x: -1})) == "x ** -1"
assert str(Expr(Op.FACTORS, {x: -2})) == "x ** -2"
assert str(Expr(Op.FACTORS, {x: 1, y: 1})) == "x * y"
assert str(Expr(Op.FACTORS, {x: 2, y: 3})) == "x ** 2 * y ** 3"
v = Expr(Op.FACTORS, {x: 2, Expr(Op.TERMS, {x: 1, y: 1}): 3})
assert str(v) == "x ** 2 * (x + y) ** 3", str(v)
v = Expr(Op.FACTORS, {x: 2, Expr(Op.FACTORS, {x: 1, y: 1}): 3})
assert str(v) == "x ** 2 * (x * y) ** 3", str(v)
assert str(Expr(Op.APPLY, ("f", (), {}))) == "f()"
assert str(Expr(Op.APPLY, ("f", (x, ), {}))) == "f(x)"
assert str(Expr(Op.APPLY, ("f", (x, y), {}))) == "f(x, y)"
assert str(Expr(Op.INDEXING, ("f", x))) == "f[x]"
assert str(as_ternary(x, y, z)) == "merge(y, z, x)"
assert str(as_eq(x, y)) == "x .eq. y"
assert str(as_ne(x, y)) == "x .ne. y"
assert str(as_lt(x, y)) == "x .lt. y"
assert str(as_le(x, y)) == "x .le. y"
assert str(as_gt(x, y)) == "x .gt. y"
assert str(as_ge(x, y)) == "x .ge. y"
def test_tostring_c(self):
language = Language.C
x = as_symbol("x")
y = as_symbol("y")
z = as_symbol("z")
n = as_number(123)
assert Expr(Op.FACTORS, {x: 2}).tostring(language=language) == "x * x"
assert (Expr(Op.FACTORS, {
x + y: 2
}).tostring(language=language) == "(x + y) * (x + y)")
assert Expr(Op.FACTORS, {
x: 12
}).tostring(language=language) == "pow(x, 12)"
assert as_apply(ArithOp.DIV, x,
y).tostring(language=language) == "x / y"
assert (as_apply(ArithOp.DIV, x,
x + y).tostring(language=language) == "x / (x + y)")
assert (as_apply(ArithOp.DIV, x - y, x +
y).tostring(language=language) == "(x - y) / (x + y)")
assert (x + (x - y) / (x + y) +
n).tostring(language=language) == "123 + x + (x - y) / (x + y)"
assert as_ternary(x, y, z).tostring(language=language) == "(x?y:z)"
assert as_eq(x, y).tostring(language=language) == "x == y"
assert as_ne(x, y).tostring(language=language) == "x != y"
assert as_lt(x, y).tostring(language=language) == "x < y"
assert as_le(x, y).tostring(language=language) == "x <= y"
assert as_gt(x, y).tostring(language=language) == "x > y"
assert as_ge(x, y).tostring(language=language) == "x >= y"
def test_operations(self):
x = as_symbol("x")
y = as_symbol("y")
z = as_symbol("z")
assert x + x == Expr(Op.TERMS, {x: 2})
assert x - x == Expr(Op.INTEGER, (0, 4))
assert x + y == Expr(Op.TERMS, {x: 1, y: 1})
assert x - y == Expr(Op.TERMS, {x: 1, y: -1})
assert x * x == Expr(Op.FACTORS, {x: 2})
assert x * y == Expr(Op.FACTORS, {x: 1, y: 1})
assert +x == x
assert -x == Expr(Op.TERMS, {x: -1}), repr(-x)
assert 2 * x == Expr(Op.TERMS, {x: 2})
assert 2 + x == Expr(Op.TERMS, {x: 1, as_number(1): 2})
assert 2 * x + 3 * y == Expr(Op.TERMS, {x: 2, y: 3})
assert (x + y) * 2 == Expr(Op.TERMS, {x: 2, y: 2})
assert x**2 == Expr(Op.FACTORS, {x: 2})
assert (x + y)**2 == Expr(
Op.TERMS,
{
Expr(Op.FACTORS, {x: 2}): 1,
Expr(Op.FACTORS, {y: 2}): 1,
Expr(Op.FACTORS, {
x: 1,
y: 1
}): 2,
},
)
assert (x + y) * x == x**2 + x * y
assert (x + y)**2 == x**2 + 2 * x * y + y**2
assert (x + y)**2 + (x - y)**2 == 2 * x**2 + 2 * y**2
assert (x + y) * z == x * z + y * z
assert z * (x + y) == x * z + y * z
assert (x / 2) == as_apply(ArithOp.DIV, x, as_number(2))
assert (2 * x / 2) == x
assert (3 * x / 2) == as_apply(ArithOp.DIV, 3 * x, as_number(2))
assert (4 * x / 2) == 2 * x
assert (5 * x / 2) == as_apply(ArithOp.DIV, 5 * x, as_number(2))
assert (6 * x / 2) == 3 * x
assert ((3 * 5) * x / 6) == as_apply(ArithOp.DIV, 5 * x, as_number(2))
assert (30 * x**2 * y**4 / (24 * x**3 * y**3)) == as_apply(
ArithOp.DIV, 5 * y, 4 * x)
assert ((15 * x / 6) / 5) == as_apply(ArithOp.DIV, x,
as_number(2)), (15 * x / 6) / 5
assert (x / (5 / x)) == as_apply(ArithOp.DIV, x**2, as_number(5))
assert (x / 2.0) == Expr(Op.TERMS, {x: 0.5})
s = as_string('"ABC"')
t = as_string('"123"')
assert s // t == Expr(Op.STRING, ('"ABC123"', 1))
assert s // x == Expr(Op.CONCAT, (s, x))
assert x // s == Expr(Op.CONCAT, (x, s))
c = as_complex(1.0, 2.0)
assert -c == as_complex(-1.0, -2.0)
assert c + c == as_expr((1 + 2j) * 2)
assert c * c == as_expr((1 + 2j)**2)
def test_substitute(self):
x = as_symbol("x")
y = as_symbol("y")
z = as_symbol("z")
a = as_array((x, y))
assert x.substitute({x: y}) == y
assert (x + y).substitute({x: z}) == y + z
assert (x * y).substitute({x: z}) == y * z
assert (x**4).substitute({x: z}) == z**4
assert (x / y).substitute({x: z}) == z / y
assert x.substitute({x: y + z}) == y + z
assert a.substitute({x: y + z}) == as_array((y + z, y))
assert as_ternary(x, y,
z).substitute({x: y + z}) == as_ternary(y + z, y, z)
assert as_eq(x, y).substitute({x: y + z}) == as_eq(y + z, y)
def test_fromstring(self):
x = as_symbol("x")
y = as_symbol("y")
z = as_symbol("z")
f = as_symbol("f")
s = as_string('"ABC"')
t = as_string('"123"')
a = as_array((x, y))
assert fromstring("x") == x
assert fromstring("+ x") == x
assert fromstring("- x") == -x
assert fromstring("x + y") == x + y
assert fromstring("x + 1") == x + 1
assert fromstring("x * y") == x * y
assert fromstring("x * 2") == x * 2
assert fromstring("x / y") == x / y
assert fromstring("x ** 2", language=Language.Python) == x**2
assert fromstring("x ** 2 ** 3", language=Language.Python) == x**2**3
assert fromstring("(x + y) * z") == (x + y) * z
assert fromstring("f(x)") == f(x)
assert fromstring("f(x,y)") == f(x, y)
assert fromstring("f[x]") == f[x]
assert fromstring("f[x][y]") == f[x][y]
assert fromstring('"ABC"') == s
assert (normalize(
fromstring('"ABC" // "123" ',
language=Language.Fortran)) == s // t)
assert fromstring('f("ABC")') == f(s)
assert fromstring('MYSTRKIND_"ABC"') == as_string('"ABC"', "MYSTRKIND")
assert fromstring("(/x, y/)") == a, fromstring("(/x, y/)")
assert fromstring("f((/x, y/))") == f(a)
assert fromstring("(/(x+y)*z/)") == as_array(((x + y) * z, ))
assert fromstring("123") == as_number(123)
assert fromstring("123_2") == as_number(123, 2)
assert fromstring("123_myintkind") == as_number(123, "myintkind")
assert fromstring("123.0") == as_number(123.0, 4)
assert fromstring("123.0_4") == as_number(123.0, 4)
assert fromstring("123.0_8") == as_number(123.0, 8)
assert fromstring("123.0e0") == as_number(123.0, 4)
assert fromstring("123.0d0") == as_number(123.0, 8)
assert fromstring("123d0") == as_number(123.0, 8)
assert fromstring("123e-0") == as_number(123.0, 4)
assert fromstring("123d+0") == as_number(123.0, 8)
assert fromstring("123.0_myrealkind") == as_number(123.0, "myrealkind")
assert fromstring("3E4") == as_number(30000.0, 4)
assert fromstring("(1, 2)") == as_complex(1, 2)
assert fromstring("(1e2, PI)") == as_complex(as_number(100.0),
as_symbol("PI"))
assert fromstring("[1, 2]") == as_array((as_number(1), as_number(2)))
assert fromstring("POINT(x, y=1)") == as_apply(as_symbol("POINT"),
x,
y=as_number(1))
assert fromstring(
'PERSON(name="John", age=50, shape=(/34, 23/))') == as_apply(
as_symbol("PERSON"),
name=as_string('"John"'),
age=as_number(50),
shape=as_array((as_number(34), as_number(23))),
)
assert fromstring("x?y:z") == as_ternary(x, y, z)
assert fromstring("*x") == as_deref(x)
assert fromstring("**x") == as_deref(as_deref(x))
assert fromstring("&x") == as_ref(x)
assert fromstring("(*x) * (*y)") == as_deref(x) * as_deref(y)
assert fromstring("(*x) * *y") == as_deref(x) * as_deref(y)
assert fromstring("*x * *y") == as_deref(x) * as_deref(y)
assert fromstring("*x**y") == as_deref(x) * as_deref(y)
assert fromstring("x == y") == as_eq(x, y)
assert fromstring("x != y") == as_ne(x, y)
assert fromstring("x < y") == as_lt(x, y)
assert fromstring("x > y") == as_gt(x, y)
assert fromstring("x <= y") == as_le(x, y)
assert fromstring("x >= y") == as_ge(x, y)
assert fromstring("x .eq. y", language=Language.Fortran) == as_eq(x, y)
assert fromstring("x .ne. y", language=Language.Fortran) == as_ne(x, y)
assert fromstring("x .lt. y", language=Language.Fortran) == as_lt(x, y)
assert fromstring("x .gt. y", language=Language.Fortran) == as_gt(x, y)
assert fromstring("x .le. y", language=Language.Fortran) == as_le(x, y)
assert fromstring("x .ge. y", language=Language.Fortran) == as_ge(x, y)
def test_traverse(self):
x = as_symbol("x")
y = as_symbol("y")
z = as_symbol("z")
f = as_symbol("f")
# Use traverse to substitute a symbol
def replace_visit(s, r=z):
if s == x:
return r
assert x.traverse(replace_visit) == z
assert y.traverse(replace_visit) == y
assert z.traverse(replace_visit) == z
assert (f(y)).traverse(replace_visit) == f(y)
assert (f(x)).traverse(replace_visit) == f(z)
assert (f[y]).traverse(replace_visit) == f[y]
assert (f[z]).traverse(replace_visit) == f[z]
assert (x + y + z).traverse(replace_visit) == (2 * z + y)
assert (x +
f(y, x - z)).traverse(replace_visit) == (z +
f(y, as_number(0)))
assert as_eq(x, y).traverse(replace_visit) == as_eq(z, y)
# Use traverse to collect symbols, method 1
function_symbols = set()
symbols = set()
def collect_symbols(s):
if s.op is Op.APPLY:
oper = s.data[0]
function_symbols.add(oper)
if oper in symbols:
symbols.remove(oper)
elif s.op is Op.SYMBOL and s not in function_symbols:
symbols.add(s)
(x + f(y, x - z)).traverse(collect_symbols)
assert function_symbols == {f}
assert symbols == {x, y, z}
# Use traverse to collect symbols, method 2
def collect_symbols2(expr, symbols):
if expr.op is Op.SYMBOL:
symbols.add(expr)
symbols = set()
(x + f(y, x - z)).traverse(collect_symbols2, symbols)
assert symbols == {x, y, z, f}
# Use traverse to partially collect symbols
def collect_symbols3(expr, symbols):
if expr.op is Op.APPLY:
# skip traversing function calls
return expr
if expr.op is Op.SYMBOL:
symbols.add(expr)
symbols = set()
(x + f(y, x - z)).traverse(collect_symbols3, symbols)
assert symbols == {x}
def test_linear_solve(self):
x = as_symbol("x")
y = as_symbol("y")
z = as_symbol("z")
assert x.linear_solve(x) == (as_number(1), as_number(0))
assert (x + 1).linear_solve(x) == (as_number(1), as_number(1))
assert (2 * x).linear_solve(x) == (as_number(2), as_number(0))
assert (2 * x + 3).linear_solve(x) == (as_number(2), as_number(3))
assert as_number(3).linear_solve(x) == (as_number(0), as_number(3))
assert y.linear_solve(x) == (as_number(0), y)
assert (y * z).linear_solve(x) == (as_number(0), y * z)
assert (x + y).linear_solve(x) == (as_number(1), y)
assert (z * x + y).linear_solve(x) == (z, y)
assert ((z + y) * x + y).linear_solve(x) == (z + y, y)
assert (z * y * x + y).linear_solve(x) == (z * y, y)
pytest.raises(RuntimeError, lambda: (x * x).linear_solve(x))
def test_as_numer_denom(self):
x = as_symbol("x")
y = as_symbol("y")
n = as_number(123)
assert as_numer_denom(x) == (x, as_number(1))
assert as_numer_denom(x / n) == (x, n)
assert as_numer_denom(n / x) == (n, x)
assert as_numer_denom(x / y) == (x, y)
assert as_numer_denom(x * y) == (x * y, as_number(1))
assert as_numer_denom(n + x / y) == (x + n * y, y)
assert as_numer_denom(n + x / (y - x / n)) == (y * n**2, y * n - x)
def test_polynomial_atoms(self):
x = as_symbol("x")
y = as_symbol("y")
n = as_number(123)
assert x.polynomial_atoms() == {x}
assert n.polynomial_atoms() == set()
assert (y[x]).polynomial_atoms() == {y[x]}
assert (y(x)).polynomial_atoms() == {y(x)}
assert (y(x) + x).polynomial_atoms() == {y(x), x}
assert (y(x) * x[y]).polynomial_atoms() == {y(x), x[y]}
assert (y(x)**x).polynomial_atoms() == {y(x)}
def test_unmatched_parenthesis_gh30268(self):
#gh - 30268
with pytest.raises(ValueError, match=r"Mismatch of \(\) parenthesis"):
Expr.parse("DATA (A, I=1, N", language=Language.Fortran)
|
TestSymbolic
|
python
|
ansible__ansible
|
test/lib/ansible_test/_internal/ci/azp.py
|
{
"start": 571,
"end": 4180
}
|
class ____(CIProvider):
"""CI provider implementation for Azure Pipelines."""
def __init__(self) -> None:
self.auth = AzurePipelinesAuthHelper()
self._changes: AzurePipelinesChanges | None = None
@staticmethod
def is_supported() -> bool:
"""Return True if this provider is supported in the current running environment."""
return os.environ.get('SYSTEM_COLLECTIONURI', '').startswith('https://dev.azure.com/')
@property
def code(self) -> str:
"""Return a unique code representing this provider."""
return CODE
@property
def name(self) -> str:
"""Return descriptive name for this provider."""
return 'Azure Pipelines'
def generate_resource_prefix(self) -> str:
"""Return a resource prefix specific to this CI provider."""
try:
prefix = 'azp-%s-%s-%s' % (
os.environ['BUILD_BUILDID'],
os.environ['SYSTEM_JOBATTEMPT'],
os.environ['SYSTEM_JOBIDENTIFIER'],
)
except KeyError as ex:
raise MissingEnvironmentVariable(name=ex.args[0]) from None
return prefix
def get_base_commit(self, args: CommonConfig) -> str:
"""Return the base commit or an empty string."""
return self._get_changes(args).base_commit or ''
def _get_changes(self, args: CommonConfig) -> AzurePipelinesChanges:
"""Return an AzurePipelinesChanges instance, which will be created on first use."""
if not self._changes:
self._changes = AzurePipelinesChanges(args)
return self._changes
def detect_changes(self, args: TestConfig) -> t.Optional[list[str]]:
"""Initialize change detection."""
result = self._get_changes(args)
if result.is_pr:
job_type = 'pull request'
else:
job_type = 'merge commit'
display.info('Processing %s for branch %s commit %s' % (job_type, result.branch, result.commit))
if not args.metadata.changes:
args.metadata.populate_changes(result.diff)
if result.paths is None:
# There are several likely causes of this:
# - First run on a new branch.
# - Too many pull requests passed since the last merge run passed.
display.warning('No successful commit found. All tests will be executed.')
return result.paths
def supports_core_ci_auth(self) -> bool:
"""Return True if Ansible Core CI is supported."""
return True
def prepare_core_ci_request(self, config: dict[str, object], context: AuthContext) -> dict[str, object]:
try:
request: dict[str, object] = dict(
type="azp:ssh",
config=config,
org_name=os.environ['SYSTEM_COLLECTIONURI'].strip('/').split('/')[-1],
project_name=os.environ['SYSTEM_TEAMPROJECT'],
build_id=int(os.environ['BUILD_BUILDID']),
task_id=str(uuid.UUID(os.environ['SYSTEM_TASKINSTANCEID'])),
)
except KeyError as ex:
raise MissingEnvironmentVariable(name=ex.args[0]) from None
self.auth.sign_request(request, context)
return request
def get_git_details(self, args: CommonConfig) -> t.Optional[dict[str, t.Any]]:
"""Return details about git in the current environment."""
changes = self._get_changes(args)
details = dict(
base_commit=changes.base_commit,
commit=changes.commit,
)
return details
|
AzurePipelines
|
python
|
scipy__scipy
|
benchmarks/benchmarks/cluster.py
|
{
"start": 3077,
"end": 3529
}
|
class ____(Benchmark):
params = [[2, 10, 50], ['float32', 'float64']]
param_names = ['k', 'dtype']
def __init__(self):
rnd = np.random.RandomState(0)
self.data = rnd.rand(5000, 5)
self.cbook_source = rnd.rand(50, 5)
def setup(self, k, dtype):
self.obs = self.data.astype(dtype)
self.cbook = self.cbook_source[:k].astype(dtype)
def time_vq(self, k, dtype):
vq(self.obs, self.cbook)
|
VQ
|
python
|
allegroai__clearml
|
clearml/backend_api/services/v2_23/frames.py
|
{
"start": 130330,
"end": 133918
}
|
class ____(Request):
"""
Get specific frames for a dataset version using the frame ids. Random Access API.
:param dataset: Dataset ID
:type dataset: str
:param version: Version ID
:type version: str
:param frame_ids: Frame IDs
:type frame_ids: Sequence[str]
:param projection: Used to select which parts of the frame will be returned.
Each string represents a field or sub-field (using dot-separated notation). In
order to specify a specific array element, use array index as a field name. To
specify all array elements, use '*'.
:type projection: Sequence[str]
"""
_service = "frames"
_action = "get_by_ids"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"dataset": {"description": "Dataset ID", "type": "string"},
"frame_ids": {
"description": "Frame IDs",
"items": {"type": "string"},
"type": "array",
},
"projection": {
"description": (
"Used to select which parts of the frame will be returned. Each string represents a\n "
" field or sub-field (using dot-separated notation). In order to specify a specific array"
" element,\n use array index as a field name. To specify all array elements, use"
" '*'."
),
"items": {"type": "string"},
"type": "array",
},
"version": {"description": "Version ID", "type": "string"},
},
"required": ["dataset", "version", "frame_ids"],
"type": "object",
}
def __init__(self, dataset, version, frame_ids, projection=None, **kwargs):
super(GetByIdsRequest, self).__init__(**kwargs)
self.dataset = dataset
self.version = version
self.frame_ids = frame_ids
self.projection = projection
@schema_property("dataset")
def dataset(self):
return self._property_dataset
@dataset.setter
def dataset(self, value):
if value is None:
self._property_dataset = None
return
self.assert_isinstance(value, "dataset", six.string_types)
self._property_dataset = value
@schema_property("version")
def version(self):
return self._property_version
@version.setter
def version(self, value):
if value is None:
self._property_version = None
return
self.assert_isinstance(value, "version", six.string_types)
self._property_version = value
@schema_property("frame_ids")
def frame_ids(self):
return self._property_frame_ids
@frame_ids.setter
def frame_ids(self, value):
if value is None:
self._property_frame_ids = None
return
self.assert_isinstance(value, "frame_ids", (list, tuple))
self.assert_isinstance(value, "frame_ids", six.string_types, is_array=True)
self._property_frame_ids = value
@schema_property("projection")
def projection(self):
return self._property_projection
@projection.setter
def projection(self, value):
if value is None:
self._property_projection = None
return
self.assert_isinstance(value, "projection", (list, tuple))
self.assert_isinstance(value, "projection", six.string_types, is_array=True)
self._property_projection = value
|
GetByIdsRequest
|
python
|
tensorflow__tensorflow
|
tensorflow/python/keras/layers/rnn_cell_wrapper_v2.py
|
{
"start": 4994,
"end": 5385
}
|
class ____(rnn_cell_wrapper_impl.DeviceWrapperBase,
_RNNCellWrapperV2):
"""Operator that ensures an RNNCell runs on a particular device."""
def __init__(self, *args, **kwargs): # pylint: disable=useless-super-delegation
super(DeviceWrapper, self).__init__(*args, **kwargs)
__init__.__doc__ = rnn_cell_wrapper_impl.DeviceWrapperBase.__init__.__doc__
|
DeviceWrapper
|
python
|
ipython__ipython
|
IPython/lib/display.py
|
{
"start": 9136,
"end": 10185
}
|
class ____:
"""
Generic class to embed an iframe in an IPython notebook
"""
iframe = """
<iframe
width="{width}"
height="{height}"
src="{src}{params}"
frameborder="0"
allowfullscreen
{extras}
></iframe>
"""
def __init__(
self, src, width, height, extras: Optional[Iterable[str]] = None, **kwargs
):
if extras is None:
extras = []
self.src = src
self.width = width
self.height = height
self.extras = extras
self.params = kwargs
def _repr_html_(self):
"""return the embed iframe"""
if self.params:
from urllib.parse import urlencode
params = "?" + urlencode(self.params)
else:
params = ""
return self.iframe.format(
src=self.src,
width=self.width,
height=self.height,
params=params,
extras=" ".join(self.extras),
)
|
IFrame
|
python
|
openai__openai-python
|
src/openai/_module_client.py
|
{
"start": 2131,
"end": 2258
}
|
class ____(LazyProxy["Videos"]):
@override
def __load__(self) -> Videos:
return _load_client().videos
|
VideosProxy
|
python
|
tensorflow__tensorflow
|
tensorflow/python/distribute/cluster_resolver/cluster_resolver.py
|
{
"start": 1974,
"end": 11814
}
|
class ____(object):
"""Abstract class for all implementations of ClusterResolvers.
This defines the skeleton for all implementations of ClusterResolvers.
ClusterResolvers are a way for TensorFlow to communicate with various cluster
management systems (e.g. GCE, AWS, etc...) and gives TensorFlow necessary
information to set up distributed training.
By letting TensorFlow communicate with these systems, we will be able to
automatically discover and resolve IP addresses for various TensorFlow
workers. This will eventually allow us to automatically recover from
underlying machine failures and scale TensorFlow worker clusters up and down.
Note to Implementors of `tf.distribute.cluster_resolver.ClusterResolver`
subclass: In addition to these abstract methods, when task_type, task_id, and
rpc_layer attributes are applicable, you should also implement them either as
properties with getters or setters, or directly set the attributes
`self._task_type`, `self._task_id`, or `self._rpc_layer` so the base class'
getters and setters are used. See
`tf.distribute.cluster_resolver.SimpleClusterResolver.__init__` for an
example.
In general, multi-client tf.distribute strategies such as
`tf.distribute.experimental.MultiWorkerMirroredStrategy` require task_type and
task_id properties to be available in the `ClusterResolver` they are using. On
the other hand, these concepts are not applicable in single-client strategies,
such as `tf.distribute.experimental.TPUStrategy`, because the program is only
expected to be run on one task, so there should not be a need to have code
branches according to task type and task id.
- task_type is the name of the server's current named job (e.g. 'worker',
'ps' in a distributed parameterized training job).
- task_id is the ordinal index of the server within the task type.
- rpc_layer is the protocol used by TensorFlow to communicate with other
TensorFlow servers in a distributed environment.
"""
@abc.abstractmethod
def cluster_spec(self):
"""Retrieve the current state of the cluster and return a `tf.train.ClusterSpec`.
Returns:
A `tf.train.ClusterSpec` representing the state of the cluster at the
moment this function is called.
Implementors of this function must take care in ensuring that the
ClusterSpec returned is up-to-date at the time of calling this function.
This usually means retrieving the information from the underlying cluster
management system every time this function is invoked and reconstructing
a cluster_spec, rather than attempting to cache anything.
"""
raise NotImplementedError()
@abc.abstractmethod
def master(self, task_type=None, task_id=None, rpc_layer=None):
"""Retrieves the name or URL of the session master.
Note: this is only useful for TensorFlow 1.x.
Args:
task_type: (Optional) The type of the TensorFlow task of the master.
task_id: (Optional) The index of the TensorFlow task of the master.
rpc_layer: (Optional) The RPC protocol for the given cluster.
Returns:
The name or URL of the session master.
Implementors of this function must take care in ensuring that the master
returned is up-to-date at the time to calling this function. This usually
means retrieving the master every time this function is invoked.
"""
raise NotImplementedError()
def num_accelerators(self,
task_type=None,
task_id=None,
config_proto=None):
"""Returns the number of accelerator cores per worker.
This returns the number of accelerator cores (such as GPUs and TPUs)
available per worker.
Optionally, we allow callers to specify the task_type, and task_id, for
if they want to target a specific TensorFlow task to query
the number of accelerators. This is to support heterogenous environments,
where the number of accelerators cores per host is different.
Args:
task_type: (Optional) The type of the TensorFlow task of the machine we
want to query.
task_id: (Optional) The index of the TensorFlow task of the machine we
want to query.
config_proto: (Optional) Configuration for starting a new session to
query how many accelerator cores it has.
Returns:
A map of accelerator types to number of cores.
"""
master = self.master(task_type, task_id)
# TODO(b/126786766): in eager mode, we should check whether
# `tf.config.experimental_connect_to_cluster` is called or not.
devices = get_accelerator_devices(master, config_proto)
mapping = collections.defaultdict(int)
for device in devices:
if task_type is not None and task_id is not None:
job_path = '/job:%s' % task_type
task_path = '/task:%s' % task_id
if job_path not in device.name or task_path not in device.name:
continue
mapping[device.device_type] += 1
return mapping
@property
def environment(self):
"""Returns the current environment which TensorFlow is running in.
There are two possible return values, "google" (when TensorFlow is running
in a Google-internal environment) or an empty string (when TensorFlow is
running elsewhere).
If you are implementing a ClusterResolver that works in both the Google
environment and the open-source world (for instance, a TPU ClusterResolver
or similar), you will have to return the appropriate string depending on the
environment, which you will have to detect.
Otherwise, if you are implementing a ClusterResolver that will only work
in open-source TensorFlow, you do not need to implement this property.
"""
return ''
@property
def task_type(self):
"""Returns the task type this `ClusterResolver` indicates.
In TensorFlow distributed environment, each job may have an applicable
task type. Valid task types in TensorFlow include
'chief': a worker that is designated with more responsibility,
'worker': a regular worker for training/evaluation,
'ps': a parameter server, or
'evaluator': an evaluator that evaluates the checkpoints for metrics.
See [Multi-worker configuration](
https://www.tensorflow.org/tutorials/distribute/multi_worker_with_keras#multi-worker_configuration)
for more information about 'chief' and 'worker' task type, which are most
commonly used.
Having access to such information is useful when user needs to run specific
code according to task types. For example,
```python
cluster_spec = tf.train.ClusterSpec({
"ps": ["localhost:2222", "localhost:2223"],
"worker": ["localhost:2224", "localhost:2225", "localhost:2226"]
})
# SimpleClusterResolver is used here for illustration; other cluster
# resolvers may be used for other source of task type/id.
simple_resolver = SimpleClusterResolver(cluster_spec, task_type="worker",
task_id=1)
...
if cluster_resolver.task_type == 'worker':
# Perform something that's only applicable on workers. This block
# will run on this particular instance since we've specified this task to
# be a worker in above cluster resolver.
elif cluster_resolver.task_type == 'ps':
# Perform something that's only applicable on parameter servers. This
# block will not run on this particular instance.
```
Returns `None` if such information is not available or is not applicable
in the current distributed environment, such as training with
`tf.distribute.experimental.TPUStrategy`.
For more information, please see
`tf.distribute.cluster_resolver.ClusterResolver`'s class doc.
"""
return getattr(self, '_task_type', None)
@property
def task_id(self):
"""Returns the task id this `ClusterResolver` indicates.
In TensorFlow distributed environment, each job may have an applicable
task id, which is the index of the instance within its task type. This is
useful when user needs to run specific code according to task index. For
example,
```python
cluster_spec = tf.train.ClusterSpec({
"ps": ["localhost:2222", "localhost:2223"],
"worker": ["localhost:2224", "localhost:2225", "localhost:2226"]
})
# SimpleClusterResolver is used here for illustration; other cluster
# resolvers may be used for other source of task type/id.
simple_resolver = SimpleClusterResolver(cluster_spec, task_type="worker",
task_id=0)
...
if cluster_resolver.task_type == 'worker' and cluster_resolver.task_id == 0:
# Perform something that's only applicable on 'worker' type, id 0. This
# block will run on this particular instance since we've specified this
# task to be a 'worker', id 0 in above cluster resolver.
else:
# Perform something that's only applicable on other ids. This block will
# not run on this particular instance.
```
Returns `None` if such information is not available or is not applicable
in the current distributed environment, such as training with
`tf.distribute.cluster_resolver.TPUClusterResolver`.
For more information, please see
`tf.distribute.cluster_resolver.ClusterResolver`'s class docstring.
"""
return getattr(self, '_task_id', None)
@task_type.setter
def task_type(self, task_type):
"""Setter of `task_type` property. See `task_type` property doc."""
self._task_type = task_type
@task_id.setter
def task_id(self, task_id):
"""Setter of `task_id` property. See `task_type` property doc."""
self._task_id = task_id
@tf_export('distribute.cluster_resolver.SimpleClusterResolver')
|
ClusterResolver
|
python
|
dagster-io__dagster
|
python_modules/dagster/dagster_tests/execution_tests/pipes_tests/in_process_client.py
|
{
"start": 759,
"end": 1069
}
|
class ____(PipesContextLoader):
def __init__(self, pipes_context_data: PipesContextData):
self.pipes_context_data = pipes_context_data
@contextmanager
def load_context(self, params: PipesParams) -> Iterator[PipesContextData]:
yield self.pipes_context_data
|
InProcessPipesContextLoader
|
python
|
tensorflow__tensorflow
|
tensorflow/python/util/nest_test.py
|
{
"start": 1603,
"end": 1901
}
|
class ____(collections.abc.Mapping):
def __init__(self, *args, **kwargs):
self._wrapped = dict(*args, **kwargs)
def __getitem__(self, key):
return self._wrapped[key]
def __iter__(self):
return iter(self._wrapped)
def __len__(self):
return len(self._wrapped)
|
_CustomMapping
|
python
|
django__django
|
tests/admin_changelist/admin.py
|
{
"start": 2562,
"end": 2698
}
|
class ____(admin.ModelAdmin):
list_filter = [NrOfMembersFilter]
site.register(Band, BandCallableFilterAdmin)
|
BandCallableFilterAdmin
|
python
|
sympy__sympy
|
sympy/functions/elementary/complexes.py
|
{
"start": 30025,
"end": 32363
}
|
class ____(DefinedFunction):
"""
Lift argument to the Riemann surface of the logarithm, using the
standard branch.
Examples
========
>>> from sympy import Symbol, polar_lift, I
>>> p = Symbol('p', polar=True)
>>> x = Symbol('x')
>>> polar_lift(4)
4*exp_polar(0)
>>> polar_lift(-4)
4*exp_polar(I*pi)
>>> polar_lift(-I)
exp_polar(-I*pi/2)
>>> polar_lift(I + 2)
polar_lift(2 + I)
>>> polar_lift(4*x)
4*polar_lift(x)
>>> polar_lift(4*p)
4*p
Parameters
==========
arg : Expr
Real or complex expression.
See Also
========
sympy.functions.elementary.exponential.exp_polar
periodic_argument
"""
is_polar = True
is_comparable = False # Cannot be evalf'd.
@classmethod
def eval(cls, arg):
from sympy.functions.elementary.complexes import arg as argument
if arg.is_number:
ar = argument(arg)
# In general we want to affirm that something is known,
# e.g. `not ar.has(argument) and not ar.has(atan)`
# but for now we will just be more restrictive and
# see that it has evaluated to one of the known values.
if ar in (0, pi/2, -pi/2, pi):
from sympy.functions.elementary.exponential import exp_polar
return exp_polar(I*ar)*abs(arg)
if arg.is_Mul:
args = arg.args
else:
args = [arg]
included = []
excluded = []
positive = []
for arg in args:
if arg.is_polar:
included += [arg]
elif arg.is_positive:
positive += [arg]
else:
excluded += [arg]
if len(excluded) < len(args):
if excluded:
return Mul(*(included + positive))*polar_lift(Mul(*excluded))
elif included:
return Mul(*(included + positive))
else:
from sympy.functions.elementary.exponential import exp_polar
return Mul(*positive)*exp_polar(0)
def _eval_evalf(self, prec):
""" Careful! any evalf of polar numbers is flaky """
return self.args[0]._eval_evalf(prec)
def _eval_Abs(self):
return Abs(self.args[0], evaluate=True)
|
polar_lift
|
python
|
conda__conda
|
conda/exceptions.py
|
{
"start": 14284,
"end": 14627
}
|
class ____(CondaError):
def __init__(self, dist: str, placeholder: str, placeholder_length: int):
msg = (
"Placeholder of length '%d' too short in package %s.\n"
"The package must be rebuilt with conda-build > 2.0."
% (placeholder_length, dist)
)
super().__init__(msg)
|
PaddingError
|
python
|
etianen__django-reversion
|
tests/test_app/tests/test_commands.py
|
{
"start": 776,
"end": 2007
}
|
class ____(TestModelMixin, TestBase):
def testCreateInitialRevisionsAppLabel(self):
obj = TestModel.objects.create()
self.callCommand("createinitialrevisions", "test_app")
self.assertSingleRevision((obj,), comment="Initial version.")
def testCreateInitialRevisionsAppLabelMissing(self):
with self.assertRaises(CommandError):
self.callCommand("createinitialrevisions", "boom")
def testCreateInitialRevisionsModel(self):
obj = TestModel.objects.create()
self.callCommand("createinitialrevisions", "test_app.TestModel")
self.assertSingleRevision((obj,), comment="Initial version.")
def testCreateInitialRevisionsModelMissing(self):
with self.assertRaises(CommandError):
self.callCommand("createinitialrevisions", "test_app.boom")
def testCreateInitialRevisionsModelMissingApp(self):
with self.assertRaises(CommandError):
self.callCommand("createinitialrevisions", "boom.boom")
def testCreateInitialRevisionsModelNotRegistered(self):
TestModel.objects.create()
self.callCommand("createinitialrevisions", "auth.User")
self.assertNoRevision()
|
CreateInitialRevisionsAppLabelTest
|
python
|
pyqtgraph__pyqtgraph
|
pyqtgraph/imageview/ImageView.py
|
{
"start": 1523,
"end": 33734
}
|
class ____(QtWidgets.QWidget):
"""
Widget used for display and analysis of image data.
Implements many features:
* Displays 2D and 3D image data. For 3D data, a z-axis
slider is displayed allowing the user to select which frame is displayed.
* Displays histogram of image data with movable region defining the dark/light levels
* Editable gradient provides a color lookup table
* Frame slider may also be moved using left/right arrow keys as well as pgup, pgdn, home, and end.
* Basic analysis features including:
* ROI and embedded plot for measuring image values across frames
* Image normalization / background subtraction
Basic Usage::
imv = pg.ImageView()
imv.show()
imv.setImage(data)
**Keyboard interaction**
* left/right arrows step forward/backward 1 frame when pressed,
seek at 20fps when held.
* up/down arrows seek at 100fps
* pgup/pgdn seek at 1000fps
* home/end seek immediately to the first/last frame
* space begins playing frames. If time values (in seconds) are given
for each frame, then playback is in realtime.
"""
sigTimeChanged = QtCore.Signal(object, object)
sigProcessingChanged = QtCore.Signal(object)
def __init__(
self,
parent=None,
name="ImageView",
view=None,
imageItem=None,
levelMode='mono',
discreteTimeLine=False,
roi=None,
normRoi=None,
*args,
):
"""
By default, this class creates an :class:`ImageItem <pyqtgraph.ImageItem>` to display image data
and a :class:`ViewBox <pyqtgraph.ViewBox>` to contain the ImageItem.
Parameters
----------
parent : QWidget
Specifies the parent widget to which this ImageView will belong. If None, then the ImageView is created with
no parent.
name : str
The name used to register both the internal ViewBox and the PlotItem used to display ROI data. See the
*name* argument to :func:`ViewBox.__init__() <pyqtgraph.ViewBox.__init__>`.
view : ViewBox or PlotItem
If specified, this will be used as the display area that contains the displayed image. Any
:class:`ViewBox <pyqtgraph.ViewBox>`, :class:`PlotItem <pyqtgraph.PlotItem>`, or other compatible object is
acceptable. Note: to display axis ticks inside the ImageView, instantiate it with a PlotItem instance as its
view::
pg.ImageView(view=pg.PlotItem())
imageItem : ImageItem
If specified, this object will be used to display the image. Must be an instance of ImageItem or other
compatible object.
levelMode : str
See the *levelMode* argument to :func:`HistogramLUTItem.__init__() <pyqtgraph.HistogramLUTItem.__init__>`
discreteTimeLine : bool
Whether to snap to xvals / frame numbers when interacting with the timeline position.
roi : ROI
If specified, this object is used as ROI for the plot feature. Must be an instance of ROI.
normRoi : ROI
If specified, this object is used as ROI for the normalization feature. Must be an instance of ROI.
"""
QtWidgets.QWidget.__init__(self, parent, *args)
self._imageLevels = None # [(min, max), ...] per channel image metrics
self.levelMin = None # min / max levels across all channels
self.levelMax = None
self.name = name
self.image = None
self.axes = {}
self.imageDisp = None
self.ui = ui_template.Ui_Form()
self.ui.setupUi(self)
self.scene = self.ui.graphicsView.scene()
self.discreteTimeLine = discreteTimeLine
self.ui.histogram.setLevelMode(levelMode)
self.ignoreTimeLine = False
if view is None:
self.view = ViewBox()
else:
self.view = view
self.ui.graphicsView.setCentralItem(self.view)
self.view.setAspectLocked(True)
self.view.invertY()
self.menu = None
self.ui.normGroup.hide()
if roi is None:
self.roi = PlotROI(10)
else:
self.roi = roi
self.roi.setZValue(20)
self.view.addItem(self.roi)
self.roi.hide()
if normRoi is None:
self.normRoi = PlotROI(10)
self.normRoi.setPen('y')
else:
self.normRoi = normRoi
self.normRoi.setZValue(20)
self.view.addItem(self.normRoi)
self.normRoi.hide()
self.roiCurves = []
self.timeLine = InfiniteLine(0, movable=True)
if getConfigOption('background')=='w':
self.timeLine.setPen((20, 80,80, 200))
else:
self.timeLine.setPen((255, 255, 0, 200))
self.timeLine.setZValue(1)
self.ui.roiPlot.addItem(self.timeLine)
self.ui.splitter.setSizes([self.height()-35, 35])
# init imageItem and histogram
if imageItem is None:
self.imageItem = ImageItem()
else:
self.imageItem = imageItem
self.setImage(imageItem.image, autoRange=False, autoLevels=False, transform=imageItem.transform())
self.view.addItem(self.imageItem)
self.currentIndex = 0
self.ui.histogram.setImageItem(self.imageItem)
self.ui.histogram.setLevelMode(levelMode)
# make splitter an unchangeable small grey line:
s = self.ui.splitter
s.handle(1).setEnabled(False)
s.setStyleSheet("QSplitter::handle{background-color: grey}")
s.setHandleWidth(2)
self.ui.roiPlot.hideAxis('left')
self.frameTicks = VTickGroup(yrange=[0.8, 1], pen=0.4)
self.ui.roiPlot.addItem(self.frameTicks, ignoreBounds=True)
self.keysPressed = {}
self.playTimer = QtCore.QTimer()
self.playRate = 0
self._pausedPlayRate = None
self.fps = 1 # 1 Hz by default
self.lastPlayTime = 0
self.normRgn = LinearRegionItem()
self.normRgn.setZValue(0)
self.ui.roiPlot.addItem(self.normRgn)
self.normRgn.hide()
## wrap functions from view box
for fn in ['addItem', 'removeItem']:
setattr(self, fn, getattr(self.view, fn))
## wrap functions from histogram
for fn in ['setHistogramRange', 'autoHistogramRange', 'getLookupTable', 'getLevels']:
setattr(self, fn, getattr(self.ui.histogram, fn))
self.timeLine.sigPositionChanged.connect(self.timeLineChanged)
self.ui.roiBtn.clicked.connect(self.roiClicked)
self.roi.sigRegionChanged.connect(self.roiChanged)
#self.ui.normBtn.toggled.connect(self.normToggled)
self.ui.menuBtn.clicked.connect(self.menuClicked)
self.ui.normDivideRadio.clicked.connect(self.normRadioChanged)
self.ui.normSubtractRadio.clicked.connect(self.normRadioChanged)
self.ui.normOffRadio.clicked.connect(self.normRadioChanged)
self.ui.normROICheck.clicked.connect(self.updateNorm)
self.ui.normFrameCheck.clicked.connect(self.updateNorm)
self.ui.normTimeRangeCheck.clicked.connect(self.updateNorm)
self.playTimer.timeout.connect(self.timeout)
self.normProxy = SignalProxy(
self.normRgn.sigRegionChanged,
slot=self.updateNorm,
threadSafe=False,
)
self.normRoi.sigRegionChangeFinished.connect(self.updateNorm)
self.ui.roiPlot.registerPlot(self.name + '_ROI')
self.view.register(self.name)
self.noRepeatKeys = [
QtCore.Qt.Key.Key_Right,
QtCore.Qt.Key.Key_Left,
QtCore.Qt.Key.Key_Up,
QtCore.Qt.Key.Key_Down,
QtCore.Qt.Key.Key_PageUp,
QtCore.Qt.Key.Key_PageDown,
]
self.roiClicked() ## initialize roi plot to correct shape / visibility
def setImage(
self,
img,
autoRange=True,
autoLevels=True,
levels=None,
axes=None,
xvals=None,
pos=None,
scale=None,
transform=None,
autoHistogramRange=True,
levelMode=None,
):
"""
Set the image to be displayed in the widget.
Parameters
----------
img : np.ndarray
The image to be displayed. See :func:`ImageItem.setImage` and *notes* below.
autoRange : bool
Whether to scale/pan the view to fit the image.
autoLevels : bool
Whether to update the white/black levels to fit the image.
levels : tuple
(min, max) white and black level values to use.
axes : dict
Dictionary indicating the interpretation for each axis. This is only needed to override the default guess.
Format is::
{'t':0, 'x':1, 'y':2, 'c':3};
xvals : np.ndarray
1D array of values corresponding to the first axis in a 3D image. For video, this array should contain
the time of each frame.
pos
Change the position of the displayed image
scale
Change the scale of the displayed image
transform
Set the transform of the displayed image. This option overrides *pos* and *scale*.
autoHistogramRange : bool
If True, the histogram y-range is automatically scaled to fit the image data.
levelMode : str
If specified, this sets the user interaction mode for setting image levels. Options are 'mono',
which provides a single level control for all image channels, and 'rgb' or 'rgba', which provide
individual controls for each channel.
Notes
-----
For backward compatibility, image data is assumed to be in column-major order (column, row).
However, most image data is stored in row-major order (row, column) and will need to be
transposed before calling setImage()::
imageview.setImage(imagedata.T)
This requirement can be changed by the ``imageAxisOrder``
:ref:`global configuration option <apiref_config>`.
"""
profiler = debug.Profiler()
if not isinstance(img, np.ndarray):
required = ['dtype', 'max', 'min', 'ndim', 'shape', 'size']
if not all(hasattr(img, attr) for attr in required):
raise TypeError("Image must be NumPy array or any object "
"that provides compatible attributes/methods:\n"
" %s" % str(required))
self.image = img
self.imageDisp = None
if levelMode is not None:
self.ui.histogram.setLevelMode(levelMode)
profiler()
if axes is None:
x,y = (0, 1) if self.imageItem.axisOrder == 'col-major' else (1, 0)
if img.ndim == 2:
self.axes = {'t': None, 'x': x, 'y': y, 'c': None}
elif img.ndim == 3:
# Ambiguous case; make a guess
if img.shape[2] <= 4:
self.axes = {'t': None, 'x': x, 'y': y, 'c': 2}
else:
self.axes = {'t': 0, 'x': x+1, 'y': y+1, 'c': None}
elif img.ndim == 4:
# Even more ambiguous; just assume the default
self.axes = {'t': 0, 'x': x+1, 'y': y+1, 'c': 3}
else:
raise Exception("Can not interpret image with dimensions %s" % (str(img.shape)))
elif isinstance(axes, dict):
self.axes = axes.copy()
elif isinstance(axes, list) or isinstance(axes, tuple):
self.axes = {}
for i in range(len(axes)):
self.axes[axes[i]] = i
else:
raise Exception("Can not interpret axis specification %s. Must be like {'t': 2, 'x': 0, 'y': 1} or ('t', 'x', 'y', 'c')" % (str(axes)))
for x in ['t', 'x', 'y', 'c']:
self.axes[x] = self.axes.get(x, None)
axes = self.axes
if xvals is not None:
self.tVals = xvals
elif axes['t'] is not None:
self.tVals = np.arange(img.shape[axes['t']])
profiler()
self.currentIndex = 0
self.updateImage(autoHistogramRange=autoHistogramRange)
if levels is None and autoLevels:
self.autoLevels()
if levels is not None: ## this does nothing since getProcessedImage sets these values again.
self.setLevels(*levels)
if self.ui.roiBtn.isChecked():
self.roiChanged()
profiler()
if self.axes['t'] is not None:
self.ui.roiPlot.setXRange(self.tVals.min(), self.tVals.max())
self.frameTicks.setXVals(self.tVals)
self.timeLine.setValue(0)
if len(self.tVals) > 1:
start = self.tVals.min()
stop = self.tVals.max() + abs(self.tVals[-1] - self.tVals[0]) * 0.02
elif len(self.tVals) == 1:
start = self.tVals[0] - 0.5
stop = self.tVals[0] + 0.5
else:
start = 0
stop = 1
for s in [self.timeLine, self.normRgn]:
s.setBounds([start, stop])
profiler()
if transform is None:
transform = QtGui.QTransform()
# note that the order of transform is
# scale followed by translate
if pos is not None:
transform.translate(*pos)
if scale is not None:
transform.scale(*scale)
self.imageItem.setTransform(transform)
profiler()
if autoRange:
self.autoRange()
self.roiClicked()
profiler()
def clear(self):
self.image = None
self.imageItem.clear()
def play(self, rate=None):
"""Begin automatically stepping frames forward at the given rate (in fps).
This can also be accessed by pressing the spacebar."""
if rate is None:
rate = self._pausedPlayRate or self.fps
if rate == 0 and self.playRate not in (None, 0):
self._pausedPlayRate = self.playRate
self.playRate = rate
if rate == 0:
self.playTimer.stop()
return
self.lastPlayTime = perf_counter()
if not self.playTimer.isActive():
self.playTimer.start(abs(int(1000/rate)))
def togglePause(self):
if self.playTimer.isActive():
self.play(0)
elif self.playRate == 0:
if self._pausedPlayRate is not None:
fps = self._pausedPlayRate
else:
fps = (self.nframes() - 1) / (self.tVals[-1] - self.tVals[0])
self.play(fps)
else:
self.play(self.playRate)
def setHistogramLabel(self, text=None, **kwargs):
"""
Set the label text of the histogram axis similar to
:func:`AxisItem.setLabel() <pyqtgraph.AxisItem.setLabel>`
"""
a = self.ui.histogram.axis
a.setLabel(text, **kwargs)
if text == '':
a.showLabel(False)
self.ui.histogram.setMinimumWidth(135)
def nframes(self):
"""
Returns
-------
int
The number of frames in the image data.
"""
if self.image is None:
return 0
elif self.axes['t'] is not None:
return self.image.shape[self.axes['t']]
return 1
def autoLevels(self):
"""Set the min/max intensity levels automatically to match the image data."""
self.setLevels(rgba=self._imageLevels)
def setLevels(self, *args, **kwds):
"""Set the min/max (bright and dark) levels.
See :func:`HistogramLUTItem.setLevels <pyqtgraph.HistogramLUTItem.setLevels>`.
"""
self.ui.histogram.setLevels(*args, **kwds)
def autoRange(self):
"""Auto scale and pan the view around the image such that the image fills the view."""
self.getProcessedImage()
self.view.autoRange()
def getProcessedImage(self):
"""Returns the image data after it has been processed by any normalization options in use.
"""
if self.imageDisp is None:
image = self.normalize(self.image)
self.imageDisp = image
self._imageLevels = self.quickMinMax(self.imageDisp)
self.levelMin = min([level[0] for level in self._imageLevels])
self.levelMax = max([level[1] for level in self._imageLevels])
return self.imageDisp
def close(self):
"""Closes the widget nicely, making sure to clear the graphics scene and release memory."""
self.clear()
self.imageDisp = None
self.imageItem.setParent(None)
super(ImageView, self).close()
self.setParent(None)
def keyPressEvent(self, ev):
if not self.hasTimeAxis():
super().keyPressEvent(ev)
return
if ev.key() == QtCore.Qt.Key.Key_Space:
self.togglePause()
ev.accept()
elif ev.key() == QtCore.Qt.Key.Key_Home:
self.setCurrentIndex(0)
self.play(0)
ev.accept()
elif ev.key() == QtCore.Qt.Key.Key_End:
self.setCurrentIndex(self.nframes()-1)
self.play(0)
ev.accept()
elif ev.key() in self.noRepeatKeys:
ev.accept()
if ev.isAutoRepeat():
return
self.keysPressed[ev.key()] = 1
self.evalKeyState()
else:
super().keyPressEvent(ev)
def keyReleaseEvent(self, ev):
if not self.hasTimeAxis():
super().keyReleaseEvent(ev)
return
if ev.key() in [QtCore.Qt.Key.Key_Space, QtCore.Qt.Key.Key_Home, QtCore.Qt.Key.Key_End]:
ev.accept()
elif ev.key() in self.noRepeatKeys:
ev.accept()
if ev.isAutoRepeat():
return
try:
del self.keysPressed[ev.key()]
except:
self.keysPressed = {}
self.evalKeyState()
else:
super().keyReleaseEvent(ev)
def evalKeyState(self):
if len(self.keysPressed) == 1:
key = list(self.keysPressed.keys())[0]
if key == QtCore.Qt.Key.Key_Right:
self.play(20)
self.jumpFrames(1)
# effectively pause playback for 0.2 s
self.lastPlayTime = perf_counter() + 0.2
elif key == QtCore.Qt.Key.Key_Left:
self.play(-20)
self.jumpFrames(-1)
self.lastPlayTime = perf_counter() + 0.2
elif key == QtCore.Qt.Key.Key_Up:
self.play(-100)
elif key == QtCore.Qt.Key.Key_Down:
self.play(100)
elif key == QtCore.Qt.Key.Key_PageUp:
self.play(-1000)
elif key == QtCore.Qt.Key.Key_PageDown:
self.play(1000)
else:
self.play(0)
@QtCore.Slot()
def timeout(self):
now = perf_counter()
dt = now - self.lastPlayTime
if dt < 0:
return
n = int(self.playRate * dt)
if n != 0:
self.lastPlayTime += (float(n)/self.playRate)
if self.currentIndex+n > self.image.shape[self.axes['t']]:
self.play(0)
self.jumpFrames(n)
def setCurrentIndex(self, ind):
"""Set the currently displayed frame index."""
index = fn.clip_scalar(ind, 0, self.nframes()-1)
self.currentIndex = index
self.updateImage()
self.ignoreTimeLine = True
# Implicitly call timeLineChanged
self.timeLine.setValue(self.tVals[index])
self.ignoreTimeLine = False
def jumpFrames(self, n):
"""Move video frame ahead n frames (may be negative)"""
if self.axes['t'] is not None:
self.setCurrentIndex(self.currentIndex + n)
@QtCore.Slot()
def normRadioChanged(self):
self.imageDisp = None
self.updateImage()
self.autoLevels()
self.roiChanged()
self.sigProcessingChanged.emit(self)
@QtCore.Slot()
def updateNorm(self):
if self.ui.normTimeRangeCheck.isChecked():
self.normRgn.show()
else:
self.normRgn.hide()
if self.ui.normROICheck.isChecked():
self.normRoi.show()
else:
self.normRoi.hide()
if not self.ui.normOffRadio.isChecked():
self.imageDisp = None
self.updateImage()
self.autoLevels()
self.roiChanged()
self.sigProcessingChanged.emit(self)
@QtCore.Slot(bool)
def normToggled(self, b):
self.ui.normGroup.setVisible(b)
self.normRoi.setVisible(b and self.ui.normROICheck.isChecked())
self.normRgn.setVisible(b and self.ui.normTimeRangeCheck.isChecked())
def hasTimeAxis(self):
return 't' in self.axes and self.axes['t'] is not None
@QtCore.Slot()
def roiClicked(self):
showRoiPlot = False
if self.ui.roiBtn.isChecked():
showRoiPlot = True
self.roi.show()
self.ui.roiPlot.setMouseEnabled(True, True)
self.ui.splitter.setSizes([int(self.height()*0.6), int(self.height()*0.4)])
self.ui.splitter.handle(1).setEnabled(True)
self.roiChanged()
for c in self.roiCurves:
c.show()
self.ui.roiPlot.showAxis('left')
else:
self.roi.hide()
self.ui.roiPlot.setMouseEnabled(False, False)
for c in self.roiCurves:
c.hide()
self.ui.roiPlot.hideAxis('left')
if self.hasTimeAxis():
showRoiPlot = True
mn = self.tVals.min()
mx = self.tVals.max()
self.ui.roiPlot.setXRange(mn, mx, padding=0.01)
self.timeLine.show()
self.timeLine.setBounds([mn, mx])
if not self.ui.roiBtn.isChecked():
self.ui.splitter.setSizes([self.height()-35, 35])
self.ui.splitter.handle(1).setEnabled(False)
else:
self.timeLine.hide()
self.ui.roiPlot.setVisible(showRoiPlot)
@QtCore.Slot()
def roiChanged(self):
# Extract image data from ROI
if self.image is None:
return
image = self.getProcessedImage()
# getArrayRegion axes should be (x, y) of data array for col-major,
# (y, x) for row-major
# can't just transpose input because ROI is axisOrder aware
colmaj = self.imageItem.axisOrder == 'col-major'
if colmaj:
axes = (self.axes['x'], self.axes['y'])
else:
axes = (self.axes['y'], self.axes['x'])
data, coords = self.roi.getArrayRegion(
image.view(np.ndarray), img=self.imageItem, axes=axes,
returnMappedCoords=True)
if data is None:
return
# Convert extracted data into 1D plot data
if self.axes['t'] is None:
# Average across y-axis of ROI
data = data.mean(axis=self.axes['y'])
# get coordinates along x axis of ROI mapped to range (0, roiwidth)
if colmaj:
coords = coords[:, :, 0] - coords[:, 0:1, 0]
else:
coords = coords[:, 0, :] - coords[:, 0, 0:1]
xvals = (coords**2).sum(axis=0) ** 0.5
else:
# Average data within entire ROI for each frame
data = data.mean(axis=axes)
xvals = self.tVals
# Handle multi-channel data
if data.ndim == 1:
plots = [(xvals, data, 'w')]
if data.ndim == 2:
if data.shape[1] == 1:
colors = 'w'
else:
colors = 'rgbw'
plots = []
for i in range(data.shape[1]):
d = data[:,i]
plots.append((xvals, d, colors[i]))
# Update plot line(s)
while len(plots) < len(self.roiCurves):
c = self.roiCurves.pop()
c.scene().removeItem(c)
while len(plots) > len(self.roiCurves):
self.roiCurves.append(self.ui.roiPlot.plot())
for i in range(len(plots)):
x, y, p = plots[i]
self.roiCurves[i].setData(x, y, pen=p)
def quickMinMax(self, data):
"""
Estimate the min/max values of *data* by subsampling.
Returns [(min, max), ...] with one item per channel
"""
while data.size > 1e6:
ax = np.argmax(data.shape)
sl = [slice(None)] * data.ndim
sl[ax] = slice(None, None, 2)
data = data[tuple(sl)]
cax = self.axes['c']
if cax is None:
if data.size == 0:
return [(0, 0)]
return [(float(nanmin(data)), float(nanmax(data)))]
else:
if data.size == 0:
return [(0, 0)] * data.shape[-1]
return [(float(nanmin(data.take(i, axis=cax))),
float(nanmax(data.take(i, axis=cax)))) for i in range(data.shape[-1])]
def normalize(self, image):
"""
Process *image* using the normalization options configured in the
control panel.
This can be repurposed to process any data through the same filter.
"""
if self.ui.normOffRadio.isChecked():
return image
div = self.ui.normDivideRadio.isChecked()
norm = image.view(np.ndarray).copy()
#if div:
#norm = ones(image.shape)
#else:
#norm = zeros(image.shape)
if div:
norm = norm.astype(np.float32)
if self.ui.normTimeRangeCheck.isChecked() and image.ndim == 3:
(sind, start) = self.timeIndex(self.normRgn.lines[0])
(eind, end) = self.timeIndex(self.normRgn.lines[1])
#print start, end, sind, eind
n = image[sind:eind+1].mean(axis=0, keepdims=True)
if div:
norm /= n
else:
norm -= n
if self.ui.normFrameCheck.isChecked() and image.ndim == 3:
n = image.mean(axis=(1, 2), keepdims=True)
if div:
norm /= n
else:
norm -= n
if self.ui.normROICheck.isChecked() and image.ndim == 3:
n = self.normRoi.getArrayRegion(norm, self.imageItem, (1, 2)).mean(axis=1).mean(axis=1)
n = n[:,np.newaxis,np.newaxis]
#print start, end, sind, eind
if div:
norm /= n
else:
norm -= n
return norm
@QtCore.Slot()
def timeLineChanged(self):
if not self.ignoreTimeLine:
self.play(0)
(ind, time) = self.timeIndex(self.timeLine)
if ind != self.currentIndex:
self.currentIndex = ind
self.updateImage()
if self.discreteTimeLine:
with fn.SignalBlock(self.timeLine.sigPositionChanged, self.timeLineChanged):
if self.tVals is not None:
self.timeLine.setPos(self.tVals[ind])
else:
self.timeLine.setPos(ind)
self.sigTimeChanged.emit(ind, time)
def updateImage(self, autoHistogramRange=True):
## Redraw image on screen
if self.image is None:
return
image = self.getProcessedImage()
if autoHistogramRange:
self.ui.histogram.setHistogramRange(self.levelMin, self.levelMax)
# Transpose image into order expected by ImageItem
if self.imageItem.axisOrder == 'col-major':
axorder = ['t', 'x', 'y', 'c']
else:
axorder = ['t', 'y', 'x', 'c']
axorder = [self.axes[ax] for ax in axorder if self.axes[ax] is not None]
image = image.transpose(axorder)
# Select time index
if self.axes['t'] is not None:
self.ui.roiPlot.show()
image = image[self.currentIndex]
self.imageItem.updateImage(image)
def timeIndex(self, slider):
"""
Returns
-------
int
The index of the frame closest to the timeline slider.
float
The time value of the slider.
"""
if not self.hasTimeAxis():
return 0, 0.0
t = slider.value()
xv = self.tVals
if xv is None:
ind = int(t)
else:
if len(xv) < 2:
return 0, 0.0
inds = np.argwhere(xv <= t)
if len(inds) < 1:
return 0, t
ind = inds[-1, 0]
return ind, t
def getView(self):
"""Return the ViewBox (or other compatible object) which displays the ImageItem"""
return self.view
def getImageItem(self):
"""Return the ImageItem for this ImageView."""
return self.imageItem
def getRoiPlot(self):
"""Return the ROI PlotWidget for this ImageView"""
return self.ui.roiPlot
def getHistogramWidget(self):
"""Return the HistogramLUTWidget for this ImageView"""
return self.ui.histogram
def export(self, fileName):
"""
Export data from the ImageView to a file, or to a stack of files if
the data is 3D. Saving an image stack will result in index numbers
being added to the file name. Images are saved as they would appear
onscreen, with levels and lookup table applied.
"""
img = self.getProcessedImage()
if self.hasTimeAxis():
base, ext = os.path.splitext(fileName)
fmt = "%%s%%0%dd%%s" % int(log10(img.shape[0])+1)
for i in range(img.shape[0]):
self.imageItem.setImage(img[i], autoLevels=False)
self.imageItem.save(fmt % (base, i, ext))
self.updateImage()
else:
self.imageItem.save(fileName)
@QtCore.Slot()
def exportClicked(self):
fileName, _ = QtWidgets.QFileDialog.getSaveFileName()
if not fileName:
return
self.export(fileName)
def buildMenu(self):
self.menu = QtWidgets.QMenu()
self.normAction = QtGui.QAction(translate("ImageView", "Normalization"), self.menu)
self.normAction.setCheckable(True)
self.normAction.toggled.connect(self.normToggled)
self.menu.addAction(self.normAction)
self.exportAction = QtGui.QAction(translate("ImageView", "Export"), self.menu)
self.exportAction.triggered.connect(self.exportClicked)
self.menu.addAction(self.exportAction)
@QtCore.Slot()
def menuClicked(self):
if self.menu is None:
self.buildMenu()
self.menu.popup(QtGui.QCursor.pos())
def setColorMap(self, colormap):
"""Set the color map.
Parameters
----------
colormap : ColorMap
The ColorMap to use for coloring images.
"""
self.ui.histogram.gradient.setColorMap(colormap)
@addGradientListToDocstring()
def setPredefinedGradient(self, name):
"""Set one of the gradients defined in :class:`GradientEditorItem`.
Currently available gradients are:
"""
self.ui.histogram.gradient.loadPreset(name)
|
ImageView
|
python
|
has2k1__plotnine
|
plotnine/labels.py
|
{
"start": 2344,
"end": 2572
}
|
class ____(labs):
"""
Label/name for the y aesthetic
Parameters
----------
name :
y aesthetic label i.e. y-axis label
"""
def __init__(self, label: str):
super().__init__(y=label)
|
ylab
|
python
|
TheAlgorithms__Python
|
ciphers/polybius.py
|
{
"start": 365,
"end": 3084
}
|
class ____:
def __init__(self) -> None:
self.SQUARE = np.array(SQUARE)
def letter_to_numbers(self, letter: str) -> np.ndarray:
"""
Return the pair of numbers that represents the given letter in the
polybius square
>>> np.array_equal(PolybiusCipher().letter_to_numbers('a'), [1,1])
True
>>> np.array_equal(PolybiusCipher().letter_to_numbers('u'), [4,5])
True
"""
index1, index2 = np.where(letter == self.SQUARE)
indexes = np.concatenate([index1 + 1, index2 + 1])
return indexes
def numbers_to_letter(self, index1: int, index2: int) -> str:
"""
Return the letter corresponding to the position [index1, index2] in
the polybius square
>>> PolybiusCipher().numbers_to_letter(4, 5) == "u"
True
>>> PolybiusCipher().numbers_to_letter(1, 1) == "a"
True
"""
return self.SQUARE[index1 - 1, index2 - 1]
def encode(self, message: str) -> str:
"""
Return the encoded version of message according to the polybius cipher
>>> PolybiusCipher().encode("test message") == "44154344 32154343112215"
True
>>> PolybiusCipher().encode("Test Message") == "44154344 32154343112215"
True
"""
message = message.lower()
message = message.replace("j", "i")
encoded_message = ""
for letter_index in range(len(message)):
if message[letter_index] != " ":
numbers = self.letter_to_numbers(message[letter_index])
encoded_message = encoded_message + str(numbers[0]) + str(numbers[1])
elif message[letter_index] == " ":
encoded_message = encoded_message + " "
return encoded_message
def decode(self, message: str) -> str:
"""
Return the decoded version of message according to the polybius cipher
>>> PolybiusCipher().decode("44154344 32154343112215") == "test message"
True
>>> PolybiusCipher().decode("4415434432154343112215") == "testmessage"
True
"""
message = message.replace(" ", " ")
decoded_message = ""
for numbers_index in range(int(len(message) / 2)):
if message[numbers_index * 2] != " ":
index1 = message[numbers_index * 2]
index2 = message[numbers_index * 2 + 1]
letter = self.numbers_to_letter(int(index1), int(index2))
decoded_message = decoded_message + letter
elif message[numbers_index * 2] == " ":
decoded_message = decoded_message + " "
return decoded_message
|
PolybiusCipher
|
python
|
encode__django-rest-framework
|
tests/test_validation.py
|
{
"start": 3071,
"end": 3651
}
|
class ____(TestCase):
"""
If serializer was initialized with invalid data (None or non dict-like), it
should avoid validation layer (validate_<field> and validate methods)
"""
def test_serializer_errors_has_only_invalid_data_error(self):
serializer = ValidationSerializer(data='invalid data')
assert not serializer.is_valid()
assert serializer.errors == {
'non_field_errors': [
'Invalid data. Expected a dictionary, but got str.',
]
}
# regression tests for issue: 1493
|
TestAvoidValidation
|
python
|
modin-project__modin
|
modin/tests/pandas/native_df_interoperability/test_compiler_caster.py
|
{
"start": 10178,
"end": 27769
}
|
class ____(BaseTestAutoMover):
"""Represents a local query compiler that prefers small data."""
# Operations are cheap on this engine for small data, but there is an upper bound
_MAX_SIZE_THIS_ENGINE_CAN_HANDLE = BIG_DATA_CLOUD_MIN_NUM_ROWS
_OPERATION_PER_ROW_OVERHEAD = 1
def __init__(self, pandas_frame):
super().__init__(pandas_frame)
def get_backend(self) -> str:
return "Small_Data_Local"
@classmethod
def max_cost(cls):
return QCCoercionCost.COST_IMPOSSIBLE * 10
def register_backend(name, qc):
class TestCasterIO(BaseIO):
_should_warn_on_default_to_pandas: bool = False
query_compiler_cls = qc
class TestCasterFactory(BaseFactory):
@classmethod
def prepare(cls):
cls.io_cls = TestCasterIO
TestCasterFactory.prepare()
factory_name = f"{name}OnNativeFactory"
setattr(factories, factory_name, TestCasterFactory)
Engine.add_option(name)
Backend.register_backend(name, Execution(name, "Native"))
ALL_BACKENDS = {
"Pico": PicoQC,
"Cluster": ClusterQC,
"Cloud": CloudQC,
"Cloud_High_Self": CloudQCHighSelf,
"Local_Machine": LocalMachineQC,
"Adversarial": AdversarialQC,
"Eager": OmniscientEagerQC,
"Lazy": OmniscientLazyQC,
"Test_Casting_Default": DefaultQC,
"Test_Casting_Default_2": DefaultQC2,
"Big_Data_Cloud": CloudForBigDataQC,
"Small_Data_Local": LocalForSmallDataQC,
}
for backend, qc in ALL_BACKENDS.items():
register_backend(backend, qc)
DEFAULT_TEST_BACKENDS = (
"Pico",
"Cluster",
"Cloud",
"Cloud_High_Self",
"Local_Machine",
"Lazy",
)
@pytest.fixture(autouse=True)
def turn_on_auto_switch_backend():
with config_context(AutoSwitchBackend=True):
yield
@contextlib.contextmanager
def backend_test_context(
*, test_backend: Optional[str] = None, choices: Optional[tuple] = None
) -> Iterator[None]:
if choices is None:
# Consider only a select set custom-defined test backends by default for easier testing.
# This is necessary because n-ary operations consider _all_ possible active backends, so
# we may observe unexpected behavior if too many backends are activated at once.
# If a QC is explicitly created for an inactive backend, the QC calculator should still
# be able to accept it.
choices = DEFAULT_TEST_BACKENDS
if test_backend is None:
test_backend = choices[0]
old_default_backend = Backend.get()
old_backend_choices = Backend.get_active_backends()
try:
Backend.set_active_backends(choices)
Backend.put(test_backend)
yield
finally:
Backend.set_active_backends(old_backend_choices)
Backend.put(old_default_backend)
@pytest.fixture()
def cloud_df():
return pd.DataFrame(query_compiler=CloudQC(pandas.DataFrame([0, 1, 2])))
@pytest.fixture()
def cloud_high_self_df():
return pd.DataFrame(query_compiler=CloudQCHighSelf(pandas.DataFrame([0, 1, 2])))
@pytest.fixture()
def cluster_df():
return pd.DataFrame(query_compiler=ClusterQC(pandas.DataFrame([0, 1, 2])))
@pytest.fixture()
def local_df():
return pd.DataFrame(query_compiler=LocalMachineQC(pandas.DataFrame([0, 1, 2])))
@pytest.fixture()
def pico_df():
return pd.DataFrame(query_compiler=PicoQC(pandas.DataFrame([0, 1, 2])))
@pytest.fixture()
def adversarial_df():
return pd.DataFrame(query_compiler=AdversarialQC(pandas.DataFrame([0, 1, 2])))
@pytest.fixture()
def eager_df():
return pd.DataFrame(query_compiler=OmniscientEagerQC(pandas.DataFrame([0, 1, 2])))
@pytest.fixture()
def lazy_df():
return pd.DataFrame(query_compiler=OmniscientLazyQC(pandas.DataFrame([0, 1, 2])))
@pytest.fixture()
def default_df():
return pd.DataFrame(query_compiler=DefaultQC(pandas.DataFrame([0, 1, 2])))
@pytest.fixture()
def default2_df():
return pd.DataFrame(query_compiler=DefaultQC2(pandas.DataFrame([0, 1, 2])))
def test_two_same_backend(pico_df):
df3 = pd.concat([pico_df, pico_df], axis=1)
assert pico_df.get_backend() == "Pico"
assert df3.get_backend() == "Pico"
def test_cast_to_second_backend_with_concat(pico_df, cluster_df, caplog):
with caplog.at_level(level=logging.INFO, logger=DEFAULT_LOGGER_NAME):
# We have to copy the input dataframes because of inplace merging
df3 = pd.concat([pico_df.copy(), cluster_df.copy()], axis=1)
assert pico_df.get_backend() == "Pico"
assert cluster_df.get_backend() == "Cluster"
assert df3.get_backend() == "Cluster" # result should be on cluster
log_records = caplog.records
assert len(log_records) == 1
assert log_records[0].name == DEFAULT_LOGGER_NAME
assert log_records[0].levelno == logging.INFO
assert log_records[0].message.startswith(
"BackendCostCalculator results for pd.concat: "
)
def test_cast_to_second_backend_with_concat_uses_second_backend_api_override(
pico_df, cluster_df
):
register_pd_accessor(name="concat", backend="Cluster")(
lambda *args, **kwargs: "custom_concat_result"
)
# copy dataframes for concat to allow for in-place merging
assert (
pd.concat([pico_df.copy(), cluster_df.copy()], axis=1) == "custom_concat_result"
)
assert pico_df.get_backend() == "Pico"
assert cluster_df.get_backend() == "Cluster"
def test_moving_pico_to_cluster_in_place_calls_set_backend_only_once_github_issue_7490(
pico_df, cluster_df
):
with mock.patch.object(
pd.DataFrame, "set_backend", wraps=pico_df.set_backend
) as mock_set_backend:
pico_df.set_backend(cluster_df.get_backend(), inplace=True)
assert pico_df.get_backend() == "Cluster"
mock_set_backend.assert_called_once_with("Cluster", inplace=True)
def test_cast_to_second_backend_with___init__(pico_df, cluster_df):
df3 = pd.DataFrame({"pico": pico_df.iloc[:, 0], "cluster": cluster_df.iloc[:, 0]})
assert (
pico_df.get_backend() == "Pico"
) # pico stays despite in-place casting by iloc
assert cluster_df.get_backend() == "Cluster"
assert df3.get_backend() == "Cluster" # result should be on cluster
def test_cast_to_first_backend(pico_df, cluster_df):
df3 = pd.concat([cluster_df, pico_df], axis=1)
assert pico_df.get_backend() == "Cluster" # pico_df was cast in place by concat
assert cluster_df.get_backend() == "Cluster"
assert df3.get_backend() == cluster_df.get_backend() # result should be on cluster
def test_cast_to_first_backend_with_concat_uses_first_backend_api_override(
pico_df, cluster_df
):
register_pd_accessor(name="concat", backend="Cluster")(
lambda *args, **kwargs: "custom_concat_result"
)
assert pd.concat([cluster_df, pico_df], axis=1) == "custom_concat_result"
assert pico_df.get_backend() == "Cluster" # pico was cast in place by concat
assert cluster_df.get_backend() == "Cluster"
def test_cast_to_first_backend_with___init__(pico_df, cluster_df):
df3 = pd.DataFrame(
{
"cluster": cluster_df.iloc[:, 0],
"pico": pico_df.iloc[:, 0],
}
)
assert pico_df.get_backend() == "Pico" # Pico not cast in place by iloc
assert cluster_df.get_backend() == "Cluster"
assert df3.get_backend() == "Cluster" # result should be on cluster
def test_self_cost_causes_move(cloud_high_self_df, cluster_df):
"""
Test that ``self_cost`` is being properly considered.
Cost to stay on cloud_high_self is HIGH, but moving to cluster is MEDIUM.
Cost to stay on cluster is ZERO, and moving to cloud_high_self is MEDIUM.
With two dataframes, one on each backend, the total cost of using
``cloud_high_self`` as the final backend is:
``stay_cost(cloud_high_self) + move_cost(cluster->cloud_high_self)``
which is ``HIGH + MEDIUM``.
The total cost of using ``cluster`` as the final backend is:
``stay_cost(cluster) + move_cost(cloud_high_self->cluster)``
which is ``ZERO + MEDIUM``.
So we should select ``cluster``.
"""
result = pd.concat([cloud_high_self_df, cluster_df])
assert result.get_backend() == "Cluster"
result = pd.concat([cluster_df, cloud_high_self_df])
assert result.get_backend() == "Cluster"
@pytest.mark.parametrize(
"df1, df2, df3, df4, expected_result_backend",
[
# no-op
("cloud_df", "cloud_df", "cloud_df", "cloud_df", "Cloud"),
# moving all dfs to cloud is 1250, moving to cluster is 1000
# regardless of how they are ordered
("pico_df", "local_df", "cluster_df", "cloud_df", "Cluster"),
("cloud_df", "local_df", "cluster_df", "pico_df", "Cluster"),
("cloud_df", "cluster_df", "local_df", "pico_df", "Cluster"),
("cloud_df", "cloud_df", "local_df", "pico_df", "Cloud"),
# Still move everything to cloud
("pico_df", "pico_df", "pico_df", "cloud_df", "Cloud"),
("pico_df", "pico_df", "local_df", "cloud_df", "Cloud"),
],
)
def test_mixed_dfs(df1, df2, df3, df4, expected_result_backend, request):
df1 = request.getfixturevalue(df1)
df2 = request.getfixturevalue(df2)
df3 = request.getfixturevalue(df3)
df4 = request.getfixturevalue(df4)
if expected_result_backend is None:
with pytest.raises(ValueError):
pd.concat(axis=1, objs=[df1, df2, df3, df4])
else:
result = pd.concat(axis=1, objs=[df1, df2, df3, df4])
assert result.get_backend() == expected_result_backend
def test_adversarial_high(adversarial_df, cluster_df):
with pytest.raises(ValueError):
pd.concat([adversarial_df, cluster_df], axis=1)
def test_adversarial_low(adversarial_df, cloud_df):
with pytest.raises(ValueError):
pd.concat([adversarial_df, cloud_df], axis=1)
def test_two_two_qc_types_default_rhs(default_df, cluster_df):
# none of the query compilers know about each other here
# so we default to the caller
df3 = pd.concat([default_df, cluster_df], axis=1)
assert default_df.get_backend() == "Test_Casting_Default"
assert (
cluster_df.get_backend() == "Test_Casting_Default"
) # in place cast to default by concat
assert df3.get_backend() == default_df.get_backend() # should move to default
def test_two_two_qc_types_default_lhs(default_df, cluster_df):
# none of the query compilers know about each other here
# so we default to the caller
df3 = pd.concat([cluster_df, default_df], axis=1)
assert default_df.get_backend() == "Cluster" # in place cast to Cluster by concat
assert cluster_df.get_backend() == "Cluster"
assert df3.get_backend() == cluster_df.get_backend() # should move to cluster
def test_two_two_qc_types_default_2_rhs(default_df, cloud_df):
# cloud knows a bit about costing; so we prefer moving to there
df3 = pd.concat([default_df, cloud_df], axis=1)
assert default_df.get_backend() == "Cloud" # inplace cast to Cloud by concat
assert cloud_df.get_backend() == "Cloud"
assert df3.get_backend() == cloud_df.get_backend() # should move to cloud
def test_two_two_qc_types_default_2_lhs(default_df, cloud_df):
# cloud knows a bit about costing; so we prefer moving to there
df3 = pd.concat([cloud_df, default_df], axis=1)
assert default_df.get_backend() == "Cloud" # inplace cast to Cloud by concat
assert cloud_df.get_backend() == "Cloud"
assert df3.get_backend() == cloud_df.get_backend() # should move to cloud
def test_default_to_caller(default_df, default2_df):
# No qc knows anything; default to caller
df3 = pd.concat([default_df, default2_df], axis=1)
assert df3.get_backend() == default_df.get_backend() # should stay on caller
df3 = pd.concat([default2_df, default_df], axis=1)
assert df3.get_backend() == default2_df.get_backend() # should stay on caller
df3 = pd.concat([default_df, default_df], axis=1)
assert df3.get_backend() == default_df.get_backend() # no change
def test_no_qc_to_calculate():
calculator = BackendCostCalculator(
operation_arguments=MappingProxyType({}),
api_cls_name=None,
operation="operation0",
query_compilers=[],
preop_switch=False,
)
with pytest.raises(ValueError):
calculator.calculate()
def test_qc_default_self_cost(default_df, default2_df):
assert (
default_df._query_compiler.move_to_cost(
other_qc_type=type(default2_df._query_compiler),
api_cls_name=None,
operation="operation0",
arguments=MappingProxyType({}),
)
is None
)
assert (
default_df._query_compiler.move_to_cost(
other_qc_type=type(default_df._query_compiler),
api_cls_name=None,
operation="operation0",
arguments=MappingProxyType({}),
)
is QCCoercionCost.COST_ZERO
)
def test_qc_casting_changed_operation(pico_df, cloud_df):
pico_df1 = pico_df
cloud_df1 = cloud_df
native_cdf2 = cloud_df1._to_pandas()
native_pdf2 = pico_df1._to_pandas()
expected = native_cdf2 + native_pdf2
# test both directions
df_cast_to_rhs = pico_df1 + cloud_df1
df_cast_to_lhs = cloud_df1 + pico_df1
assert df_cast_to_rhs._to_pandas().equals(expected)
assert df_cast_to_lhs._to_pandas().equals(expected)
def test_qc_mixed_loc(pico_df, cloud_df):
pico_df1 = pico_df
cloud_df1 = cloud_df
assert pico_df1[pico_df1[0][0]][cloud_df1[0][1]] == 1
assert pico_df1[cloud_df1[0][0]][pico_df1[0][1]] == 1
assert cloud_df1[pico_df1[0][0]][pico_df1[0][1]] == 1
def test_merge_in_place(default_df, lazy_df, cloud_df):
# lazy_df tries to pawn off work on other engines
df = default_df.merge(lazy_df)
assert df.get_backend() is default_df.get_backend()
# Both arguments now have the same qc type
assert lazy_df.get_backend() is default_df.get_backend()
with config_context(BackendMergeCastInPlace=False):
lazy_df = lazy_df.move_to("Lazy")
cloud_df = cloud_df.move_to("Cloud")
df = cloud_df.merge(lazy_df)
assert df.get_backend() == cloud_df.get_backend()
assert lazy_df.get_backend() == "Lazy"
assert cloud_df.get_backend() == "Cloud"
def test_information_asymmetry(default_df, cloud_df, eager_df, lazy_df):
# normally, the default query compiler should be chosen
# here, but since eager knows about default, but not
# the other way around, eager has a special ability to
# control the directionality of the cast.
df = default_df.merge(eager_df)
assert df.get_backend() == eager_df.get_backend()
df = cloud_df.merge(eager_df)
assert df.get_backend() == eager_df.get_backend()
# lazy_df tries to pawn off work on other engines
df = default_df.merge(lazy_df)
assert df.get_backend() == default_df.get_backend()
df = cloud_df.merge(lazy_df)
assert df.get_backend() == cloud_df.get_backend()
def test_setitem_in_place_with_self_switching_backend(cloud_df, local_df):
local_df.iloc[1, 0] = cloud_df.iloc[1, 0] + local_df.iloc[1, 0]
# compute happens in cloud, but we have to make sure that we propagate the
# in-place update to the local_df
df_equals(
local_df,
pandas.DataFrame(
[
0,
2,
2,
]
),
)
assert local_df.get_backend() == "Local_Machine"
assert cloud_df.get_backend() == "Cloud"
@pytest.mark.parametrize("pin_local", [True, False], ids=["pinned", "unpinned"])
def test_switch_local_to_cloud_with_iloc___setitem__(local_df, cloud_df, pin_local):
if pin_local:
local_df = local_df.pin_backend()
local_df.iloc[:, 0] = cloud_df.iloc[:, 0] + 1
expected_pandas = local_df._to_pandas()
expected_pandas.iloc[:, 0] = cloud_df._to_pandas().iloc[:, 0] + 1
df_equals(local_df, expected_pandas)
assert local_df.get_backend() == "Local_Machine" if pin_local else "Cloud"
# This test should force the creation of a dataframe which
# is too large for the backend and verify that it stays there
# because there are no other options
def test_single_backend_merge_no_good_options():
with backend_test_context(
test_backend="Small_Data_Local",
choices=["Small_Data_Local"],
):
df1 = pd.DataFrame({"a": [1] * 100})
df1["two"] = pd.to_datetime(df1["a"])
assert df1.get_backend() == "Small_Data_Local"
def test_stay_or_move_evaluation(cloud_high_self_df, default_df):
default_cls = type(default_df._get_query_compiler())
cloud_cls = type(cloud_high_self_df._get_query_compiler())
empty_arguments = MappingProxyType({})
stay_cost = cloud_high_self_df._get_query_compiler().stay_cost(
"Series", "myop", arguments=empty_arguments
)
move_cost = cloud_high_self_df._get_query_compiler().move_to_cost(
default_cls, "Series", "myop", arguments=empty_arguments
)
if stay_cost > move_cost:
df = cloud_high_self_df.move_to("Test_Casting_Default")
else:
assert False
stay_cost = df._get_query_compiler().stay_cost(
"Series", "myop", arguments=empty_arguments
)
move_cost = df._get_query_compiler().move_to_cost(
cloud_cls, "Series", "myop", arguments=empty_arguments
)
assert stay_cost is not None
assert move_cost is None
def test_max_shape(cloud_df):
# default implementation matches df.shape
assert cloud_df.shape == cloud_df._query_compiler._max_shape()
|
LocalForSmallDataQC
|
python
|
tensorflow__tensorflow
|
tensorflow/python/data/kernel_tests/counter_test.py
|
{
"start": 1158,
"end": 1913
}
|
class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(start=3, step=4, expected_output=[[3, 7, 11]]) +
combinations.combine(start=0, step=-1, expected_output=[[0, -1, -2]]))
)
def testCounter(self, start, step, expected_output):
dataset = dataset_ops.Dataset.counter(start, step)
self.assertEqual(
[], dataset_ops.get_legacy_output_shapes(dataset).as_list())
self.assertEqual(dtypes.int64, dataset_ops.get_legacy_output_types(dataset))
get_next = self.getNext(dataset)
for expected in expected_output:
self.assertEqual(expected, self.evaluate(get_next()))
|
CounterTest
|
python
|
pyinstaller__pyinstaller
|
PyInstaller/building/makespec.py
|
{
"start": 6376,
"end": 35999
}
|
class ____:
def __init__(
self, datas, binaries, hiddenimports, collect_data, collect_binaries, collect_submodules, collect_all,
copy_metadata, recursive_copy_metadata
):
# Initialize with literal values - will be switched to preamble variable name later, if necessary
self.binaries = binaries or []
self.hiddenimports = hiddenimports or []
self.datas = datas or []
# Preamble content
self.content = []
# Import statements
if collect_data:
self._add_hookutil_import('collect_data_files')
if collect_binaries:
self._add_hookutil_import('collect_dynamic_libs')
if collect_submodules:
self._add_hookutil_import('collect_submodules')
if collect_all:
self._add_hookutil_import('collect_all')
if copy_metadata or recursive_copy_metadata:
self._add_hookutil_import('copy_metadata')
if self.content:
self.content += [''] # empty line to separate the section
# Variables
if collect_data or copy_metadata or collect_all or recursive_copy_metadata:
self._add_var('datas', self.datas)
self.datas = 'datas' # switch to variable
if collect_binaries or collect_all:
self._add_var('binaries', self.binaries)
self.binaries = 'binaries' # switch to variable
if collect_submodules or collect_all:
self._add_var('hiddenimports', self.hiddenimports)
self.hiddenimports = 'hiddenimports' # switch to variable
# Content - collect_data_files
for entry in collect_data:
self._add_collect_data(entry)
# Content - copy_metadata
for entry in copy_metadata:
self._add_copy_metadata(entry)
# Content - copy_metadata(..., recursive=True)
for entry in recursive_copy_metadata:
self._add_recursive_copy_metadata(entry)
# Content - collect_binaries
for entry in collect_binaries:
self._add_collect_binaries(entry)
# Content - collect_submodules
for entry in collect_submodules:
self._add_collect_submodules(entry)
# Content - collect_all
for entry in collect_all:
self._add_collect_all(entry)
# Merge
if self.content and self.content[-1] != '':
self.content += [''] # empty line
self.content = '\n'.join(self.content)
def _add_hookutil_import(self, name):
self.content += ['from PyInstaller.utils.hooks import {0}'.format(name)]
def _add_var(self, name, initial_value):
self.content += ['{0} = {1}'.format(name, initial_value)]
def _add_collect_data(self, name):
self.content += ['datas += collect_data_files(\'{0}\')'.format(name)]
def _add_copy_metadata(self, name):
self.content += ['datas += copy_metadata(\'{0}\')'.format(name)]
def _add_recursive_copy_metadata(self, name):
self.content += ['datas += copy_metadata(\'{0}\', recursive=True)'.format(name)]
def _add_collect_binaries(self, name):
self.content += ['binaries += collect_dynamic_libs(\'{0}\')'.format(name)]
def _add_collect_submodules(self, name):
self.content += ['hiddenimports += collect_submodules(\'{0}\')'.format(name)]
def _add_collect_all(self, name):
self.content += [
'tmp_ret = collect_all(\'{0}\')'.format(name),
'datas += tmp_ret[0]; binaries += tmp_ret[1]; hiddenimports += tmp_ret[2]'
]
def __add_options(parser):
"""
Add the `Makespec` options to a option-parser instance or a option group.
"""
g = parser.add_argument_group('What to generate')
g.add_argument(
"-D",
"--onedir",
dest="onefile",
action="store_false",
default=None,
help="Create a one-folder bundle containing an executable (default)",
)
g.add_argument(
"-F",
"--onefile",
dest="onefile",
action="store_true",
default=None,
help="Create a one-file bundled executable.",
)
g.add_argument(
"--specpath",
metavar="DIR",
help="Folder to store the generated spec file (default: current directory)",
)
g.add_argument(
"-n",
"--name",
help="Name to assign to the bundled app and spec file (default: first script's basename)",
)
g.add_argument(
"--contents-directory",
help="For onedir builds only, specify the name of the directory in which all supporting files (i.e. everything "
"except the executable itself) will be placed in. Use \".\" to re-enable old onedir layout without contents "
"directory.",
)
g = parser.add_argument_group('What to bundle, where to search')
g.add_argument(
'--add-data',
action=SourceDestAction,
dest='datas',
help="Additional data files or directories containing data files to be added to the application. The argument "
'value should be in form of "source:dest_dir", where source is the path to file (or directory) to be '
"collected, dest_dir is the destination directory relative to the top-level application directory, and both "
"paths are separated by a colon (:). To put a file in the top-level application directory, use . as a "
"dest_dir. This option can be used multiple times."
)
g.add_argument(
'--add-binary',
action=SourceDestAction,
dest="binaries",
help='Additional binary files to be added to the executable. See the ``--add-data`` option for the format. '
'This option can be used multiple times.',
)
g.add_argument(
"-p",
"--paths",
dest="pathex",
metavar="DIR",
action="append",
default=[],
help="A path to search for imports (like using PYTHONPATH). Multiple paths are allowed, separated by ``%s``, "
"or use this option multiple times. Equivalent to supplying the ``pathex`` argument in the spec file." %
repr(os.pathsep),
)
g.add_argument(
'--hidden-import',
'--hiddenimport',
action='append',
default=[],
metavar="MODULENAME",
dest='hiddenimports',
help='Name an import not visible in the code of the script(s). This option can be used multiple times.',
)
g.add_argument(
'--collect-submodules',
action="append",
default=[],
metavar="MODULENAME",
dest='collect_submodules',
help='Collect all submodules from the specified package or module. This option can be used multiple times.',
)
g.add_argument(
'--collect-data',
'--collect-datas',
action="append",
default=[],
metavar="MODULENAME",
dest='collect_data',
help='Collect all data from the specified package or module. This option can be used multiple times.',
)
g.add_argument(
'--collect-binaries',
action="append",
default=[],
metavar="MODULENAME",
dest='collect_binaries',
help='Collect all binaries from the specified package or module. This option can be used multiple times.',
)
g.add_argument(
'--collect-all',
action="append",
default=[],
metavar="MODULENAME",
dest='collect_all',
help='Collect all submodules, data files, and binaries from the specified package or module. This option can '
'be used multiple times.',
)
g.add_argument(
'--copy-metadata',
action="append",
default=[],
metavar="PACKAGENAME",
dest='copy_metadata',
help='Copy metadata for the specified package. This option can be used multiple times.',
)
g.add_argument(
'--recursive-copy-metadata',
action="append",
default=[],
metavar="PACKAGENAME",
dest='recursive_copy_metadata',
help='Copy metadata for the specified package and all its dependencies. This option can be used multiple '
'times.',
)
g.add_argument(
"--additional-hooks-dir",
action="append",
dest="hookspath",
default=[],
help="An additional path to search for hooks. This option can be used multiple times.",
)
g.add_argument(
'--runtime-hook',
action='append',
dest='runtime_hooks',
default=[],
help='Path to a custom runtime hook file. A runtime hook is code that is bundled with the executable and is '
'executed before any other code or module to set up special features of the runtime environment. This option '
'can be used multiple times.',
)
g.add_argument(
'--exclude-module',
dest='excludes',
action='append',
default=[],
help='Optional module or package (the Python name, not the path name) that will be ignored (as though it was '
'not found). This option can be used multiple times.',
)
g.add_argument(
'--key',
dest='key',
help=argparse.SUPPRESS,
type=removed_key_option,
)
g.add_argument(
'--splash',
dest='splash',
metavar="IMAGE_FILE",
help="(EXPERIMENTAL) Add an splash screen with the image IMAGE_FILE to the application. The splash screen can "
"display progress updates while unpacking.",
)
g = parser.add_argument_group('How to generate')
g.add_argument(
"-d",
"--debug",
# If this option is not specified, then its default value is an empty list (no debug options selected).
default=[],
# Note that ``nargs`` is omitted. This produces a single item not stored in a list, as opposed to a list
# containing one item, as per `nargs <https://docs.python.org/3/library/argparse.html#nargs>`_.
nargs=None,
# The options specified must come from this list.
choices=DEBUG_ALL_CHOICE + DEBUG_ARGUMENT_CHOICES,
# Append choice, rather than storing them (which would overwrite any previous selections).
action='append',
# Allow newlines in the help text; see the ``_SmartFormatter`` in ``__main__.py``.
help=(
"R|Provide assistance with debugging a frozen\n"
"application. This argument may be provided multiple\n"
"times to select several of the following options.\n"
"\n"
"- all: All three of the following options.\n"
"\n"
"- imports: specify the -v option to the underlying\n"
" Python interpreter, causing it to print a message\n"
" each time a module is initialized, showing the\n"
" place (filename or built-in module) from which it\n"
" is loaded. See\n"
" https://docs.python.org/3/using/cmdline.html#id4.\n"
"\n"
"- bootloader: tell the bootloader to issue progress\n"
" messages while initializing and starting the\n"
" bundled app. Used to diagnose problems with\n"
" missing imports.\n"
"\n"
"- noarchive: instead of storing all frozen Python\n"
" source files as an archive inside the resulting\n"
" executable, store them as files in the resulting\n"
" output directory.\n"
"\n"
),
)
g.add_argument(
'--optimize',
dest='optimize',
metavar='LEVEL',
type=int,
choices={-1, 0, 1, 2},
default=None,
help='Bytecode optimization level used for collected python modules and scripts. For details, see the section '
'“Bytecode Optimization Level” in PyInstaller manual.',
)
g.add_argument(
'--python-option',
dest='python_options',
metavar='PYTHON_OPTION',
action='append',
default=[],
help='Specify a command-line option to pass to the Python interpreter at runtime. Currently supports '
'"v" (equivalent to "--debug imports"), "u", "W <warning control>", "X <xoption>", and "hash_seed=<value>". '
'For details, see the section "Specifying Python Interpreter Options" in PyInstaller manual.',
)
g.add_argument(
"-s",
"--strip",
action="store_true",
help="Apply a symbol-table strip to the executable and shared libs (not recommended for Windows)",
)
g.add_argument(
"--noupx",
action="store_true",
default=False,
help="Do not use UPX even if it is available (works differently between Windows and *nix)",
)
g.add_argument(
"--upx-exclude",
dest="upx_exclude",
metavar="FILE",
action="append",
help="Prevent a binary from being compressed when using upx. This is typically used if upx corrupts certain "
"binaries during compression. FILE is the filename of the binary without path. This option can be used "
"multiple times.",
)
g = parser.add_argument_group('Windows and macOS specific options')
g.add_argument(
"-c",
"--console",
"--nowindowed",
dest="console",
action="store_true",
default=None,
help="Open a console window for standard i/o (default). On Windows this option has no effect if the first "
"script is a '.pyw' file.",
)
g.add_argument(
"-w",
"--windowed",
"--noconsole",
dest="console",
action="store_false",
default=None,
help="Windows and macOS: do not provide a console window for standard i/o. On macOS this also triggers "
"building a macOS .app bundle. On Windows this option is automatically set if the first script is a '.pyw' "
"file. This option is ignored on *NIX systems.",
)
g.add_argument(
"--hide-console",
type=str,
choices={'hide-early', 'hide-late', 'minimize-early', 'minimize-late'},
default=None,
help="Windows only: in console-enabled executable, have bootloader automatically hide or minimize the console "
"window if the program owns the console window (i.e., was not launched from an existing console window).",
)
g.add_argument(
"-i",
"--icon",
action='append',
dest="icon_file",
metavar='<FILE.ico or FILE.exe,ID or FILE.icns or Image or "NONE">',
help="FILE.ico: apply the icon to a Windows executable. FILE.exe,ID: extract the icon with ID from an exe. "
"FILE.icns: apply the icon to the .app bundle on macOS. If an image file is entered that isn't in the "
"platform format (ico on Windows, icns on Mac), PyInstaller tries to use Pillow to translate the icon into "
"the correct format (if Pillow is installed). Use \"NONE\" to not apply any icon, thereby making the OS show "
"some default (default: apply PyInstaller's icon). This option can be used multiple times.",
)
g.add_argument(
"--disable-windowed-traceback",
dest="disable_windowed_traceback",
action="store_true",
default=False,
help="Disable traceback dump of unhandled exception in windowed (noconsole) mode (Windows and macOS only), "
"and instead display a message that this feature is disabled.",
)
g = parser.add_argument_group('Windows specific options')
g.add_argument(
"--version-file",
dest="version_file",
metavar="FILE",
help="Add a version resource from FILE to the exe.",
)
g.add_argument(
"--manifest",
metavar="<FILE or XML>",
help="Add manifest FILE or XML to the exe.",
)
g.add_argument(
"-m",
dest="shorthand_manifest",
metavar="<FILE or XML>",
help="Deprecated shorthand for --manifest.",
)
g.add_argument(
"--no-embed-manifest",
action=_RemovedNoEmbedManifestAction,
)
g.add_argument(
"-r",
"--resource",
dest="resources",
metavar="RESOURCE",
action="append",
default=[],
help="Add or update a resource to a Windows executable. The RESOURCE is one to four items, "
"FILE[,TYPE[,NAME[,LANGUAGE]]]. FILE can be a data file or an exe/dll. For data files, at least TYPE and NAME "
"must be specified. LANGUAGE defaults to 0 or may be specified as wildcard * to update all resources of the "
"given TYPE and NAME. For exe/dll files, all resources from FILE will be added/updated to the final executable "
"if TYPE, NAME and LANGUAGE are omitted or specified as wildcard *. This option can be used multiple times.",
)
g.add_argument(
'--uac-admin',
dest='uac_admin',
action="store_true",
default=False,
help="Using this option creates a Manifest that will request elevation upon application start.",
)
g.add_argument(
'--uac-uiaccess',
dest='uac_uiaccess',
action="store_true",
default=False,
help="Using this option allows an elevated application to work with Remote Desktop.",
)
g = parser.add_argument_group('Windows Side-by-side Assembly searching options (advanced)')
g.add_argument(
"--win-private-assemblies",
action=_RemovedWinPrivateAssembliesAction,
)
g.add_argument(
"--win-no-prefer-redirects",
action=_RemovedWinNoPreferRedirectsAction,
)
g = parser.add_argument_group('macOS specific options')
g.add_argument(
"--argv-emulation",
dest="argv_emulation",
action="store_true",
default=False,
help="Enable argv emulation for macOS app bundles. If enabled, the initial open document/URL event is "
"processed by the bootloader and the passed file paths or URLs are appended to sys.argv.",
)
g.add_argument(
'--osx-bundle-identifier',
dest='bundle_identifier',
help="macOS .app bundle identifier is used as the default unique program name for code signing purposes. "
"The usual form is a hierarchical name in reverse DNS notation. For example: com.mycompany.department.appname "
"(default: first script's basename)",
)
g.add_argument(
'--target-architecture',
'--target-arch',
dest='target_arch',
metavar='ARCH',
default=None,
help="Target architecture (macOS only; valid values: x86_64, arm64, universal2). Enables switching between "
"universal2 and single-arch version of frozen application (provided python installation supports the target "
"architecture). If not target architecture is not specified, the current running architecture is targeted.",
)
g.add_argument(
'--codesign-identity',
dest='codesign_identity',
metavar='IDENTITY',
default=None,
help="Code signing identity (macOS only). Use the provided identity to sign collected binaries and generated "
"executable. If signing identity is not provided, ad-hoc signing is performed instead.",
)
g.add_argument(
'--osx-entitlements-file',
dest='entitlements_file',
metavar='FILENAME',
default=None,
help="Entitlements file to use when code-signing the collected binaries (macOS only).",
)
g = parser.add_argument_group('Rarely used special options')
g.add_argument(
"--runtime-tmpdir",
dest="runtime_tmpdir",
metavar="PATH",
help="Where to extract libraries and support files in `onefile` mode. If this option is given, the bootloader "
"will ignore any temp-folder location defined by the run-time OS. The ``_MEIxxxxxx``-folder will be created "
"here. Please use this option only if you know what you are doing. Note that on POSIX systems, PyInstaller's "
"bootloader does NOT perform shell-style environment variable expansion on the given path string. Therefore, "
"using environment variables (e.g., ``~`` or ``$HOME``) in path will NOT work.",
)
g.add_argument(
"--bootloader-ignore-signals",
action="store_true",
default=False,
help="Tell the bootloader to ignore signals rather than forwarding them to the child process. Useful in "
"situations where for example a supervisor process signals both the bootloader and the child (e.g., via a "
"process group) to avoid signalling the child twice.",
)
def main(
scripts,
name=None,
onefile=False,
console=True,
debug=[],
python_options=[],
strip=False,
noupx=False,
upx_exclude=None,
runtime_tmpdir=None,
contents_directory=None,
pathex=[],
version_file=None,
specpath=None,
bootloader_ignore_signals=False,
disable_windowed_traceback=False,
datas=[],
binaries=[],
icon_file=None,
manifest=None,
resources=[],
bundle_identifier=None,
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
uac_admin=False,
uac_uiaccess=False,
collect_submodules=[],
collect_binaries=[],
collect_data=[],
collect_all=[],
copy_metadata=[],
splash=None,
recursive_copy_metadata=[],
target_arch=None,
codesign_identity=None,
entitlements_file=None,
argv_emulation=False,
hide_console=None,
optimize=None,
**_kwargs
):
# Default values for onefile and console when not explicitly specified on command-line (indicated by None)
if onefile is None:
onefile = False
if console is None:
console = True
# If appname is not specified - use the basename of the main script as name.
if name is None:
name = os.path.splitext(os.path.basename(scripts[0]))[0]
# If specpath not specified - use default value - current working directory.
if specpath is None:
specpath = DEFAULT_SPECPATH
else:
# Expand starting tilde into user's home directory, as a work-around for tilde not being expanded by shell when
# using `--specpath=~/path/abc` instead of `--specpath ~/path/abc` (or when the path argument is quoted).
specpath = os.path.expanduser(specpath)
# If cwd is the root directory of PyInstaller, generate the .spec file in ./appname/ subdirectory.
if specpath == HOMEPATH:
specpath = os.path.join(HOMEPATH, name)
# Create directory tree if missing.
if not os.path.exists(specpath):
os.makedirs(specpath)
# Handle additional EXE options.
exe_options = ''
if version_file:
exe_options += "\n version='%s'," % escape_win_filepath(version_file)
if uac_admin:
exe_options += "\n uac_admin=True,"
if uac_uiaccess:
exe_options += "\n uac_uiaccess=True,"
if icon_file:
# Icon file for Windows.
# On Windows, the default icon is embedded in the bootloader executable.
if icon_file[0] == 'NONE':
exe_options += "\n icon='NONE',"
else:
exe_options += "\n icon=[%s]," % ','.join("'%s'" % escape_win_filepath(ic) for ic in icon_file)
# Icon file for macOS.
# We need to encapsulate it into apostrofes.
icon_file = "'%s'" % icon_file[0]
else:
# On macOS, the default icon has to be copied into the .app bundle.
# The the text value 'None' means - use default icon.
icon_file = 'None'
if contents_directory:
exe_options += "\n contents_directory='%s'," % (contents_directory or "_internal")
if hide_console:
exe_options += "\n hide_console='%s'," % hide_console
if bundle_identifier:
# We need to encapsulate it into apostrofes.
bundle_identifier = "'%s'" % bundle_identifier
if _kwargs["shorthand_manifest"]:
manifest = _kwargs["shorthand_manifest"]
logger.log(
logging.DEPRECATION, "PyInstaller v7 will remove the -m shorthand flag. Please use --manifest=%s instead",
manifest
)
if manifest:
if "<" in manifest:
# Assume XML string
exe_options += "\n manifest='%s'," % manifest.replace("'", "\\'")
else:
# Assume filename
exe_options += "\n manifest='%s'," % escape_win_filepath(manifest)
if resources:
resources = list(map(escape_win_filepath, resources))
exe_options += "\n resources=%s," % repr(resources)
hiddenimports = hiddenimports or []
upx_exclude = upx_exclude or []
if is_darwin and onefile and not console:
from PyInstaller.building.osx import WINDOWED_ONEFILE_DEPRCATION
logger.log(logging.DEPRECATION, WINDOWED_ONEFILE_DEPRCATION)
# If file extension of the first script is '.pyw', force --windowed option.
if is_win and os.path.splitext(scripts[0])[-1] == '.pyw':
console = False
# If script paths are relative, make them relative to the directory containing .spec file.
scripts = [make_path_spec_relative(x, specpath) for x in scripts]
# With absolute paths replace prefix with variable HOMEPATH.
scripts = list(map(Path, scripts))
# Translate the default of ``debug=None`` to an empty list.
if debug is None:
debug = []
# Translate the ``all`` option.
if DEBUG_ALL_CHOICE[0] in debug:
debug = DEBUG_ARGUMENT_CHOICES
# Create preamble (for collect_*() calls)
preamble = Preamble(
datas, binaries, hiddenimports, collect_data, collect_binaries, collect_submodules, collect_all, copy_metadata,
recursive_copy_metadata
)
if splash:
splash_init = splashtmpl % {'splash_image': splash}
splash_binaries = "\n splash.binaries,"
splash_target = "\n splash,"
else:
splash_init = splash_binaries = splash_target = ""
# Infer byte-code optimization level.
opt_level = sum([opt == 'O' for opt in python_options])
if opt_level > 2:
logger.warning(
"The switch '--python-option O' has been specified %d times - it should be specified at most twice!",
opt_level,
)
opt_level = 2
if optimize is None:
if opt_level == 0:
# Infer from running python process
optimize = sys.flags.optimize
else:
# Infer from `--python-option O` switch(es).
optimize = opt_level
elif optimize != opt_level and opt_level != 0:
logger.warning(
"Mismatch between optimization level passed via --optimize switch (%d) and number of '--python-option O' "
"switches (%d)!",
optimize,
opt_level,
)
if optimize >= 0:
# Ensure OPTIONs passed to bootloader match the optimization settings.
python_options += max(0, optimize - opt_level) * ['O']
# Create OPTIONs array
if 'imports' in debug and 'v' not in python_options:
python_options.append('v')
python_options_array = [(opt, None, 'OPTION') for opt in python_options]
d = {
'scripts': scripts,
'pathex': pathex or [],
'binaries': preamble.binaries,
'datas': preamble.datas,
'hiddenimports': preamble.hiddenimports,
'preamble': preamble.content,
'name': name,
'noarchive': 'noarchive' in debug,
'optimize': optimize,
'options': python_options_array,
'debug_bootloader': 'bootloader' in debug,
'bootloader_ignore_signals': bootloader_ignore_signals,
'strip': strip,
'upx': not noupx,
'upx_exclude': upx_exclude,
'runtime_tmpdir': runtime_tmpdir,
'exe_options': exe_options,
# Directory with additional custom import hooks.
'hookspath': hookspath,
# List with custom runtime hook files.
'runtime_hooks': runtime_hooks or [],
# List of modules/packages to ignore.
'excludes': excludes or [],
# only Windows and macOS distinguish windowed and console apps
'console': console,
'disable_windowed_traceback': disable_windowed_traceback,
# Icon filename. Only macOS uses this item.
'icon': icon_file,
# .app bundle identifier. Only macOS uses this item.
'bundle_identifier': bundle_identifier,
# argv emulation (macOS only)
'argv_emulation': argv_emulation,
# Target architecture (macOS only)
'target_arch': target_arch,
# Code signing identity (macOS only)
'codesign_identity': codesign_identity,
# Entitlements file (macOS only)
'entitlements_file': entitlements_file,
# splash screen
'splash_init': splash_init,
'splash_target': splash_target,
'splash_binaries': splash_binaries,
}
# Write down .spec file to filesystem.
specfnm = os.path.join(specpath, name + '.spec')
with open(specfnm, 'w', encoding='utf-8') as specfile:
if onefile:
specfile.write(onefiletmplt % d)
# For macOS create .app bundle.
if is_darwin and not console:
specfile.write(bundleexetmplt % d)
else:
specfile.write(onedirtmplt % d)
# For macOS create .app bundle.
if is_darwin and not console:
specfile.write(bundletmplt % d)
return specfnm
|
Preamble
|
python
|
jina-ai__jina
|
tests/docker_compose/test-executor/debug_executor.py
|
{
"start": 64,
"end": 2920
}
|
class ____(Executor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
from jina.logging.logger import JinaLogger
self.logger = JinaLogger(self.__class__.__name__)
self._name = self.runtime_args.name
@requests(on='/debug')
def debug(self, docs: DocumentArray, **kwargs):
self.logger.debug(
f'Received doc array in test-executor {self._name} with length {len(docs)}.'
)
key = 'traversed-executors'
for doc in docs:
if key not in doc.tags:
doc.tags[key] = []
traversed = list(doc.tags.get(key))
traversed.append(self._name)
doc.tags[key] = traversed
doc.tags['parallel'] = self.runtime_args.replicas
doc.tags['shards'] = self.runtime_args.shards
doc.tags['shard_id'] = self.runtime_args.shard_id
@requests(on='/env')
def env(self, docs: DocumentArray, **kwargs):
self.logger.debug(
f'Received doc array in test-executor {self._name} with length {len(docs)}.'
)
for doc in docs:
doc.tags['k1'] = os.environ.get('k1')
doc.tags['k2'] = os.environ.get('k2')
doc.tags['JINA_LOG_LEVEL'] = os.environ.get('JINA_LOG_LEVEL')
doc.tags['env'] = {'k1': os.environ.get('k1'), 'k2': os.environ.get('k2')}
@requests(on='/cuda')
def cuda(self, docs: DocumentArray, **kwargs):
self.logger.debug(
f'Received doc array in test-executor {self._name} with length {len(docs)}.'
)
import kubernetes
from kubernetes import client
api_client = client.ApiClient()
core_client = client.CoreV1Api(api_client=api_client)
try:
# try loading kube config from disk first
kubernetes.config.load_kube_config()
except kubernetes.config.config_exception.ConfigException:
# if the config could not be read from disk, try loading in cluster config
# this works if we are running inside k8s
kubernetes.config.load_incluster_config()
pods = core_client.list_namespaced_pod('test-gpu') # List[V1Pod]
pod_spec = pods[0].spec # V1PodSpec
pod_container = pod_spec.containers[0] # V1Container
pod_resources = pod_container.resources # V1ResourceRequirements
for doc in docs:
doc.tags['resources']['limits'] = pod_resources.limits
@requests(on='/workspace')
def foo_workspace(self, docs: DocumentArray, **kwargs):
self.logger.debug(
f'Received doc array in test-executor {self._name} with length {len(docs)}.'
)
self.logger.debug(f'Workspace {self.workspace}.')
for doc in docs:
doc.tags['workspace'] = self.workspace
|
TestExecutor
|
python
|
charliermarsh__ruff
|
crates/ruff_linter/resources/test/fixtures/flake8_comprehensions/C420_3.py
|
{
"start": 0,
"end": 111
}
|
class ____: a = None
{C.a: None for C.a in "abc"}
print(C.a)
x = [None]
{x[0]: None for x[0] in "abc"}
print(x)
|
C
|
python
|
apache__airflow
|
providers/apache/druid/src/airflow/providers/apache/druid/transfers/hive_to_druid.py
|
{
"start": 1325,
"end": 10166
}
|
class ____(BaseOperator):
"""
Moves data from Hive to Druid.
[del]note that for now the data is loaded into memory before being pushed to
Druid, so this operator should be used for smallish amount of data.[/del]
:param sql: SQL query to execute against the Druid database. (templated)
:param druid_datasource: the datasource you want to ingest into in druid
:param ts_dim: the timestamp dimension
:param metric_spec: the metrics you want to define for your data
:param hive_cli_conn_id: the hive connection id
:param druid_ingest_conn_id: the druid ingest connection id
:param metastore_conn_id: the metastore connection id
:param hadoop_dependency_coordinates: list of coordinates to squeeze
int the ingest json
:param intervals: list of time intervals that defines segments,
this is passed as is to the json object. (templated)
:param num_shards: Directly specify the number of shards to create.
:param target_partition_size: Target number of rows to include in a partition,
:param query_granularity: The minimum granularity to be able to query results at and the granularity of
the data inside the segment. E.g. a value of "minute" will mean that data is aggregated at minutely
granularity. That is, if there are collisions in the tuple (minute(timestamp), dimensions), then it
will aggregate values together using the aggregators instead of storing individual rows.
A granularity of 'NONE' means millisecond granularity.
:param segment_granularity: The granularity to create time chunks at. Multiple segments can be created per
time chunk. For example, with 'DAY' segmentGranularity, the events of the same day fall into the
same time chunk which can be optionally further partitioned into multiple segments based on other
configurations and input size.
:param hive_tblproperties: additional properties for tblproperties in
hive for the staging table
:param job_properties: additional properties for job
"""
template_fields: Sequence[str] = ("sql", "intervals")
template_ext: Sequence[str] = (".sql",)
template_fields_renderers = {"sql": "hql"}
def __init__(
self,
*,
sql: str,
druid_datasource: str,
ts_dim: str,
metric_spec: list[Any] | None = None,
hive_cli_conn_id: str = "hive_cli_default",
druid_ingest_conn_id: str = "druid_ingest_default",
metastore_conn_id: str = "metastore_default",
hadoop_dependency_coordinates: list[str] | None = None,
intervals: list[Any] | None = None,
num_shards: float = -1,
target_partition_size: int = -1,
query_granularity: str = "NONE",
segment_granularity: str = "DAY",
hive_tblproperties: dict[Any, Any] | None = None,
job_properties: dict[Any, Any] | None = None,
**kwargs: Any,
) -> None:
super().__init__(**kwargs)
self.sql = sql
self.druid_datasource = druid_datasource
self.ts_dim = ts_dim
self.intervals = intervals or ["{{ ds }}/{{ logical_date.add_days(1) | ds }}"]
self.num_shards = num_shards
self.target_partition_size = target_partition_size
self.query_granularity = query_granularity
self.segment_granularity = segment_granularity
self.metric_spec = metric_spec or [{"name": "count", "type": "count"}]
self.hive_cli_conn_id = hive_cli_conn_id
self.hadoop_dependency_coordinates = hadoop_dependency_coordinates
self.druid_ingest_conn_id = druid_ingest_conn_id
self.metastore_conn_id = metastore_conn_id
self.hive_tblproperties = hive_tblproperties or {}
self.job_properties = job_properties
def execute(self, context: Context) -> None:
hive = HiveCliHook(hive_cli_conn_id=self.hive_cli_conn_id)
self.log.info("Extracting data from Hive")
hive_table = "druid." + context["task_instance_key_str"].replace(".", "_")
sql = self.sql.strip().strip(";")
tblproperties = "".join(f", '{k}' = '{v}'" for k, v in self.hive_tblproperties.items())
hql = f"""\
SET mapred.output.compress=false;
SET hive.exec.compress.output=false;
DROP TABLE IF EXISTS {hive_table};
CREATE TABLE {hive_table}
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'
STORED AS TEXTFILE
TBLPROPERTIES ('serialization.null.format' = ''{tblproperties})
AS
{sql}
"""
self.log.info("Running command:\n %s", hql)
hive.run_cli(hql)
meta_hook = HiveMetastoreHook(self.metastore_conn_id)
# Get the Hive table and extract the columns
table = meta_hook.get_table(hive_table)
columns = [col.name for col in table.sd.cols]
# Get the path on hdfs
static_path = meta_hook.get_table(hive_table).sd.location
druid = DruidHook(druid_ingest_conn_id=self.druid_ingest_conn_id)
try:
index_spec = self.construct_ingest_query(
static_path=static_path,
columns=columns,
)
self.log.info("Inserting rows into Druid, hdfs path: %s", static_path)
druid.submit_indexing_job(index_spec)
self.log.info("Load seems to have succeeded!")
finally:
self.log.info("Cleaning up by dropping the temp Hive table %s", hive_table)
hql = f"DROP TABLE IF EXISTS {hive_table}"
hive.run_cli(hql)
def construct_ingest_query(self, static_path: str, columns: list[str]) -> dict[str, Any]:
"""
Build an ingest query for an HDFS TSV load.
:param static_path: The path on hdfs where the data is
:param columns: List of all the columns that are available
"""
# backward compatibility for num_shards,
# but target_partition_size is the default setting
# and overwrites the num_shards
num_shards = self.num_shards
target_partition_size = self.target_partition_size
if self.target_partition_size == -1:
if self.num_shards == -1:
target_partition_size = DEFAULT_TARGET_PARTITION_SIZE
else:
num_shards = -1
metric_names = [m["fieldName"] for m in self.metric_spec if m["type"] != "count"]
# Take all the columns, which are not the time dimension
# or a metric, as the dimension columns
dimensions = [c for c in columns if c not in metric_names and c != self.ts_dim]
ingest_query_dict: dict[str, Any] = {
"type": "index_hadoop",
"spec": {
"dataSchema": {
"metricsSpec": self.metric_spec,
"granularitySpec": {
"queryGranularity": self.query_granularity,
"intervals": self.intervals,
"type": "uniform",
"segmentGranularity": self.segment_granularity,
},
"parser": {
"type": "string",
"parseSpec": {
"columns": columns,
"dimensionsSpec": {
"dimensionExclusions": [],
"dimensions": dimensions, # list of names
"spatialDimensions": [],
},
"timestampSpec": {"column": self.ts_dim, "format": "auto"},
"format": "tsv",
},
},
"dataSource": self.druid_datasource,
},
"tuningConfig": {
"type": "hadoop",
"jobProperties": {
"mapreduce.job.user.classpath.first": "false",
"mapreduce.map.output.compress": "false",
"mapreduce.output.fileoutputformat.compress": "false",
},
"partitionsSpec": {
"type": "hashed",
"targetPartitionSize": target_partition_size,
"numShards": num_shards,
},
},
"ioConfig": {"inputSpec": {"paths": static_path, "type": "static"}, "type": "hadoop"},
},
}
if self.job_properties:
ingest_query_dict["spec"]["tuningConfig"]["jobProperties"].update(self.job_properties)
if self.hadoop_dependency_coordinates:
ingest_query_dict["hadoopDependencyCoordinates"] = self.hadoop_dependency_coordinates
return ingest_query_dict
|
HiveToDruidOperator
|
python
|
MongoEngine__mongoengine
|
docs/code/tumblelog.py
|
{
"start": 626,
"end": 682
}
|
class ____(Post):
image_path = StringField()
|
ImagePost
|
python
|
mlflow__mlflow
|
mlflow/genai/scorers/builtin_scorers.py
|
{
"start": 29973,
"end": 36058
}
|
class ____(BuiltInScorer):
"""
This scorer evaluates whether the agent's response follows specific constraints
or instructions provided for each row in the input dataset. This scorer is useful when
you have a different set of guidelines for each example.
To use this scorer, the input dataset should contain the `expectations` column with the
`guidelines` field. Then pass this scorer to `mlflow.genai.evaluate` for running full
evaluation on the input dataset.
Args:
name: The name of the scorer. Defaults to "expectations_guidelines".
model: {{ model }}
Example:
In this example, the guidelines specified in the `guidelines` field of the `expectations`
column will be applied to each example individually. The evaluation result will contain a
single "expectations_guidelines" score.
.. code-block:: python
import mlflow
from mlflow.genai.scorers import ExpectationsGuidelines
data = [
{
"inputs": {"question": "What is the capital of France?"},
"outputs": "The capital of France is Paris.",
"expectations": {
"guidelines": ["The response must be factual and concise"],
},
},
{
"inputs": {"question": "How to learn Python?"},
"outputs": "You can read a book or take a course.",
"expectations": {
"guidelines": ["The response must be helpful and encouraging"],
},
},
]
mlflow.genai.evaluate(data=data, scorers=[ExpectationsGuidelines()])
"""
name: str = "expectations_guidelines"
model: str | None = None
required_columns: set[str] = {"inputs", "outputs"}
description: str = (
"Evaluate whether the agent's response follows specific constraints or instructions "
"provided for each row in the input dataset."
)
@property
def instructions(self) -> str:
"""Get the instructions of what this scorer evaluates."""
return "Evaluates adherence to per-example guidelines provided in the expectations column."
def get_input_fields(self) -> list[JudgeField]:
"""
Get the input fields for the ExpectationsGuidelines judge.
Returns:
List of JudgeField objects defining the input fields based on the __call__ method.
"""
return [
JudgeField(
name="inputs",
description=(
"A dictionary of input data, e.g. "
"{'question': 'What is the capital of France?'}."
),
),
JudgeField(
name="outputs",
description="The response from the model, e.g. 'The capital of France is Paris.'",
),
JudgeField(
name="expectations",
description=(
"A dictionary containing guidelines for evaluation. "
"Must contain a 'guidelines' key (optional)."
),
),
]
def validate_columns(self, columns: set[str]) -> None:
super().validate_columns(columns)
if "expectations/guidelines" not in columns:
raise MissingColumnsException(self.name, ["expectations/guidelines"])
def __call__(
self,
*,
inputs: dict[str, Any] | None = None,
outputs: Any | None = None,
expectations: dict[str, Any] | None = None,
trace: Trace | None = None,
) -> Feedback:
"""
Evaluate adherence to specified guidelines.
This scorer can be used in two ways:
1. Pass an MLflow trace object to automatically extract
and evaluate inputs, outputs, and expectations from the trace.
2. Directly provide the inputs, outputs, and expectations to evaluate.
Args:
inputs: A dictionary of input data, e.g. {"question": "What is the capital of France?"}.
Optional when trace is provided.
outputs: The response from the model, e.g. "The capital of France is Paris."
Optional when trace is provided.
expectations: A dictionary of expectations for the response. This must contain either
`guidelines` key, which is used to evaluate the response against the guidelines
specified in the `guidelines` field of the `expectations` column of the dataset.
E.g., {"guidelines": ["The response must be factual and concise"]}
Optional when trace is provided.
trace: MLflow trace object containing the execution to evaluate. When provided,
missing inputs, outputs, and expectations will be automatically extracted from
the trace.
Returns:
An :py:class:`mlflow.entities.assessment.Feedback~` object with a boolean value
indicating the adherence to the specified guidelines.
"""
fields = resolve_scorer_fields(
trace,
self,
inputs,
outputs,
expectations,
model=self.model,
extract_expectations=True,
)
_validate_required_fields(fields, self, "ExpectationsGuidelines scorer")
guidelines = (fields.expectations or {}).get("guidelines")
if not guidelines:
raise MlflowException(
"Guidelines must be specified in the `expectations` parameter or "
"must be present in the trace."
)
feedback = judges.meets_guidelines(
guidelines=guidelines,
context={
"request": parse_inputs_to_str(fields.inputs),
"response": parse_outputs_to_str(fields.outputs),
},
name=self.name,
model=self.model,
)
return _sanitize_scorer_feedback(feedback)
@format_docstring(_MODEL_API_DOC)
|
ExpectationsGuidelines
|
python
|
getsentry__sentry
|
src/sentry/audit_log/services/log/impl.py
|
{
"start": 4037,
"end": 5076
}
|
class ____(LogService):
def record_audit_log(self, *, event: AuditLogEvent) -> None:
outbox = RegionOutbox(
shard_scope=OutboxScope.AUDIT_LOG_SCOPE,
shard_identifier=event.organization_id,
category=OutboxCategory.AUDIT_LOG_EVENT,
object_identifier=RegionOutbox.next_object_identifier(),
payload=event.to_json_encodable(),
)
outbox.save()
def record_user_ip(self, *, event: UserIpEvent) -> None:
outbox = RegionOutbox(
shard_scope=OutboxScope.USER_IP_SCOPE,
shard_identifier=event.user_id,
category=OutboxCategory.USER_IP_EVENT,
object_identifier=event.user_id,
payload=event.to_json_encodable(),
)
outbox.save()
def find_last_log(
self,
*,
organization_id: int,
target_object_id: int | None,
event: int,
data: dict[str, str] | None = None,
) -> AuditLogEvent | None:
return None
|
OutboxBackedLogService
|
python
|
huggingface__transformers
|
src/transformers/models/clip/modeling_clip.py
|
{
"start": 9551,
"end": 11895
}
|
class ____(nn.Module):
def __init__(self, config: CLIPTextConfig):
super().__init__()
embed_dim = config.hidden_size
self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
self.register_buffer(
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
) -> torch.Tensor:
seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
max_position_embedding = self.position_embedding.weight.shape[0]
if seq_length > max_position_embedding:
raise ValueError(
f"Sequence length must be less than max_position_embeddings (got `sequence length`: "
f"{seq_length} and max_position_embeddings: {max_position_embedding}"
)
if position_ids is None:
position_ids = self.position_ids[:, :seq_length]
if inputs_embeds is None:
inputs_embeds = self.token_embedding(input_ids)
position_embeddings = self.position_embedding(position_ids)
embeddings = inputs_embeds + position_embeddings
return embeddings
def eager_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Optional[torch.Tensor],
scaling: float,
dropout: float = 0.0,
**kwargs: Unpack[TransformersKwargs],
):
attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
if attention_mask is not None:
attn_weights = attn_weights + attention_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
attn_output = torch.matmul(attn_weights, value)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
|
CLIPTextEmbeddings
|
python
|
keon__algorithms
|
tests/test_maths.py
|
{
"start": 13926,
"end": 14392
}
|
class ____(unittest.TestCase):
"""[summary]
Test for the file num_digits.py
Arguments:
unittest {[type]} -- [description]
"""
def test_num_digits(self):
self.assertEqual(2, num_digits(12))
self.assertEqual(5, num_digits(99999))
self.assertEqual(1, num_digits(8))
self.assertEqual(1, num_digits(0))
self.assertEqual(1, num_digits(-5))
self.assertEqual(3, num_digits(-254))
|
TestNumberOfDigits
|
python
|
ray-project__ray
|
python/ray/data/preprocessors/imputer.py
|
{
"start": 691,
"end": 9174
}
|
class ____(SerializablePreprocessorBase):
"""Replace missing values with imputed values. If the column is missing from a
batch, it will be filled with the imputed value.
Examples:
>>> import pandas as pd
>>> import ray
>>> from ray.data.preprocessors import SimpleImputer
>>> df = pd.DataFrame({"X": [0, None, 3, 3], "Y": [None, "b", "c", "c"]})
>>> ds = ray.data.from_pandas(df) # doctest: +SKIP
>>> ds.to_pandas() # doctest: +SKIP
X Y
0 0.0 None
1 NaN b
2 3.0 c
3 3.0 c
The `"mean"` strategy imputes missing values with the mean of non-missing
values. This strategy doesn't work with categorical data.
>>> preprocessor = SimpleImputer(columns=["X"], strategy="mean")
>>> preprocessor.fit_transform(ds).to_pandas() # doctest: +SKIP
X Y
0 0.0 None
1 2.0 b
2 3.0 c
3 3.0 c
The `"most_frequent"` strategy imputes missing values with the most frequent
value in each column.
>>> preprocessor = SimpleImputer(columns=["X", "Y"], strategy="most_frequent")
>>> preprocessor.fit_transform(ds).to_pandas() # doctest: +SKIP
X Y
0 0.0 c
1 3.0 b
2 3.0 c
3 3.0 c
The `"constant"` strategy imputes missing values with the value specified by
`fill_value`.
>>> preprocessor = SimpleImputer(
... columns=["Y"],
... strategy="constant",
... fill_value="?",
... )
>>> preprocessor.fit_transform(ds).to_pandas() # doctest: +SKIP
X Y
0 0.0 ?
1 NaN b
2 3.0 c
3 3.0 c
:class:`SimpleImputer` can also be used in append mode by providing the
name of the output_columns that should hold the imputed values.
>>> preprocessor = SimpleImputer(columns=["X"], output_columns=["X_imputed"], strategy="mean")
>>> preprocessor.fit_transform(ds).to_pandas() # doctest: +SKIP
X Y X_imputed
0 0.0 None 0.0
1 NaN b 2.0
2 3.0 c 3.0
3 3.0 c 3.0
Args:
columns: The columns to apply imputation to.
strategy: How imputed values are chosen.
* ``"mean"``: The mean of non-missing values. This strategy only works with numeric columns.
* ``"most_frequent"``: The most common value.
* ``"constant"``: The value passed to ``fill_value``.
fill_value: The value to use when ``strategy`` is ``"constant"``.
output_columns: The names of the transformed columns. If None, the transformed
columns will be the same as the input columns. If not None, the length of
``output_columns`` must match the length of ``columns``, othwerwise an error
will be raised.
Raises:
ValueError: if ``strategy`` is not ``"mean"``, ``"most_frequent"``, or
``"constant"``.
""" # noqa: E501
_valid_strategies = ["mean", "most_frequent", "constant"]
def __init__(
self,
columns: List[str],
strategy: str = "mean",
fill_value: Optional[Union[str, Number]] = None,
*,
output_columns: Optional[List[str]] = None,
):
super().__init__()
self.columns = columns
self.strategy = strategy
self.fill_value = fill_value
if strategy not in self._valid_strategies:
raise ValueError(
f"Strategy {strategy} is not supported."
f"Supported values are: {self._valid_strategies}"
)
if strategy == "constant":
# There is no information to be fitted.
self._is_fittable = False
if fill_value is None:
raise ValueError(
'`fill_value` must be set when using "constant" strategy.'
)
self.output_columns = (
SerializablePreprocessorBase._derive_and_validate_output_columns(
columns, output_columns
)
)
def _fit(self, dataset: "Dataset") -> SerializablePreprocessorBase:
if self.strategy == "mean":
self.stat_computation_plan.add_aggregator(
aggregator_fn=Mean, columns=self.columns
)
elif self.strategy == "most_frequent":
self.stat_computation_plan.add_callable_stat(
stat_fn=lambda key_gen: _get_most_frequent_values(
dataset=dataset,
columns=self.columns,
key_gen=key_gen,
),
stat_key_fn=lambda col: f"most_frequent({col})",
columns=self.columns,
)
return self
def _transform_pandas(self, df: pd.DataFrame):
for column, output_column in zip(self.columns, self.output_columns):
value = self._get_fill_value(column)
if value is None:
raise ValueError(
f"Column {column} has no fill value. "
"Check the data used to fit the SimpleImputer."
)
if column not in df.columns:
# Create the column with the fill_value if it doesn't exist
df[output_column] = value
else:
if is_categorical_dtype(df.dtypes[column]):
df[output_column] = df[column].cat.add_categories([value])
if (
output_column != column
# If the backing array is memory-mapped from shared memory, then the
# array won't be writeable.
or (
isinstance(df[output_column].values, np.ndarray)
and not df[output_column].values.flags.writeable
)
):
df[output_column] = df[column].copy(deep=True)
df.fillna({output_column: value}, inplace=True)
return df
def _get_fill_value(self, column):
if self.strategy == "mean":
return self.stats_[f"mean({column})"]
elif self.strategy == "most_frequent":
return self.stats_[f"most_frequent({column})"]
elif self.strategy == "constant":
return self.fill_value
else:
raise ValueError(
f"Strategy {self.strategy} is not supported. "
"Supported values are: {self._valid_strategies}"
)
def __repr__(self):
return (
f"{self.__class__.__name__}(columns={self.columns!r}, "
f"strategy={self.strategy!r}, fill_value={self.fill_value!r}, "
f"output_columns={self.output_columns!r})"
)
def _get_serializable_fields(self) -> Dict[str, Any]:
return {
"columns": self.columns,
"output_columns": self.output_columns,
"_fitted": getattr(self, "_fitted", None),
"strategy": self.strategy,
"fill_value": getattr(self, "fill_value", None),
}
def _set_serializable_fields(self, fields: Dict[str, Any], version: int):
# required fields
self.columns = fields["columns"]
self.output_columns = fields["output_columns"]
self.strategy = fields["strategy"]
# optional fields
self._fitted = fields.get("_fitted")
self.fill_value = fields.get("fill_value")
if self.strategy == "constant":
self._is_fittable = False
def _get_most_frequent_values(
dataset: "Dataset",
columns: List[str],
key_gen: Callable[[str], str],
) -> Dict[str, Union[str, Number]]:
def get_pd_value_counts(df: pd.DataFrame) -> Dict[str, List[Counter]]:
return {col: [Counter(df[col].value_counts().to_dict())] for col in columns}
value_counts = dataset.map_batches(get_pd_value_counts, batch_format="pandas")
final_counters = {col: Counter() for col in columns}
for batch in value_counts.iter_batches(batch_size=None):
for col, counters in batch.items():
for counter in counters:
final_counters[col] += counter
return {
key_gen(column): final_counters[column].most_common(1)[0][0] # noqa
for column in columns
}
|
SimpleImputer
|
python
|
sphinx-doc__sphinx
|
tests/test_builders/test_build_linkcheck.py
|
{
"start": 32777,
"end": 34733
}
|
class ____(BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
def do_HEAD(self) -> None:
self.send_response(302, 'Found')
self.send_header('Location', '/redirected')
self.send_header('Content-Length', '0')
self.end_headers()
def do_GET(self) -> None:
content = b'ok\n'
self.send_response(200, 'OK')
self.send_header('Content-Length', str(len(content)))
self.end_headers()
self.wfile.write(content)
self.close_connection = (
True # we don't expect the client to read this response body
)
@pytest.mark.sphinx(
'linkcheck',
testroot='linkcheck-localserver',
freshenv=True,
)
def test_TooManyRedirects_on_HEAD(
app: SphinxTestApp, monkeypatch: pytest.MonkeyPatch
) -> None:
import requests.sessions
monkeypatch.setattr(requests.sessions, 'DEFAULT_REDIRECT_LIMIT', 5)
with serve_application(app, InfiniteRedirectOnHeadHandler) as address:
app.build()
with open(app.outdir / 'output.json', encoding='utf-8') as fp:
content = json.load(fp)
assert content == {
'code': 0,
'status': 'working',
'filename': 'index.rst',
'lineno': 1,
'uri': f'http://{address}/',
'info': '',
}
@pytest.mark.sphinx('linkcheck', testroot='linkcheck-localserver')
def test_ignore_local_redirection(app: SphinxTestApp) -> None:
with serve_application(app, InfiniteRedirectOnHeadHandler) as address:
app.config.linkcheck_ignore = [f'http://{address}/redirected']
app.build()
with open(app.outdir / 'output.json', encoding='utf-8') as fp:
content = json.load(fp)
assert content == {
'code': 302,
'status': 'ignored',
'filename': 'index.rst',
'lineno': 1,
'uri': f'http://{address}/',
'info': f'ignored redirect: http://{address}/redirected',
}
|
InfiniteRedirectOnHeadHandler
|
python
|
microsoft__pyright
|
packages/pyright-internal/src/tests/samples/dataclassFrozen1.py
|
{
"start": 427,
"end": 618
}
|
class ____(DC2):
val4: int = 4
val5: ClassVar[int]
# This should generate an error because a non-frozen dataclass
# cannot inherit from a frozen dataclass.
@dataclass(frozen=False)
|
DC4
|
python
|
scipy__scipy
|
scipy/io/tests/test_mmio.py
|
{
"start": 13054,
"end": 19596
}
|
class ____:
def setup_method(self):
self.tmpdir = mkdtemp(suffix=str(threading.get_native_id()))
self.fn = os.path.join(self.tmpdir, 'testfile.mtx')
def teardown_method(self):
shutil.rmtree(self.tmpdir)
def check_read(self, example, a, info, dense, over32, over64):
with open(self.fn, 'w') as f:
f.write(example)
assert_equal(mminfo(self.fn), info)
if ((over32 and (np.intp(0).itemsize < 8) and mmwrite == scipy.io._mmio.mmwrite)
or over64):
assert_raises(OverflowError, mmread, self.fn)
else:
b = mmread(self.fn, spmatrix=False)
if not dense:
b = b.toarray()
assert_equal(a, b)
def test_read_32bit_integer_dense(self):
a = array([[2**31-1, 2**31-1],
[2**31-2, 2**31-2]], dtype=np.int64)
self.check_read(_32bit_integer_dense_example,
a,
(2, 2, 4, 'array', 'integer', 'general'),
dense=True,
over32=False,
over64=False)
def test_read_32bit_integer_sparse(self):
a = array([[2**31-1, 0],
[0, 2**31-2]], dtype=np.int64)
self.check_read(_32bit_integer_sparse_example,
a,
(2, 2, 2, 'coordinate', 'integer', 'symmetric'),
dense=False,
over32=False,
over64=False)
def test_read_64bit_integer_dense(self):
a = array([[2**31, -2**31],
[-2**63+2, 2**63-1]], dtype=np.int64)
self.check_read(_64bit_integer_dense_example,
a,
(2, 2, 4, 'array', 'integer', 'general'),
dense=True,
over32=True,
over64=False)
def test_read_64bit_integer_sparse_general(self):
a = array([[2**31, 2**63-1],
[0, 2**63-1]], dtype=np.int64)
self.check_read(_64bit_integer_sparse_general_example,
a,
(2, 2, 3, 'coordinate', 'integer', 'general'),
dense=False,
over32=True,
over64=False)
def test_read_64bit_integer_sparse_symmetric(self):
a = array([[2**31, -2**63+1],
[-2**63+1, 2**63-1]], dtype=np.int64)
self.check_read(_64bit_integer_sparse_symmetric_example,
a,
(2, 2, 3, 'coordinate', 'integer', 'symmetric'),
dense=False,
over32=True,
over64=False)
def test_read_64bit_integer_sparse_skew(self):
a = array([[2**31, -2**63+1],
[2**63-1, 2**63-1]], dtype=np.int64)
self.check_read(_64bit_integer_sparse_skew_example,
a,
(2, 2, 3, 'coordinate', 'integer', 'skew-symmetric'),
dense=False,
over32=True,
over64=False)
def test_read_over64bit_integer_dense(self):
self.check_read(_over64bit_integer_dense_example,
None,
(2, 2, 4, 'array', 'integer', 'general'),
dense=True,
over32=True,
over64=True)
def test_read_over64bit_integer_sparse(self):
self.check_read(_over64bit_integer_sparse_example,
None,
(2, 2, 2, 'coordinate', 'integer', 'symmetric'),
dense=False,
over32=True,
over64=True)
_general_example = '''\
%%MatrixMarket matrix coordinate real general
%=================================================================================
%
% This ASCII file represents a sparse MxN matrix with L
% nonzeros in the following Matrix Market format:
%
% +----------------------------------------------+
% |%%MatrixMarket matrix coordinate real general | <--- header line
% |% | <--+
% |% comments | |-- 0 or more comment lines
% |% | <--+
% | M N L | <--- rows, columns, entries
% | I1 J1 A(I1, J1) | <--+
% | I2 J2 A(I2, J2) | |
% | I3 J3 A(I3, J3) | |-- L lines
% | . . . | |
% | IL JL A(IL, JL) | <--+
% +----------------------------------------------+
%
% Indices are 1-based, i.e. A(1,1) is the first element.
%
%=================================================================================
5 5 8
1 1 1.000e+00
2 2 1.050e+01
3 3 1.500e-02
1 4 6.000e+00
4 2 2.505e+02
4 4 -2.800e+02
4 5 3.332e+01
5 5 1.200e+01
'''
_hermitian_example = '''\
%%MatrixMarket matrix coordinate complex hermitian
5 5 7
1 1 1.0 0
2 2 10.5 0
4 2 250.5 22.22
3 3 1.5e-2 0
4 4 -2.8e2 0
5 5 12. 0
5 4 0 33.32
'''
_skew_example = '''\
%%MatrixMarket matrix coordinate real skew-symmetric
5 5 7
1 1 1.0
2 2 10.5
4 2 250.5
3 3 1.5e-2
4 4 -2.8e2
5 5 12.
5 4 0
'''
_symmetric_example = '''\
%%MatrixMarket matrix coordinate real symmetric
5 5 7
1 1 1.0
2 2 10.5
4 2 250.5
3 3 1.5e-2
4 4 -2.8e2
5 5 12.
5 4 8
'''
_symmetric_pattern_example = '''\
%%MatrixMarket matrix coordinate pattern symmetric
5 5 7
1 1
2 2
4 2
3 3
4 4
5 5
5 4
'''
# example (without comment lines) from Figure 1 in
# https://math.nist.gov/MatrixMarket/reports/MMformat.ps
_empty_lines_example = '''\
%%MatrixMarket MATRIX Coordinate Real General
5 5 8
1 1 1.0
2 2 10.5
3 3 1.5e-2
4 4 -2.8E2
5 5 12.
1 4 6
4 2 250.5
4 5 33.32
'''
|
TestMMIOReadLargeIntegers
|
python
|
getsentry__sentry
|
src/sentry/testutils/pytest/json_report_reruns.py
|
{
"start": 893,
"end": 1664
}
|
class ____:
def __init__(self, json_tests: JSONTestItems):
self.json_tests = json_tests
def pytest_json_runtest_stage(self, report: pytest.TestReport) -> None:
assert self.json_tests is not None
nodeid = report.nodeid
json_testitem = self.json_tests[nodeid]
if report.when in json_testitem:
# this is a new result of some kind -- record all prior data as a
# "rerun" and start over fresh
reruns = json_testitem.setdefault("reruns", [])
reruns.append(
{
key: json_testitem.pop(key)
for key in ("setup", "call", "teardown")
if key in json_testitem
}
)
|
PytestRerunJSONReporter
|
python
|
dagster-io__dagster
|
examples/project_fully_featured/project_fully_featured/resources/hn_resource.py
|
{
"start": 1037,
"end": 1626
}
|
class ____(HNClient):
@cached_method
def load_items(self) -> dict[str, HNItemRecord]:
file_path = file_relative_path(__file__, "../utils/snapshot.gzip")
with gzip.open(file_path, "r") as f:
return json.loads(f.read().decode())
def fetch_item_by_id(self, item_id: int) -> Optional[HNItemRecord]:
return self.load_items().get(str(item_id))
def fetch_max_item_id(self) -> int:
return int(list(self.load_items().keys())[-1])
def min_item_id(self) -> int:
return int(next(iter(self.load_items().keys())))
|
HNSnapshotClient
|
python
|
tiangolo__fastapi
|
tests/test_pydantic_v1_v2_mixed.py
|
{
"start": 620,
"end": 55952
}
|
class ____(NewBaseModel):
new_title: str
new_size: int
new_description: Union[str, None] = None
new_sub: NewSubItem
new_multi: List[NewSubItem] = []
app = FastAPI()
@app.post("/v1-to-v2/item")
def handle_v1_item_to_v2(data: Item) -> NewItem:
return NewItem(
new_title=data.title,
new_size=data.size,
new_description=data.description,
new_sub=NewSubItem(new_sub_name=data.sub.name),
new_multi=[NewSubItem(new_sub_name=s.name) for s in data.multi],
)
@app.post("/v1-to-v2/item-filter", response_model=NewItem)
def handle_v1_item_to_v2_filter(data: Item) -> Any:
result = {
"new_title": data.title,
"new_size": data.size,
"new_description": data.description,
"new_sub": {"new_sub_name": data.sub.name, "new_sub_secret": "sub_hidden"},
"new_multi": [
{"new_sub_name": s.name, "new_sub_secret": "sub_hidden"} for s in data.multi
],
"secret": "hidden_v1_to_v2",
}
return result
@app.post("/v2-to-v1/item")
def handle_v2_item_to_v1(data: NewItem) -> Item:
return Item(
title=data.new_title,
size=data.new_size,
description=data.new_description,
sub=SubItem(name=data.new_sub.new_sub_name),
multi=[SubItem(name=s.new_sub_name) for s in data.new_multi],
)
@app.post("/v2-to-v1/item-filter", response_model=Item)
def handle_v2_item_to_v1_filter(data: NewItem) -> Any:
result = {
"title": data.new_title,
"size": data.new_size,
"description": data.new_description,
"sub": {"name": data.new_sub.new_sub_name, "sub_secret": "sub_hidden"},
"multi": [
{"name": s.new_sub_name, "sub_secret": "sub_hidden"} for s in data.new_multi
],
"secret": "hidden_v2_to_v1",
}
return result
@app.post("/v1-to-v2/item-to-list")
def handle_v1_item_to_v2_list(data: Item) -> List[NewItem]:
converted = NewItem(
new_title=data.title,
new_size=data.size,
new_description=data.description,
new_sub=NewSubItem(new_sub_name=data.sub.name),
new_multi=[NewSubItem(new_sub_name=s.name) for s in data.multi],
)
return [converted, converted]
@app.post("/v1-to-v2/list-to-list")
def handle_v1_list_to_v2_list(data: List[Item]) -> List[NewItem]:
result = []
for item in data:
result.append(
NewItem(
new_title=item.title,
new_size=item.size,
new_description=item.description,
new_sub=NewSubItem(new_sub_name=item.sub.name),
new_multi=[NewSubItem(new_sub_name=s.name) for s in item.multi],
)
)
return result
@app.post("/v1-to-v2/list-to-list-filter", response_model=List[NewItem])
def handle_v1_list_to_v2_list_filter(data: List[Item]) -> Any:
result = []
for item in data:
converted = {
"new_title": item.title,
"new_size": item.size,
"new_description": item.description,
"new_sub": {"new_sub_name": item.sub.name, "new_sub_secret": "sub_hidden"},
"new_multi": [
{"new_sub_name": s.name, "new_sub_secret": "sub_hidden"}
for s in item.multi
],
"secret": "hidden_v2_to_v1",
}
result.append(converted)
return result
@app.post("/v1-to-v2/list-to-item")
def handle_v1_list_to_v2_item(data: List[Item]) -> NewItem:
if data:
item = data[0]
return NewItem(
new_title=item.title,
new_size=item.size,
new_description=item.description,
new_sub=NewSubItem(new_sub_name=item.sub.name),
new_multi=[NewSubItem(new_sub_name=s.name) for s in item.multi],
)
return NewItem(new_title="", new_size=0, new_sub=NewSubItem(new_sub_name=""))
@app.post("/v2-to-v1/item-to-list")
def handle_v2_item_to_v1_list(data: NewItem) -> List[Item]:
converted = Item(
title=data.new_title,
size=data.new_size,
description=data.new_description,
sub=SubItem(name=data.new_sub.new_sub_name),
multi=[SubItem(name=s.new_sub_name) for s in data.new_multi],
)
return [converted, converted]
@app.post("/v2-to-v1/list-to-list")
def handle_v2_list_to_v1_list(data: List[NewItem]) -> List[Item]:
result = []
for item in data:
result.append(
Item(
title=item.new_title,
size=item.new_size,
description=item.new_description,
sub=SubItem(name=item.new_sub.new_sub_name),
multi=[SubItem(name=s.new_sub_name) for s in item.new_multi],
)
)
return result
@app.post("/v2-to-v1/list-to-list-filter", response_model=List[Item])
def handle_v2_list_to_v1_list_filter(data: List[NewItem]) -> Any:
result = []
for item in data:
converted = {
"title": item.new_title,
"size": item.new_size,
"description": item.new_description,
"sub": {"name": item.new_sub.new_sub_name, "sub_secret": "sub_hidden"},
"multi": [
{"name": s.new_sub_name, "sub_secret": "sub_hidden"}
for s in item.new_multi
],
"secret": "hidden_v2_to_v1",
}
result.append(converted)
return result
@app.post("/v2-to-v1/list-to-item")
def handle_v2_list_to_v1_item(data: List[NewItem]) -> Item:
if data:
item = data[0]
return Item(
title=item.new_title,
size=item.new_size,
description=item.new_description,
sub=SubItem(name=item.new_sub.new_sub_name),
multi=[SubItem(name=s.new_sub_name) for s in item.new_multi],
)
return Item(title="", size=0, sub=SubItem(name=""))
client = TestClient(app)
def test_v1_to_v2_item():
response = client.post(
"/v1-to-v2/item",
json={
"title": "Old Item",
"size": 100,
"description": "V1 description",
"sub": {"name": "V1 Sub"},
"multi": [{"name": "M1"}, {"name": "M2"}],
},
)
assert response.status_code == 200, response.text
assert response.json() == {
"new_title": "Old Item",
"new_size": 100,
"new_description": "V1 description",
"new_sub": {"new_sub_name": "V1 Sub"},
"new_multi": [{"new_sub_name": "M1"}, {"new_sub_name": "M2"}],
}
def test_v1_to_v2_item_minimal():
response = client.post(
"/v1-to-v2/item",
json={"title": "Minimal", "size": 50, "sub": {"name": "MinSub"}},
)
assert response.status_code == 200, response.text
assert response.json() == {
"new_title": "Minimal",
"new_size": 50,
"new_description": None,
"new_sub": {"new_sub_name": "MinSub"},
"new_multi": [],
}
def test_v1_to_v2_item_filter():
response = client.post(
"/v1-to-v2/item-filter",
json={
"title": "Filtered Item",
"size": 50,
"sub": {"name": "Sub"},
"multi": [{"name": "Multi1"}],
},
)
assert response.status_code == 200, response.text
result = response.json()
assert result == snapshot(
{
"new_title": "Filtered Item",
"new_size": 50,
"new_description": None,
"new_sub": {"new_sub_name": "Sub"},
"new_multi": [{"new_sub_name": "Multi1"}],
}
)
# Verify secret fields are filtered out
assert "secret" not in result
assert "new_sub_secret" not in result["new_sub"]
assert "new_sub_secret" not in result["new_multi"][0]
def test_v2_to_v1_item():
response = client.post(
"/v2-to-v1/item",
json={
"new_title": "New Item",
"new_size": 200,
"new_description": "V2 description",
"new_sub": {"new_sub_name": "V2 Sub"},
"new_multi": [{"new_sub_name": "N1"}, {"new_sub_name": "N2"}],
},
)
assert response.status_code == 200, response.text
assert response.json() == {
"title": "New Item",
"size": 200,
"description": "V2 description",
"sub": {"name": "V2 Sub"},
"multi": [{"name": "N1"}, {"name": "N2"}],
}
def test_v2_to_v1_item_minimal():
response = client.post(
"/v2-to-v1/item",
json={
"new_title": "MinimalNew",
"new_size": 75,
"new_sub": {"new_sub_name": "MinNewSub"},
},
)
assert response.status_code == 200, response.text
assert response.json() == {
"title": "MinimalNew",
"size": 75,
"description": None,
"sub": {"name": "MinNewSub"},
"multi": [],
}
def test_v2_to_v1_item_filter():
response = client.post(
"/v2-to-v1/item-filter",
json={
"new_title": "Filtered New",
"new_size": 75,
"new_sub": {"new_sub_name": "NewSub"},
"new_multi": [],
},
)
assert response.status_code == 200, response.text
result = response.json()
assert result == snapshot(
{
"title": "Filtered New",
"size": 75,
"description": None,
"sub": {"name": "NewSub"},
"multi": [],
}
)
# Verify secret fields are filtered out
assert "secret" not in result
assert "sub_secret" not in result["sub"]
def test_v1_item_to_v2_list():
response = client.post(
"/v1-to-v2/item-to-list",
json={
"title": "Single to List",
"size": 150,
"description": "Convert to list",
"sub": {"name": "Sub1"},
"multi": [],
},
)
assert response.status_code == 200, response.text
result = response.json()
assert result == [
{
"new_title": "Single to List",
"new_size": 150,
"new_description": "Convert to list",
"new_sub": {"new_sub_name": "Sub1"},
"new_multi": [],
},
{
"new_title": "Single to List",
"new_size": 150,
"new_description": "Convert to list",
"new_sub": {"new_sub_name": "Sub1"},
"new_multi": [],
},
]
def test_v1_list_to_v2_list():
response = client.post(
"/v1-to-v2/list-to-list",
json=[
{"title": "Item1", "size": 10, "sub": {"name": "Sub1"}},
{
"title": "Item2",
"size": 20,
"description": "Second item",
"sub": {"name": "Sub2"},
"multi": [{"name": "M1"}, {"name": "M2"}],
},
{"title": "Item3", "size": 30, "sub": {"name": "Sub3"}},
],
)
assert response.status_code == 200, response.text
assert response.json() == [
{
"new_title": "Item1",
"new_size": 10,
"new_description": None,
"new_sub": {"new_sub_name": "Sub1"},
"new_multi": [],
},
{
"new_title": "Item2",
"new_size": 20,
"new_description": "Second item",
"new_sub": {"new_sub_name": "Sub2"},
"new_multi": [{"new_sub_name": "M1"}, {"new_sub_name": "M2"}],
},
{
"new_title": "Item3",
"new_size": 30,
"new_description": None,
"new_sub": {"new_sub_name": "Sub3"},
"new_multi": [],
},
]
def test_v1_list_to_v2_list_filter():
response = client.post(
"/v1-to-v2/list-to-list-filter",
json=[{"title": "FilterMe", "size": 30, "sub": {"name": "SubF"}}],
)
assert response.status_code == 200, response.text
result = response.json()
assert result == snapshot(
[
{
"new_title": "FilterMe",
"new_size": 30,
"new_description": None,
"new_sub": {"new_sub_name": "SubF"},
"new_multi": [],
}
]
)
# Verify secret fields are filtered out
assert "secret" not in result[0]
assert "new_sub_secret" not in result[0]["new_sub"]
def test_v1_list_to_v2_item():
response = client.post(
"/v1-to-v2/list-to-item",
json=[
{"title": "First", "size": 100, "sub": {"name": "FirstSub"}},
{"title": "Second", "size": 200, "sub": {"name": "SecondSub"}},
],
)
assert response.status_code == 200, response.text
assert response.json() == {
"new_title": "First",
"new_size": 100,
"new_description": None,
"new_sub": {"new_sub_name": "FirstSub"},
"new_multi": [],
}
def test_v1_list_to_v2_item_empty():
response = client.post("/v1-to-v2/list-to-item", json=[])
assert response.status_code == 200, response.text
assert response.json() == {
"new_title": "",
"new_size": 0,
"new_description": None,
"new_sub": {"new_sub_name": ""},
"new_multi": [],
}
def test_v2_item_to_v1_list():
response = client.post(
"/v2-to-v1/item-to-list",
json={
"new_title": "Single New",
"new_size": 250,
"new_description": "New to list",
"new_sub": {"new_sub_name": "NewSub"},
"new_multi": [],
},
)
assert response.status_code == 200, response.text
assert response.json() == [
{
"title": "Single New",
"size": 250,
"description": "New to list",
"sub": {"name": "NewSub"},
"multi": [],
},
{
"title": "Single New",
"size": 250,
"description": "New to list",
"sub": {"name": "NewSub"},
"multi": [],
},
]
def test_v2_list_to_v1_list():
response = client.post(
"/v2-to-v1/list-to-list",
json=[
{"new_title": "New1", "new_size": 15, "new_sub": {"new_sub_name": "NS1"}},
{
"new_title": "New2",
"new_size": 25,
"new_description": "Second new",
"new_sub": {"new_sub_name": "NS2"},
"new_multi": [{"new_sub_name": "NM1"}],
},
],
)
assert response.status_code == 200, response.text
assert response.json() == [
{
"title": "New1",
"size": 15,
"description": None,
"sub": {"name": "NS1"},
"multi": [],
},
{
"title": "New2",
"size": 25,
"description": "Second new",
"sub": {"name": "NS2"},
"multi": [{"name": "NM1"}],
},
]
def test_v2_list_to_v1_list_filter():
response = client.post(
"/v2-to-v1/list-to-list-filter",
json=[
{
"new_title": "FilterNew",
"new_size": 35,
"new_sub": {"new_sub_name": "NSF"},
}
],
)
assert response.status_code == 200, response.text
result = response.json()
assert result == snapshot(
[
{
"title": "FilterNew",
"size": 35,
"description": None,
"sub": {"name": "NSF"},
"multi": [],
}
]
)
# Verify secret fields are filtered out
assert "secret" not in result[0]
assert "sub_secret" not in result[0]["sub"]
def test_v2_list_to_v1_item():
response = client.post(
"/v2-to-v1/list-to-item",
json=[
{
"new_title": "FirstNew",
"new_size": 300,
"new_sub": {"new_sub_name": "FNS"},
},
{
"new_title": "SecondNew",
"new_size": 400,
"new_sub": {"new_sub_name": "SNS"},
},
],
)
assert response.status_code == 200, response.text
assert response.json() == {
"title": "FirstNew",
"size": 300,
"description": None,
"sub": {"name": "FNS"},
"multi": [],
}
def test_v2_list_to_v1_item_empty():
response = client.post("/v2-to-v1/list-to-item", json=[])
assert response.status_code == 200, response.text
assert response.json() == {
"title": "",
"size": 0,
"description": None,
"sub": {"name": ""},
"multi": [],
}
def test_v1_to_v2_validation_error():
response = client.post("/v1-to-v2/item", json={"title": "Missing fields"})
assert response.status_code == 422, response.text
assert response.json() == snapshot(
{
"detail": [
{
"loc": ["body", "size"],
"msg": "field required",
"type": "value_error.missing",
},
{
"loc": ["body", "sub"],
"msg": "field required",
"type": "value_error.missing",
},
]
}
)
def test_v1_to_v2_nested_validation_error():
response = client.post(
"/v1-to-v2/item",
json={"title": "Bad sub", "size": 100, "sub": {"wrong_field": "value"}},
)
assert response.status_code == 422, response.text
assert response.json() == snapshot(
{
"detail": [
{
"loc": ["body", "sub", "name"],
"msg": "field required",
"type": "value_error.missing",
}
]
}
)
def test_v1_to_v2_type_validation_error():
response = client.post(
"/v1-to-v2/item",
json={"title": "Bad type", "size": "not_a_number", "sub": {"name": "Sub"}},
)
assert response.status_code == 422, response.text
assert response.json() == snapshot(
{
"detail": [
{
"loc": ["body", "size"],
"msg": "value is not a valid integer",
"type": "type_error.integer",
}
]
}
)
def test_v2_to_v1_validation_error():
response = client.post(
"/v2-to-v1/item",
json={"new_title": "Missing fields"},
)
assert response.status_code == 422, response.text
assert response.json() == snapshot(
{
"detail": pydantic_snapshot(
v2=snapshot(
[
{
"type": "missing",
"loc": ["body", "new_size"],
"msg": "Field required",
"input": {"new_title": "Missing fields"},
},
{
"type": "missing",
"loc": ["body", "new_sub"],
"msg": "Field required",
"input": {"new_title": "Missing fields"},
},
]
),
v1=snapshot(
[
{
"loc": ["body", "new_size"],
"msg": "field required",
"type": "value_error.missing",
},
{
"loc": ["body", "new_sub"],
"msg": "field required",
"type": "value_error.missing",
},
]
),
)
}
)
def test_v2_to_v1_nested_validation_error():
response = client.post(
"/v2-to-v1/item",
json={
"new_title": "Bad sub",
"new_size": 200,
"new_sub": {"wrong_field": "value"},
},
)
assert response.status_code == 422, response.text
assert response.json() == snapshot(
{
"detail": [
pydantic_snapshot(
v2=snapshot(
{
"type": "missing",
"loc": ["body", "new_sub", "new_sub_name"],
"msg": "Field required",
"input": {"wrong_field": "value"},
}
),
v1=snapshot(
{
"loc": ["body", "new_sub", "new_sub_name"],
"msg": "field required",
"type": "value_error.missing",
}
),
)
]
}
)
def test_v1_list_validation_error():
response = client.post(
"/v1-to-v2/list-to-list",
json=[
{"title": "Valid", "size": 10, "sub": {"name": "S"}},
{"title": "Invalid"},
],
)
assert response.status_code == 422, response.text
assert response.json() == snapshot(
{
"detail": [
{
"loc": ["body", 1, "size"],
"msg": "field required",
"type": "value_error.missing",
},
{
"loc": ["body", 1, "sub"],
"msg": "field required",
"type": "value_error.missing",
},
]
}
)
def test_v2_list_validation_error():
response = client.post(
"/v2-to-v1/list-to-list",
json=[
{"new_title": "Valid", "new_size": 10, "new_sub": {"new_sub_name": "NS"}},
{"new_title": "Invalid"},
],
)
assert response.status_code == 422, response.text
assert response.json() == snapshot(
{
"detail": pydantic_snapshot(
v2=snapshot(
[
{
"type": "missing",
"loc": ["body", 1, "new_size"],
"msg": "Field required",
"input": {"new_title": "Invalid"},
},
{
"type": "missing",
"loc": ["body", 1, "new_sub"],
"msg": "Field required",
"input": {"new_title": "Invalid"},
},
]
),
v1=snapshot(
[
{
"loc": ["body", 1, "new_size"],
"msg": "field required",
"type": "value_error.missing",
},
{
"loc": ["body", 1, "new_sub"],
"msg": "field required",
"type": "value_error.missing",
},
]
),
)
}
)
def test_invalid_list_structure_v1():
response = client.post(
"/v1-to-v2/list-to-list",
json={"title": "Not a list", "size": 100, "sub": {"name": "Sub"}},
)
assert response.status_code == 422, response.text
assert response.json() == snapshot(
{
"detail": [
{
"loc": ["body"],
"msg": "value is not a valid list",
"type": "type_error.list",
}
]
}
)
def test_invalid_list_structure_v2():
response = client.post(
"/v2-to-v1/list-to-list",
json={
"new_title": "Not a list",
"new_size": 100,
"new_sub": {"new_sub_name": "Sub"},
},
)
assert response.status_code == 422, response.text
assert response.json() == snapshot(
{
"detail": pydantic_snapshot(
v2=snapshot(
[
{
"type": "list_type",
"loc": ["body"],
"msg": "Input should be a valid list",
"input": {
"new_title": "Not a list",
"new_size": 100,
"new_sub": {"new_sub_name": "Sub"},
},
}
]
),
v1=snapshot(
[
{
"loc": ["body"],
"msg": "value is not a valid list",
"type": "type_error.list",
}
]
),
)
}
)
def test_openapi_schema():
response = client.get("/openapi.json")
assert response.status_code == 200, response.text
assert response.json() == snapshot(
{
"openapi": "3.1.0",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/v1-to-v2/item": {
"post": {
"summary": "Handle V1 Item To V2",
"operationId": "handle_v1_item_to_v2_v1_to_v2_item_post",
"requestBody": {
"content": {
"application/json": {
"schema": pydantic_snapshot(
v2=snapshot(
{
"allOf": [
{
"$ref": "#/components/schemas/Item"
}
],
"title": "Data",
}
),
v1=snapshot(
{"$ref": "#/components/schemas/Item"}
),
)
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/NewItem"
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/v1-to-v2/item-filter": {
"post": {
"summary": "Handle V1 Item To V2 Filter",
"operationId": "handle_v1_item_to_v2_filter_v1_to_v2_item_filter_post",
"requestBody": {
"content": {
"application/json": {
"schema": pydantic_snapshot(
v2=snapshot(
{
"allOf": [
{
"$ref": "#/components/schemas/Item"
}
],
"title": "Data",
}
),
v1=snapshot(
{"$ref": "#/components/schemas/Item"}
),
)
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/NewItem"
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/v2-to-v1/item": {
"post": {
"summary": "Handle V2 Item To V1",
"operationId": "handle_v2_item_to_v1_v2_to_v1_item_post",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/NewItem"}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/v2-to-v1/item-filter": {
"post": {
"summary": "Handle V2 Item To V1 Filter",
"operationId": "handle_v2_item_to_v1_filter_v2_to_v1_item_filter_post",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/NewItem"}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/v1-to-v2/item-to-list": {
"post": {
"summary": "Handle V1 Item To V2 List",
"operationId": "handle_v1_item_to_v2_list_v1_to_v2_item_to_list_post",
"requestBody": {
"content": {
"application/json": {
"schema": pydantic_snapshot(
v2=snapshot(
{
"allOf": [
{
"$ref": "#/components/schemas/Item"
}
],
"title": "Data",
}
),
v1=snapshot(
{"$ref": "#/components/schemas/Item"}
),
)
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"items": {
"$ref": "#/components/schemas/NewItem"
},
"type": "array",
"title": "Response Handle V1 Item To V2 List V1 To V2 Item To List Post",
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/v1-to-v2/list-to-list": {
"post": {
"summary": "Handle V1 List To V2 List",
"operationId": "handle_v1_list_to_v2_list_v1_to_v2_list_to_list_post",
"requestBody": {
"content": {
"application/json": {
"schema": {
"items": {"$ref": "#/components/schemas/Item"},
"type": "array",
"title": "Data",
}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"items": {
"$ref": "#/components/schemas/NewItem"
},
"type": "array",
"title": "Response Handle V1 List To V2 List V1 To V2 List To List Post",
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/v1-to-v2/list-to-list-filter": {
"post": {
"summary": "Handle V1 List To V2 List Filter",
"operationId": "handle_v1_list_to_v2_list_filter_v1_to_v2_list_to_list_filter_post",
"requestBody": {
"content": {
"application/json": {
"schema": {
"items": {"$ref": "#/components/schemas/Item"},
"type": "array",
"title": "Data",
}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"items": {
"$ref": "#/components/schemas/NewItem"
},
"type": "array",
"title": "Response Handle V1 List To V2 List Filter V1 To V2 List To List Filter Post",
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/v1-to-v2/list-to-item": {
"post": {
"summary": "Handle V1 List To V2 Item",
"operationId": "handle_v1_list_to_v2_item_v1_to_v2_list_to_item_post",
"requestBody": {
"content": {
"application/json": {
"schema": {
"items": {"$ref": "#/components/schemas/Item"},
"type": "array",
"title": "Data",
}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/NewItem"
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/v2-to-v1/item-to-list": {
"post": {
"summary": "Handle V2 Item To V1 List",
"operationId": "handle_v2_item_to_v1_list_v2_to_v1_item_to_list_post",
"requestBody": {
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/NewItem"}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"items": {
"$ref": "#/components/schemas/Item"
},
"type": "array",
"title": "Response Handle V2 Item To V1 List V2 To V1 Item To List Post",
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/v2-to-v1/list-to-list": {
"post": {
"summary": "Handle V2 List To V1 List",
"operationId": "handle_v2_list_to_v1_list_v2_to_v1_list_to_list_post",
"requestBody": {
"content": {
"application/json": {
"schema": {
"items": {
"$ref": "#/components/schemas/NewItem"
},
"type": "array",
"title": "Data",
}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"items": {
"$ref": "#/components/schemas/Item"
},
"type": "array",
"title": "Response Handle V2 List To V1 List V2 To V1 List To List Post",
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/v2-to-v1/list-to-list-filter": {
"post": {
"summary": "Handle V2 List To V1 List Filter",
"operationId": "handle_v2_list_to_v1_list_filter_v2_to_v1_list_to_list_filter_post",
"requestBody": {
"content": {
"application/json": {
"schema": {
"items": {
"$ref": "#/components/schemas/NewItem"
},
"type": "array",
"title": "Data",
}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"items": {
"$ref": "#/components/schemas/Item"
},
"type": "array",
"title": "Response Handle V2 List To V1 List Filter V2 To V1 List To List Filter Post",
}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
"/v2-to-v1/list-to-item": {
"post": {
"summary": "Handle V2 List To V1 Item",
"operationId": "handle_v2_list_to_v1_item_v2_to_v1_list_to_item_post",
"requestBody": {
"content": {
"application/json": {
"schema": {
"items": {
"$ref": "#/components/schemas/NewItem"
},
"type": "array",
"title": "Data",
}
}
},
"required": True,
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {"$ref": "#/components/schemas/Item"}
}
},
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
},
},
},
}
},
},
"components": {
"schemas": {
"HTTPValidationError": {
"properties": {
"detail": {
"items": {
"$ref": "#/components/schemas/ValidationError"
},
"type": "array",
"title": "Detail",
}
},
"type": "object",
"title": "HTTPValidationError",
},
"Item": {
"properties": {
"title": {"type": "string", "title": "Title"},
"size": {"type": "integer", "title": "Size"},
"description": {"type": "string", "title": "Description"},
"sub": {"$ref": "#/components/schemas/SubItem"},
"multi": {
"items": {"$ref": "#/components/schemas/SubItem"},
"type": "array",
"title": "Multi",
"default": [],
},
},
"type": "object",
"required": ["title", "size", "sub"],
"title": "Item",
},
"NewItem": {
"properties": {
"new_title": {"type": "string", "title": "New Title"},
"new_size": {"type": "integer", "title": "New Size"},
"new_description": pydantic_snapshot(
v2=snapshot(
{
"anyOf": [{"type": "string"}, {"type": "null"}],
"title": "New Description",
}
),
v1=snapshot(
{"type": "string", "title": "New Description"}
),
),
"new_sub": {"$ref": "#/components/schemas/NewSubItem"},
"new_multi": {
"items": {"$ref": "#/components/schemas/NewSubItem"},
"type": "array",
"title": "New Multi",
"default": [],
},
},
"type": "object",
"required": ["new_title", "new_size", "new_sub"],
"title": "NewItem",
},
"NewSubItem": {
"properties": {
"new_sub_name": {"type": "string", "title": "New Sub Name"}
},
"type": "object",
"required": ["new_sub_name"],
"title": "NewSubItem",
},
"SubItem": {
"properties": {"name": {"type": "string", "title": "Name"}},
"type": "object",
"required": ["name"],
"title": "SubItem",
},
"ValidationError": {
"properties": {
"loc": {
"items": {
"anyOf": [{"type": "string"}, {"type": "integer"}]
},
"type": "array",
"title": "Location",
},
"msg": {"type": "string", "title": "Message"},
"type": {"type": "string", "title": "Error Type"},
},
"type": "object",
"required": ["loc", "msg", "type"],
"title": "ValidationError",
},
}
},
}
)
|
NewItem
|
python
|
pydantic__pydantic
|
pydantic-core/tests/test_json.py
|
{
"start": 12034,
"end": 12122
}
|
class ____(type):
def __repr__(self):
raise ValueError('bad repr')
|
BedReprMeta
|
python
|
charliermarsh__ruff
|
python/ruff-ecosystem/ruff_ecosystem/types.py
|
{
"start": 630,
"end": 2101
}
|
class ____(Serializable):
def __init__(self, lines: Iterable[str], leading_spaces: int = 0) -> None:
self.lines = list(lines)
# Compute added and removed lines once
self.added = list(
line[2:]
for line in self.lines
if line.startswith("+" + " " * leading_spaces)
# Do not include patch headers
and not line.startswith("+++")
)
self.removed = list(
line[2:]
for line in self.lines
if line.startswith("-" + " " * leading_spaces)
# Do not include patch headers
and not line.startswith("---")
)
def __bool__(self) -> bool:
return bool(self.added or self.removed)
def __iter__(self) -> Generator[str, None, None]:
yield from self.lines
@property
def lines_added(self):
return len(self.added)
@property
def lines_removed(self):
return len(self.removed)
@classmethod
def from_pair(cls, baseline: Sequence[str], comparison: Sequence[str]):
"""
Construct a diff from before and after.
"""
return cls(difflib.ndiff(baseline, comparison), leading_spaces=1)
def without_unchanged_lines(self) -> Diff:
return Diff(
line for line in self.lines if line.startswith("+") or line.startswith("-")
)
def jsonable(self) -> Any:
return self.lines
@dataclass(frozen=True)
|
Diff
|
python
|
weaviate__weaviate-python-client
|
weaviate/rbac/models.py
|
{
"start": 636,
"end": 713
}
|
class ____:
user_id: str
user_type: UserTypes
@dataclass
|
UserAssignment
|
python
|
pytorch__pytorch
|
test/test_nnapi.py
|
{
"start": 715,
"end": 25713
}
|
class ____(TestCase):
def setUp(self):
super().setUp()
# Avoid saturation in fbgemm
torch.backends.quantized.engine = "qnnpack"
libneuralnetworks_path = os.environ.get("LIBNEURALNETWORKS_PATH")
if libneuralnetworks_path:
ctypes.cdll.LoadLibrary(libneuralnetworks_path)
print("Will attempt to run NNAPI models.")
self.can_run_nnapi = True
else:
self.can_run_nnapi = False
# Created for easy override by subclasses (eg TestNnapiBackend)
def call_lowering_to_nnapi(self, traced_module, args):
return convert_model_to_nnapi(traced_module, args)
# Created for subclasses to set can_run_nnapi (eg TestNnapiBackend)
def set_can_run_nnapi(self, can_run):
self.can_run_nnapi = can_run
def check(
self,
module,
arg_or_args,
*,
trace_args=None,
convert_args=None,
atol_rtol=None,
limit=None,
expected_memory_format=None,
):
with torch.no_grad():
if isinstance(arg_or_args, torch.Tensor):
args = [arg_or_args]
else:
args = arg_or_args
module.eval()
traced = torch.jit.trace(module, trace_args or args)
nnapi_module = self.call_lowering_to_nnapi(traced, convert_args or args)
if not self.can_run_nnapi:
# Only test that the model was converted successfully.
return
eager_output = module(*args)
nnapi_output = nnapi_module(*args)
kwargs = {}
if atol_rtol is not None:
kwargs["atol"] = atol_rtol[0]
kwargs["rtol"] = atol_rtol[1]
self.assertEqual(eager_output, nnapi_output, **kwargs)
if limit is not None:
mismatches = eager_output.int_repr().to(
torch.int32
) - nnapi_output.int_repr().to(torch.int32)
if mismatches.count_nonzero() > limit:
# Too many mismatches. Re-run the check with no tolerance
# to get a nice message.
self.assertEqual(eager_output, nnapi_output, atol=0, rtol=0)
if expected_memory_format:
self.assertTrue(
nnapi_output.is_contiguous(memory_format=expected_memory_format)
)
def float_and_quant_and_nhwc(self, inp_float, scale, zero_point):
torch.manual_seed(29)
inp_quant = qpt(inp_float, 0.03, 128)
return [
("float", inp_float),
("float-nhwc", nhwc(inp_float)),
("quant", inp_quant),
("quant-nhwc", nhwc(inp_quant)),
]
def test_prelu(self):
arg = torch.tensor([[1.0, -1.0, 2.0, -2.0]]).unsqueeze(-1).unsqueeze(-1)
single_a = torch.nn.PReLU()
self.check(single_a, arg)
multi_a = torch.nn.PReLU(4)
with torch.no_grad():
multi_a.weight.copy_(torch.tensor([0.1, 0.2, 0.3, 0.4]))
self.check(multi_a, nhwc(arg))
# Test flexible size
self.check(
multi_a,
arg,
trace_args=[torch.zeros(1, 4, 3, 3)],
convert_args=[nhwc(torch.zeros(1, 4, 0, 0))],
)
def test_quantize(self):
self.check(
torch.ao.nn.quantized.Quantize(0.25, 2, torch.quint8),
nhwc(torch.tensor([[[[1.0]], [[2.0]]]])),
)
def test_dequantize(self):
self.check(
torch.ao.nn.quantized.DeQuantize(), nhwc(qpt([[[[1.0]], [[2.0]]]], 0.25, 2))
)
def test_unsqueeze(self):
class UnsqueezeModule(torch.nn.Module):
def __init__(self, dim):
super().__init__()
self.dim = dim
def forward(self, arg):
return arg.unsqueeze(self.dim)
self.check(UnsqueezeModule(-2), torch.randn(4, 2, 2))
self.check(UnsqueezeModule(-1), torch.randn(4, 2, 2))
self.check(UnsqueezeModule(0), torch.randn(4, 2, 2))
self.check(UnsqueezeModule(1), torch.randn(4, 2, 2))
self.check(UnsqueezeModule(2), torch.randn(4, 2, 2))
def test_reshape(self):
class ReshapeModule(torch.nn.Module):
def __init__(self, shape):
super().__init__()
self.shape = shape
def forward(self, arg):
return arg.reshape(self.shape)
self.check(ReshapeModule((2, 4)), torch.randn(4, 2, 1, 1))
self.check(ReshapeModule((8, -1)), nhwc(torch.randn(4, 2, 1, 1)))
with self.assertRaisesRegex(Exception, "target size"):
self.check(ReshapeModule((2, 4)), nhwc(torch.randn(4, 2, 1, 1)))
def test_flatten(self):
for mod in [
torch.nn.Flatten(),
torch.nn.Flatten(start_dim=2, end_dim=3),
torch.nn.Flatten(start_dim=2, end_dim=4),
torch.nn.Flatten(start_dim=0, end_dim=-2),
torch.nn.Flatten(start_dim=0, end_dim=4),
]:
self.check(mod, torch.randn(4, 2, 1, 3, 7))
# flex inputs
self.check(
torch.nn.Flatten(),
torch.randn(4, 2, 1, 3, 7),
convert_args=[torch.zeros(0, 2, 1, 3, 7)],
)
# channels last
self.check(torch.nn.Flatten(), nhwc(torch.randn(2, 1, 4, 7)))
self.check(torch.nn.Flatten(), nhwc(torch.randn(2, 3, 1, 1)))
# Exceptions
with self.assertRaisesRegex(Exception, "not supported on NHWC"):
self.check(torch.nn.Flatten(), nhwc(torch.randn(1, 3, 4, 4)))
with self.assertRaisesRegex(
Exception, "Flattening flexible dims is not supported yet"
):
self.check(torch.nn.Flatten(), torch.randn(4, 2, 0, 0, 7))
with self.assertRaisesRegex(Exception, "Only 1 dim"):
self.check(
torch.nn.Flatten(start_dim=1, end_dim=-2), torch.randn(0, 2, 1, 3, 0)
)
def test_slice(self):
class SliceModule(torch.nn.Module):
def __init__(self, start, stop, step):
super().__init__()
self.start = start
self.stop = stop
self.step = step
def forward(self, t):
return t[1:, self.start : self.stop : self.step, :]
class SliceModule2(torch.nn.Module):
def forward(self, t):
return t[3:]
self.check(SliceModule(1, 5, 2), torch.randn(4, 6, 2))
self.check(SliceModule2(), torch.randn(5))
# flex inputs
self.check(
SliceModule(1, 5, 2),
torch.randn(4, 6, 2),
convert_args=[torch.zeros(4, 6, 0)],
)
with self.assertRaisesRegex(Exception, "slice with flexible shape"):
self.check(
SliceModule(1, 5, 2),
torch.randn(4, 6, 2),
convert_args=[torch.zeros(0, 0, 0)],
)
def test_cat(self):
class CatModule(torch.nn.Module):
def __init__(self, dim):
super().__init__()
self.dim = dim
def forward(self, t1, t2):
return torch.cat([t1, t2], self.dim)
self.check(
CatModule(0),
[
torch.randn(1, 2, 3, 3),
torch.randn(2, 2, 3, 3),
],
)
self.check(
CatModule(1),
[
torch.randn(1, 2, 3, 3),
torch.randn(1, 4, 3, 3),
],
)
self.check(
CatModule(1),
[
nhwc(torch.randn(1, 2, 3, 3)),
nhwc(torch.randn(1, 4, 3, 3)),
],
)
self.check(
CatModule(1),
[
torch.randn(1, 2, 3, 3),
torch.randn(1, 4, 3, 3),
],
convert_args=[torch.zeros(0, 0, 0, 0), torch.zeros(0, 0, 0, 0)],
)
def test_pointwise_unary(self):
for op in ["relu", "sigmoid"]:
with self.subTest(op):
class UnaryModule(torch.nn.Module):
def forward(self, arg):
if op == "relu":
return torch.nn.functional.relu(arg)
if op == "sigmoid":
return torch.sigmoid(arg)
raise Exception("Bad op") # noqa: TRY002
self.check(UnaryModule(), torch.tensor([-1.0, 1.0]))
self.check(
UnaryModule(),
qpt(torch.tensor([-1.0, 1.0]), 1.0 / 256, 0),
)
def test_pointwise_binary(self):
for op in ["add", "sub", "mul", "div"]:
with self.subTest(op):
class BinaryModule(torch.nn.Module):
def forward(self, lhs, rhs):
if op == "add":
return lhs + rhs
if op == "sub":
return lhs - rhs
if op == "mul":
return lhs * rhs
if op == "div":
return lhs / rhs
raise Exception("Bad op") # noqa: TRY002
self.check(
BinaryModule(),
[
torch.tensor([1.0, 2.0]),
torch.tensor([3.0, 4.0]),
],
)
self.check(
BinaryModule(),
[
torch.tensor([[1.0, 2.0]]),
torch.tensor([[3.0, 4.0], [5.0, 6.0]]),
],
)
with self.assertRaisesRegex(Exception, "Non-equal-rank broadcast"):
self.check(
BinaryModule(),
[
torch.tensor([1.0, 2.0]),
torch.tensor([[3.0, 4.0], [5.0, 6.0]]),
],
)
def test_pointwise_binary_const(self):
const = torch.randn(1, 4, 6, 6)
class ArgPlusConst(torch.nn.Module):
def forward(self, arg):
return arg + const
class ConstPlusArg(torch.nn.Module):
def forward(self, arg):
return const + arg
arg_contig = torch.randn(2, 4, 6, 6)
arg_nhwc = nhwc(torch.randn(2, 4, 6, 6))
for mod_class in [ArgPlusConst, ConstPlusArg]:
for use_nhwc in [False, True]:
with self.subTest(mod_class=mod_class.__name__, use_nhwc=use_nhwc):
arg = arg_nhwc if use_nhwc else arg_contig
memory_format = (
torch.channels_last if use_nhwc else torch.contiguous_format
)
self.check(mod_class(), arg, expected_memory_format=memory_format)
def test_hardtanh(self):
inp = torch.tensor([-2.0, -0.5, 0.5, 2.0, 7.0])
self.check(torch.nn.Hardtanh(), inp)
self.check(torch.nn.Hardtanh(0.0, 6.0), inp)
with self.assertRaisesRegex(Exception, "hardtanh with args"):
self.check(torch.nn.Hardtanh(0.0, 5.0), inp)
def test_softmax(self):
inp = torch.tensor([[-2.0, -0.5], [0.5, 2.0]])
self.check(torch.nn.Softmax(), inp)
self.check(torch.nn.Softmax(dim=0), inp)
# Test flexible size
self.check(
torch.nn.Softmax(),
inp,
convert_args=[torch.zeros(0, 0)],
)
def test_to(self):
class ToCPU(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.prelu = torch.nn.PReLU()
def forward(self, x):
y = x.to("cpu")
# add prelu since input operand can't be output
return self.prelu(y)
arg = torch.randn(1, 2, 3, 3)
self.check(ToCPU(), arg)
# Test flexible size
self.check(
ToCPU(),
arg,
convert_args=[torch.zeros(1, 2, 0, 0)],
)
def test_detach(self):
class DetachModule(torch.nn.Module):
def forward(self, x):
y = x.detach()
return torch.nn.functional.relu(y)
self.check(DetachModule(), torch.randn(1, 2, 3, 3))
self.check(
DetachModule(),
torch.randn(1, 2, 3, 3),
convert_args=[torch.zeros(1, 2, 0, 0)],
)
def test_log_softmax(self):
inp = torch.randn(3, 10)
self.check(torch.nn.LogSoftmax(), inp)
self.check(torch.nn.LogSoftmax(0), inp)
def test_mean(self):
class MeanModule(torch.nn.Module):
def __init__(self, dim, keep=False):
super().__init__()
self.dim = dim
self.keep = keep
def forward(self, t):
return torch.mean(t, dim=self.dim, keepdim=self.keep)
self.check(MeanModule(0), torch.randn(2, 3))
self.check(MeanModule(1), torch.randn(2, 3))
self.check(MeanModule([2, 3]), torch.randn(2, 3, 6, 6))
self.check(MeanModule([2, 3]), nhwc(torch.randn(2, 3, 6, 6)))
self.check(MeanModule([-1, -2]), nhwc(torch.randn(2, 3, 6, 6)))
self.check(MeanModule([-1, -2], keep=True), nhwc(torch.randn(2, 3, 6, 6)))
def test_max_pool2d(self):
for name, inp in self.float_and_quant_and_nhwc(
torch.randn(2, 3, 12, 16), 0.3, 128
):
with self.subTest(name):
self.check(torch.nn.MaxPool2d(2), inp)
self.check(torch.nn.MaxPool2d((3, 4)), inp)
self.check(torch.nn.MaxPool2d((3, 4), (1, 2)), inp)
def test_avg_pool2d(self):
for name, inp in self.float_and_quant_and_nhwc(
torch.randn(2, 3, 12, 16), 0.3, 128
):
with self.subTest(name):
atol_rtol = None
limit = None
convert_dims = (2, 3, 0, 0)
convert_arg = torch.zeros(*convert_dims)
for model in (
torch.nn.AvgPool2d(2),
torch.nn.AvgPool2d((3, 4)),
torch.nn.AvgPool2d((3, 4), (1, 2)),
):
if "quant" in name:
atol_rtol = (1, 0)
limit = model(inp).numel()
convert_arg = qpt(torch.zeros(*convert_dims), 1.0 / 16, 128)
if "nhwc" in name:
convert_arg = nhwc(convert_arg)
self.check(model, inp, atol_rtol=atol_rtol, limit=limit)
self.check(
model,
inp,
convert_args=[convert_arg],
atol_rtol=atol_rtol,
limit=limit,
)
def test_adaptive_avg_pool2d(self):
for name, inp in self.float_and_quant_and_nhwc(
torch.randn(2, 3, 12, 16), 0.3, 128
):
with self.subTest(name):
self.check(torch.nn.AdaptiveAvgPool2d((1, 1)), inp)
with self.assertRaisesRegex(Exception, "with output size"):
self.check(torch.nn.AdaptiveAvgPool2d((2, 2)), inp)
def test_upsample_nearest2d(self):
convert_args = dict(
self.float_and_quant_and_nhwc(torch.randn(2, 3, 0, 0), 0.3, 128)
)
for name, inp in self.float_and_quant_and_nhwc(
torch.randn(2, 3, 12, 16), 0.3, 128
):
with self.subTest(name):
self.check(torch.nn.UpsamplingNearest2d(size=(16, 20)), inp)
self.check(torch.nn.UpsamplingNearest2d(size=(24, 32)), inp)
self.check(torch.nn.UpsamplingNearest2d(size=(36, 48)), inp)
self.check(torch.nn.UpsamplingNearest2d(scale_factor=(1.5, 1.5)), inp)
self.check(torch.nn.UpsamplingNearest2d(scale_factor=(2.0, 2.0)), inp)
self.check(torch.nn.UpsamplingNearest2d(scale_factor=(3.0, 3.0)), inp)
self.check(
torch.nn.UpsamplingNearest2d(size=(24, 32)),
inp,
convert_args=[convert_args[name]],
)
self.check(
torch.nn.UpsamplingNearest2d(scale_factor=(2.0, 2.0)),
inp,
convert_args=[convert_args[name]],
)
def test_linear(self):
torch.manual_seed(29)
self.check(torch.nn.Linear(16, 32), torch.randn(2, 16))
self.check(
torch.nn.Linear(16, 32),
torch.randn(2, 16),
convert_args=[torch.zeros(0, 16)],
)
def test_conv2d(self):
cases = [
# in_ch, out_ch, kernel, stride, padding, groups, bias, input_dim, name
(4, 8, (3, 3), 1, 0, 1, 1, (2, 4, 16, 16), "3x3"), # noqa: E201,E241
(4, 8, (3, 3), 1, 0, 1, 0, (2, 4, 16, 16), "3x3nobias"), # noqa: E201,E241
(4, 16, (3, 3), 1, 1, 1, 1, (2, 4, 16, 16), "3x3p1"), # noqa: E201,E241
(8, 8, (3, 3), 2, 0, 1, 1, (2, 8, 16, 16), "3x3s2"), # noqa: E201,E241
(4, 8, (5, 5), 1, 0, 1, 1, (2, 4, 16, 16), "5x5"), # noqa: E201,E241
(4, 4, (3, 3), 1, 0, 4, 1, (2, 4, 16, 16), "3x3dw"), # noqa: E201,E241
(8, 4, (1, 1), 1, 0, 1, 1, (2, 8, 16, 16), "1x1"), # noqa: E201,E241
]
for kind in ["float", "float-nhwc", "quant", "quant-nhwc"]:
for case in cases:
(
in_ch,
out_ch,
kernel,
stride,
padding,
groups,
bias,
input_dim,
name,
) = case
with self.subTest(f"{kind}-{name}"):
inp = torch.randn(input_dim)
model = torch.nn.Conv2d(
in_ch,
out_ch,
kernel,
stride,
padding,
groups=groups,
bias=bool(bias),
)
output_size = model(inp).numel()
atol_rtol = None
limit = None
convert_dims = (0, in_ch, 0, 0)
convert_arg = torch.zeros(*convert_dims)
if "quant" in kind:
model = torch.nn.Sequential(model)
model.eval()
model.qconfig = torch.ao.quantization.get_default_qconfig(
"qnnpack"
)
model = torch.ao.quantization.prepare(model)
model(inp)
model = torch.ao.quantization.convert(model)
inp = qpt(inp, 1.0 / 16, 128)
# I've seen numerical differences between QNNPACK and NNAPI,
# but never more than 1 quantum, and never more than ~1% of
# the output in this test.
atol_rtol = (1, 0)
limit = output_size * 0.03
convert_arg = qpt(torch.zeros(*convert_dims), 1.0 / 16, 128)
if "nhwc" in kind:
inp = nhwc(inp)
convert_arg = nhwc(convert_arg)
self.check(model, inp, atol_rtol=atol_rtol, limit=limit)
self.check(
model,
inp,
convert_args=[convert_arg],
atol_rtol=atol_rtol,
limit=limit,
)
def test_conv2d_transpose(self):
torch.manual_seed(29)
in_ch, out_ch, kernel = (5, 7, (2, 2))
input_dim = (4, 5, 3, 3)
convert_dims = input_dim[:2] + (0, 0)
for kind in ["float", "float-nhwc", "quant", "quant-nhwc"]:
with self.subTest(kind):
inp = torch.randn(input_dim)
model = torch.nn.ConvTranspose2d(in_ch, out_ch, kernel)
output_size = model(inp).numel()
atol_rtol = (0.0002, 0)
limit = None
convert_arg = torch.zeros(*convert_dims)
if "quant" in kind:
model = torch.ao.nn.quantized.ConvTranspose2d(in_ch, out_ch, kernel)
model.qconfig = torch.ao.quantization.get_default_qconfig("qnnpack")
inp = qpt(inp, 1.0 / 16, 128)
# I've seen numerical differences between QNNPACK and NNAPI,
# but never more than 1 quantum, and never more than ~10% of
# the output in this test.
atol_rtol = (1, 0)
limit = output_size * 0.1
convert_arg = qpt(convert_arg, 1.0 / 16, 128)
if "nhwc" in kind:
inp = nhwc(inp)
convert_arg = nhwc(convert_arg)
self.check(model, inp, atol_rtol=atol_rtol, limit=limit)
self.check(
model,
inp,
convert_args=[convert_arg],
atol_rtol=atol_rtol,
limit=limit,
)
def test_qadd(self):
func = torch.ao.nn.quantized.QFunctional()
func.scale = 0.5
func.zero_point = 120
class AddMod(torch.nn.Module):
def forward(self, lhs, rhs):
return func.add(lhs, rhs)
class AddReluMod(torch.nn.Module):
def forward(self, lhs, rhs):
return func.add_relu(lhs, rhs)
class MulMod(torch.nn.Module):
def forward(self, lhs, rhs):
return func.mul(lhs, rhs)
for name, mod in [("add", AddMod), ("add_relu", AddReluMod), ("mul", MulMod)]:
with self.subTest(name):
self.check(
mod(),
[
qpt([1.0, 2.0], 0.25, 128),
qpt([3.0, 4.0], 0.25, 128),
],
)
self.check(
mod(),
[
qpt([[1.0, 2.0]], 0.25, 128),
qpt([[3.0, 4.0]], 0.25, 128),
],
convert_args=[
qpt([[1.0, 2.0]], 0.25, 128),
qpt(torch.zeros((1, 2)), 0.25, 128),
],
)
self.check(
mod(),
[
qpt([[1.0, 2.0]], 0.25, 128),
qpt([[3.0, 4.0]], 0.25, 128),
],
convert_args=[
qpt(torch.zeros((1, 2)), 0.25, 128),
qpt([[3.0, 4.0]], 0.25, 128),
],
)
self.check(
mod(),
[
qpt([[1.0, 2.0]], 0.25, 128),
qpt([[3.0, 4.0]], 0.25, 128),
],
convert_args=[
qpt(torch.zeros((1, 2)), 0.25, 128),
qpt(torch.zeros((1, 2)), 0.25, 128),
],
)
# NOTE: NNAPI qadd supports broadcast, but PT does not.
def test_qlinear(self):
torch.manual_seed(29)
weight = qpt(torch.randn(16, 32), 0.125, 0, torch.qint8)
bias = torch.randn(16)
mod = torch.ao.nn.quantized.Linear(32, 16)
mod.set_weight_bias(weight, bias)
inp = qpt(torch.randn(2, 32), 0.05, 130, torch.quint8)
self.check(mod, inp)
def test_seblock_mul(self):
class MulModel(torch.nn.Module):
def forward(self, lhs, rhs):
return lhs * rhs
self.check(
MulModel(),
[
nhwc(torch.randn(2, 3, 4, 4)),
torch.randn(1, 3, 1, 1),
],
)
def test_multi_output(self):
class MultiModel(torch.nn.Module):
def forward(self, lhs, rhs) -> tuple[torch.Tensor, torch.Tensor]:
the_sum = lhs + rhs
the_diff = lhs - rhs
return the_sum, the_diff
self.check(MultiModel(), [torch.tensor([1.0, 2.0]), torch.tensor([1.0, 3.0])])
if __name__ == "__main__":
run_tests()
|
TestNNAPI
|
python
|
apache__airflow
|
airflow-core/src/airflow/api_fastapi/core_api/datamodels/common.py
|
{
"start": 2983,
"end": 3537
}
|
class ____(BulkBaseAction[T]):
"""Bulk Delete entity serializer for request bodies."""
action: Literal[BulkAction.DELETE] = Field(description="The action to be performed on the entities.")
entities: list[Union[str, BulkTaskInstanceBody]] = Field(
...,
description="A list of entity id/key or entity objects to be deleted.",
)
action_on_non_existence: BulkActionNotOnExistence = BulkActionNotOnExistence.FAIL
def _action_discriminator(action: Any) -> str:
return BulkAction(action["action"]).value
|
BulkDeleteAction
|
python
|
django__django
|
django/contrib/gis/gdal/layer.py
|
{
"start": 888,
"end": 8820
}
|
class ____(GDALBase):
"""
A class that wraps an OGR Layer, needs to be instantiated from a DataSource
object.
"""
def __init__(self, layer_ptr, ds):
"""
Initialize on an OGR C pointer to the Layer and the `DataSource` object
that owns this layer. The `DataSource` object is required so that a
reference to it is kept with this Layer. This prevents garbage
collection of the `DataSource` while this Layer is still active.
"""
if not layer_ptr:
raise GDALException("Cannot create Layer, invalid pointer given")
self.ptr = layer_ptr
self._ds = ds
self._ldefn = capi.get_layer_defn(self._ptr)
# Does the Layer support random reading?
self._random_read = self.test_capability(b"RandomRead")
def __getitem__(self, index):
"Get the Feature at the specified index."
if isinstance(index, int):
# An integer index was given -- we cannot do a check based on the
# number of features because the beginning and ending feature IDs
# are not guaranteed to be 0 and len(layer)-1, respectively.
if index < 0:
raise IndexError("Negative indices are not allowed on OGR Layers.")
return self._make_feature(index)
elif isinstance(index, slice):
# A slice was given
start, stop, stride = index.indices(self.num_feat)
return [self._make_feature(fid) for fid in range(start, stop, stride)]
else:
raise TypeError(
"Integers and slices may only be used when indexing OGR Layers."
)
def __iter__(self):
"Iterate over each Feature in the Layer."
# ResetReading() must be called before iteration is to begin.
capi.reset_reading(self._ptr)
for i in range(self.num_feat):
yield Feature(capi.get_next_feature(self._ptr), self)
def __len__(self):
"The length is the number of features."
return self.num_feat
def __str__(self):
"The string name of the layer."
return self.name
def _make_feature(self, feat_id):
"""
Helper routine for __getitem__ that constructs a Feature from the given
Feature ID. If the OGR Layer does not support random-access reading,
then each feature of the layer will be incremented through until the
a Feature is found matching the given feature ID.
"""
if self._random_read:
# If the Layer supports random reading, return.
try:
return Feature(capi.get_feature(self.ptr, feat_id), self)
except GDALException:
pass
else:
# Random access isn't supported, have to increment through
# each feature until the given feature ID is encountered.
for feat in self:
if feat.fid == feat_id:
return feat
# Should have returned a Feature, raise an IndexError.
raise IndexError("Invalid feature id: %s." % feat_id)
# #### Layer properties ####
@property
def extent(self):
"Return the extent (an Envelope) of this layer."
env = OGREnvelope()
capi.get_extent(self.ptr, byref(env), 1)
return Envelope(env)
@property
def name(self):
"Return the name of this layer in the Data Source."
name = capi.get_fd_name(self._ldefn)
return force_str(name, self._ds.encoding, strings_only=True)
@property
def num_feat(self, force=1):
"Return the number of features in the Layer."
return capi.get_feature_count(self.ptr, force)
@property
def num_fields(self):
"Return the number of fields in the Layer."
return capi.get_field_count(self._ldefn)
@property
def geom_type(self):
"Return the geometry type (OGRGeomType) of the Layer."
return OGRGeomType(capi.get_fd_geom_type(self._ldefn))
@property
def srs(self):
"Return the Spatial Reference used in this Layer."
try:
ptr = capi.get_layer_srs(self.ptr)
return SpatialReference(srs_api.clone_srs(ptr))
except SRSException:
return None
@property
def fields(self):
"""
Return a list of string names corresponding to each of the Fields
available in this Layer.
"""
return [
force_str(
capi.get_field_name(capi.get_field_defn(self._ldefn, i)),
self._ds.encoding,
strings_only=True,
)
for i in range(self.num_fields)
]
@property
def field_types(self):
"""
Return a list of the types of fields in this Layer. For example,
return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that
has an integer, a floating-point, and string fields.
"""
return [
OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))]
for i in range(self.num_fields)
]
@property
def field_widths(self):
"Return a list of the maximum field widths for the features."
return [
capi.get_field_width(capi.get_field_defn(self._ldefn, i))
for i in range(self.num_fields)
]
@property
def field_precisions(self):
"Return the field precisions for the features."
return [
capi.get_field_precision(capi.get_field_defn(self._ldefn, i))
for i in range(self.num_fields)
]
def _get_spatial_filter(self):
try:
return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))
except GDALException:
return None
def _set_spatial_filter(self, filter):
if isinstance(filter, OGRGeometry):
capi.set_spatial_filter(self.ptr, filter.ptr)
elif isinstance(filter, (tuple, list)):
if not len(filter) == 4:
raise ValueError("Spatial filter list/tuple must have 4 elements.")
# Map c_double onto params -- if a bad type is passed in it
# will be caught here.
xmin, ymin, xmax, ymax = map(c_double, filter)
capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax)
elif filter is None:
capi.set_spatial_filter(self.ptr, None)
else:
raise TypeError(
"Spatial filter must be either an OGRGeometry instance, a 4-tuple, or "
"None."
)
spatial_filter = property(_get_spatial_filter, _set_spatial_filter)
# #### Layer Methods ####
def get_fields(self, field_name):
"""
Return a list containing the given field name for every Feature
in the Layer.
"""
if field_name not in self.fields:
raise GDALException("invalid field name: %s" % field_name)
return [feat.get(field_name) for feat in self]
def get_geoms(self, geos=False):
"""
Return a list containing the OGRGeometry for every Feature in
the Layer.
"""
if geos:
from django.contrib.gis.geos import GEOSGeometry
return [GEOSGeometry(feat.geom.wkb) for feat in self]
else:
return [feat.geom for feat in self]
def test_capability(self, capability):
"""
Return a bool indicating whether the this Layer supports the given
capability (a string). Valid capability strings include:
'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',
'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',
'DeleteFeature', and 'FastSetNextByIndex'.
"""
return bool(capi.test_capability(self.ptr, force_bytes(capability)))
|
Layer
|
python
|
eriklindernoren__ML-From-Scratch
|
mlfromscratch/deep_learning/layers.py
|
{
"start": 14614,
"end": 16351
}
|
class ____(Layer):
"""A parent class of MaxPooling2D and AveragePooling2D
"""
def __init__(self, pool_shape=(2, 2), stride=1, padding=0):
self.pool_shape = pool_shape
self.stride = stride
self.padding = padding
self.trainable = True
def forward_pass(self, X, training=True):
self.layer_input = X
batch_size, channels, height, width = X.shape
_, out_height, out_width = self.output_shape()
X = X.reshape(batch_size*channels, 1, height, width)
X_col = image_to_column(X, self.pool_shape, self.stride, self.padding)
# MaxPool or AveragePool specific method
output = self._pool_forward(X_col)
output = output.reshape(out_height, out_width, batch_size, channels)
output = output.transpose(2, 3, 0, 1)
return output
def backward_pass(self, accum_grad):
batch_size, _, _, _ = accum_grad.shape
channels, height, width = self.input_shape
accum_grad = accum_grad.transpose(2, 3, 0, 1).ravel()
# MaxPool or AveragePool specific method
accum_grad_col = self._pool_backward(accum_grad)
accum_grad = column_to_image(accum_grad_col, (batch_size * channels, 1, height, width), self.pool_shape, self.stride, 0)
accum_grad = accum_grad.reshape((batch_size,) + self.input_shape)
return accum_grad
def output_shape(self):
channels, height, width = self.input_shape
out_height = (height - self.pool_shape[0]) / self.stride + 1
out_width = (width - self.pool_shape[1]) / self.stride + 1
assert out_height % 1 == 0
assert out_width % 1 == 0
return channels, int(out_height), int(out_width)
|
PoolingLayer
|
python
|
jmcnamara__XlsxWriter
|
xlsxwriter/test/comparison/test_escapes06.py
|
{
"start": 315,
"end": 967
}
|
class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("escapes06.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file a num format that require XML escaping."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
num_format = workbook.add_format({"num_format": '[Red]0.0%\\ "a"'})
worksheet.set_column("A:A", 14)
worksheet.write("A1", 123, num_format)
workbook.close()
self.assertExcelEqual()
|
TestCompareXLSXFiles
|
python
|
sqlalchemy__sqlalchemy
|
lib/sqlalchemy/testing/pickleable.py
|
{
"start": 648,
"end": 732
}
|
class ____(ComparableEntity):
pass
# TODO: these are kind of arbitrary....
|
Address
|
python
|
ethereum__web3.py
|
web3/utils/caching.py
|
{
"start": 230,
"end": 2540
}
|
class ____:
def __init__(self, size: int = 100):
self._size = size
self._data: OrderedDict[str, Any] = OrderedDict()
def __contains__(self, key: str) -> bool:
return key in self._data
def __len__(self) -> int:
return len(self._data)
def cache(self, key: str, value: Any) -> tuple[Any, dict[str, Any]]:
evicted_items = {}
# If the key is already in the OrderedDict just update it
# and don't evict any values. Ideally, we could still check to see
# if there are too many items in the OrderedDict but that may rearrange
# the order it should be unlikely that the size could grow over the limit
if key not in self._data:
while len(self._data) >= self._size:
k, v = self._data.popitem(last=False)
evicted_items[k] = v
self._data[key] = value
# Return the cached value along with the evicted items at the same time. No
# need to reach back into the cache to grab the value.
return value, evicted_items or None
def get_cache_entry(self, key: str) -> Any | None:
return self._data[key] if key in self._data else None
def clear(self) -> None:
self._data.clear()
def items(self) -> list[tuple[str, Any]]:
return list(self._data.items())
def pop(self, key: str) -> Any | None:
if key not in self._data:
return None
return self._data.pop(key)
def popitem(self, last: bool = True) -> tuple[str, Any]:
return self._data.popitem(last=last)
def is_full(self) -> bool:
return len(self._data) >= self._size
# -- async utility methods -- #
async def async_await_and_popitem(
self, last: bool = True, timeout: float = 10.0
) -> tuple[str, Any]:
start = time.time()
end_time = start + timeout
while True:
await asyncio.sleep(0)
try:
return self.popitem(last=last)
except KeyError:
now = time.time()
if now >= end_time:
raise asyncio.TimeoutError(
"Timeout waiting for item to be available"
)
await asyncio.sleep(min(0.1, end_time - now))
|
SimpleCache
|
python
|
ipython__ipython
|
tests/test_magic.py
|
{
"start": 53631,
"end": 55731
}
|
class ____(Magics):
@line_magic
def lazy_line(self, line):
print("Lazy Line")
@cell_magic
def lazy_cell(self, line, cell):
print("Lazy Cell")
def load_ipython_extension(ipython):
ipython.register_magics(LazyMagics)
"""
def test_lazy_magics():
with pytest.raises(UsageError):
ip.run_line_magic("lazy_line", "")
startdir = os.getcwd()
with TemporaryDirectory() as tmpdir:
with prepended_to_syspath(tmpdir):
ptempdir = Path(tmpdir)
tf = ptempdir / "lazy_magic_module.py"
tf.write_text(MINIMAL_LAZY_MAGIC)
ip.magics_manager.register_lazy("lazy_line", Path(tf.name).name[:-3])
with tt.AssertPrints("Lazy Line"):
ip.run_line_magic("lazy_line", "")
TEST_MODULE = """
print('Loaded my_tmp')
if __name__ == "__main__":
print('I just ran a script')
"""
def test_run_module_from_import_hook():
"Test that a module can be loaded via an import hook"
with TemporaryDirectory() as tmpdir:
fullpath = os.path.join(tmpdir, "my_tmp.py")
Path(fullpath).write_text(TEST_MODULE, encoding="utf-8")
import importlib.abc
import importlib.util
class MyTempImporter(importlib.abc.MetaPathFinder, importlib.abc.SourceLoader):
def find_spec(self, fullname, path, target=None):
if fullname == "my_tmp":
return importlib.util.spec_from_loader(fullname, self)
def get_filename(self, fullname):
assert fullname == "my_tmp"
return fullpath
def get_data(self, path):
assert Path(path).samefile(fullpath)
return Path(fullpath).read_text(encoding="utf-8")
sys.meta_path.insert(0, MyTempImporter())
with capture_output() as captured:
_ip.run_line_magic("run", "-m my_tmp")
_ip.run_cell("import my_tmp")
output = "Loaded my_tmp\nI just ran a script\nLoaded my_tmp\n"
assert output == captured.stdout
sys.meta_path.pop(0)
|
LazyMagics
|
python
|
google__pytype
|
pytype/typegraph/cfg_utils_test.py
|
{
"start": 7954,
"end": 13026
}
|
class ____(unittest.TestCase):
"""Test abstract graph utilities."""
def setUp(self):
super().setUp()
self.prog = cfg.Program()
def test_compute_predecessors(self):
# n7 n6
# ^ ^
# | |
# | |
# n1 ---> n20 --> n3 --> n5 -+
# | ^ ^ |
# | | | |
# | +------------|---+
# v |
# n4 ------------+
n1 = self.prog.NewCFGNode("n1")
n20 = n1.ConnectNew("n20")
n3 = n20.ConnectNew("n3")
n4 = n20.ConnectNew("n4")
n5 = n3.ConnectNew("n5")
n6 = n20.ConnectNew("n6")
n7 = n1.ConnectNew("n7")
n3.ConnectTo(n5)
n4.ConnectTo(n5)
n5.ConnectTo(n20)
# Intentionally pick a non-root as nodes[0] to verify that the graph
# will still be fully explored.
nodes = [n7, n1, n20, n3, n4, n5, n6]
r = cfg_utils.compute_predecessors(nodes)
self.assertCountEqual(r[n1], {n1})
self.assertCountEqual(r[n20], {n1, n20, n3, n4, n5})
self.assertCountEqual(r[n3], {n1, n20, n3, n4, n5})
self.assertCountEqual(r[n4], {n1, n20, n3, n4, n5})
self.assertCountEqual(r[n5], {n1, n20, n3, n4, n5})
self.assertCountEqual(r[n6], {n1, n20, n3, n4, n5, n6})
self.assertCountEqual(r[n7], {n1, n7})
def test_order_nodes0(self):
order = cfg_utils.order_nodes([])
self.assertCountEqual(order, [])
def test_order_nodes1(self):
# n1 --> n2
n1 = self.prog.NewCFGNode("n1")
n2 = n1.ConnectNew("n2")
order = cfg_utils.order_nodes([n1, n2])
self.assertCountEqual([n1, n2], order)
def test_order_nodes2(self):
# n1 n2(dead)
n1 = self.prog.NewCFGNode("n1")
n2 = self.prog.NewCFGNode("n2")
order = cfg_utils.order_nodes([n1, n2])
self.assertCountEqual([n1], order)
def test_order_nodes3(self):
# n1 --> n2 --> n3
# ^ |
# +-------------+
n1 = self.prog.NewCFGNode("n1")
n2 = n1.ConnectNew("n2")
n3 = n2.ConnectNew("n3")
n3.ConnectTo(n1)
order = cfg_utils.order_nodes([n1, n2, n3])
self.assertCountEqual([n1, n2, n3], order)
def test_order_nodes4(self):
# n1 --> n3 --> n2
# ^ |
# +------+
n1 = self.prog.NewCFGNode("n1")
n3 = n1.ConnectNew("n3")
n2 = n3.ConnectNew("n2")
n3.ConnectTo(n1)
order = cfg_utils.order_nodes([n1, n2, n3])
self.assertCountEqual([n1, n3, n2], order)
def test_order_nodes5(self):
# n1 --> n3 --> n2
# ^ |
# +------+ n4(dead)
n1 = self.prog.NewCFGNode("n1")
n3 = n1.ConnectNew("n3")
n2 = n3.ConnectNew("n2")
n3.ConnectTo(n1)
n4 = self.prog.NewCFGNode("n4")
order = cfg_utils.order_nodes([n1, n2, n3, n4])
self.assertCountEqual([n1, n3, n2], order)
def test_order_nodes6(self):
# +-------------------+
# | v
# n1 --> n2 --> n3 --> n5
# ^ |
# +------n4
n1 = self.prog.NewCFGNode("n1")
n2 = n1.ConnectNew("n2")
n3 = n2.ConnectNew("n3")
n4 = n3.ConnectNew("n4")
n4.ConnectTo(n2)
n5 = n3.ConnectNew("n5")
n1.ConnectTo(n5)
order = cfg_utils.order_nodes([n1, n5, n4, n3, n2])
self.assertCountEqual([n1, n2, n3, n4, n5], order)
def test_order_nodes7(self):
# +---------------------------------+
# | v
# n1 --> n2 --> n3 --> n4 --> n5 --> n6
# ^ | ^ |
# | v | v
# +------n7 +------n8
n1 = self.prog.NewCFGNode("n1")
n2 = n1.ConnectNew("n2")
n3 = n2.ConnectNew("n3")
n4 = n3.ConnectNew("n4")
n5 = n4.ConnectNew("n5")
n6 = n5.ConnectNew("n6")
n7 = n3.ConnectNew("n7")
n7.ConnectTo(n2)
n8 = n5.ConnectNew("n8")
n8.ConnectTo(n4)
n1.ConnectTo(n6)
order = cfg_utils.order_nodes([n1, n2, n3, n4, n5, n6, n7, n8])
self.assertCountEqual([n1, n2, n3, n7, n4, n5, n8, n6], order)
def test_topological_sort(self):
n1 = Node("1")
n2 = Node("2", n1)
n3 = Node("3", n2)
n4 = Node("4", n2, n3)
for permutation in itertools.permutations([n1, n2, n3, n4]):
self.assertEqual(
list(cfg_utils.topological_sort(permutation)), [n1, n2, n3, n4]
)
def test_topological_sort2(self):
n1 = Node("1")
n2 = Node("2", n1)
self.assertEqual(list(cfg_utils.topological_sort([n1, n2, 3, 4]))[-1], n2)
def test_topological_sort_cycle(self):
n1 = Node("1")
n2 = Node("2")
n1.incoming = [n2]
n2.incoming = [n1]
generator = cfg_utils.topological_sort([n1, n2])
self.assertRaises(ValueError, list, generator)
def test_topological_sort_sub_cycle(self):
n1 = Node("1")
n2 = Node("2")
n3 = Node("3")
n1.incoming = [n2]
n2.incoming = [n1]
n3.incoming = [n1, n2]
generator = cfg_utils.topological_sort([n1, n2, n3])
self.assertRaises(ValueError, list, generator)
def test_topological_sort_getattr(self):
self.assertEqual(list(cfg_utils.topological_sort([1])), [1])
if __name__ == "__main__":
unittest.main()
|
GraphUtilTest
|
python
|
pytorch__pytorch
|
torch/_inductor/pattern_matcher.py
|
{
"start": 3664,
"end": 3912
}
|
class ____(Protocol):
def __call__(
self, fn: Union[SearchFn, ReplaceFn], *args: Any, **kwargs: Any
) -> torch.fx.GraphModule: ...
T = TypeVar("T")
# What's a better name for this?
FnsType = Union[torch.fx.node.Target, str]
|
TraceFn
|
python
|
django__django
|
tests/generic_relations_regress/models.py
|
{
"start": 2135,
"end": 2346
}
|
class ____(models.Model):
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
note = models.TextField()
|
Note
|
python
|
protocolbuffers__protobuf
|
python/google/protobuf/internal/text_format_test.py
|
{
"start": 1436,
"end": 1904
}
|
class ____(unittest.TestCase):
# The members of _QUOTES are formatted into a regexp template that
# expects single characters. Therefore it's an error (in addition to being
# non-sensical in the first place) to try to specify a "quote mark" that is
# more than one character.
def testQuoteMarksAreSingleChars(self):
for quote in text_format._QUOTES:
self.assertEqual(1, len(quote))
# Base class with some common functionality.
|
SimpleTextFormatTests
|
python
|
tensorflow__tensorflow
|
tensorflow/python/ops/image_ops_test.py
|
{
"start": 208413,
"end": 216995
}
|
class ____(test_util.TensorFlowTestCase):
def testNonMaxSuppression(self):
boxes_np = [[0, 0, 1, 1], [0, 0.1, 1, 1.1], [0, -0.1, 1, 0.9],
[0, 10, 1, 11], [0, 10.1, 1, 11.1], [0, 100, 1, 101]]
scores_np = [0.9, 0.75, 0.6, 0.95, 0.5, 0.3]
max_output_size_np = 3
iou_threshold_np = 0.5
with self.cached_session():
boxes = constant_op.constant(boxes_np)
scores = constant_op.constant(scores_np)
max_output_size = constant_op.constant(max_output_size_np)
iou_threshold = constant_op.constant(iou_threshold_np)
selected_indices = image_ops.non_max_suppression(
boxes, scores, max_output_size, iou_threshold)
self.assertAllClose(selected_indices, [3, 0, 5])
def testInvalidShape(self):
def nms_func(box, score, max_output_size, iou_thres):
return image_ops.non_max_suppression(box, score, max_output_size,
iou_thres)
max_output_size = 3
iou_thres = 0.5
# The boxes should be 2D of shape [num_boxes, 4].
with self.assertRaises((ValueError, errors_impl.InvalidArgumentError)):
boxes = constant_op.constant([0.0, 0.0, 1.0, 1.0])
scores = constant_op.constant([0.9])
nms_func(boxes, scores, max_output_size, iou_thres)
# Dimensions must be 4 (but is 3)
with self.assertRaises((ValueError, errors_impl.InvalidArgumentError)):
boxes = constant_op.constant([[0.0, 0, 1.0]])
scores = constant_op.constant([0.9])
nms_func(boxes, scores, max_output_size, iou_thres)
# The boxes is of shape [num_boxes, 4], and the scores is
# of shape [num_boxes]. So an error will be thrown bc 1 != 2.
with self.assertRaises((ValueError, errors_impl.InvalidArgumentError)):
boxes = constant_op.constant([[0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0]])
scores = constant_op.constant([0.9])
nms_func(boxes, scores, max_output_size, iou_thres)
# The scores should be 1D of shape [num_boxes].
with self.assertRaises((ValueError, errors_impl.InvalidArgumentError)):
boxes = constant_op.constant([[0.0, 0.0, 1.0, 1.0]])
scores = constant_op.constant([[0.9]])
nms_func(boxes, scores, max_output_size, iou_thres)
# The max output size should be a scalar (0-D).
with self.assertRaises((ValueError, errors_impl.InvalidArgumentError)):
boxes = constant_op.constant([[0.0, 0.0, 1.0, 1.0]])
scores = constant_op.constant([0.9])
nms_func(boxes, scores, [[max_output_size]], iou_thres)
# The iou_threshold should be a scalar (0-D).
with self.assertRaises((ValueError, errors_impl.InvalidArgumentError)):
boxes = constant_op.constant([[0.0, 0.0, 1.0, 1.0]])
scores = constant_op.constant([0.9])
nms_func(boxes, scores, max_output_size, [[iou_thres]])
@test_util.xla_allow_fallback(
"non_max_suppression with dynamic output shape unsupported.")
def testTensors(self):
with context.eager_mode():
boxes_tensor = constant_op.constant([[6.625, 6.688, 272., 158.5],
[6.625, 6.75, 270.5, 158.4],
[5.375, 5., 272., 157.5]])
scores_tensor = constant_op.constant([0.84, 0.7944, 0.7715])
max_output_size = 100
iou_threshold = 0.5
score_threshold = 0.3
soft_nms_sigma = 0.25
pad_to_max_output_size = False
# gen_image_ops.non_max_suppression_v5.
for dtype in [np.float16, np.float32]:
boxes = math_ops.cast(boxes_tensor, dtype=dtype)
scores = math_ops.cast(scores_tensor, dtype=dtype)
_, _, num_selected = gen_image_ops.non_max_suppression_v5(
boxes, scores, max_output_size, iou_threshold, score_threshold,
soft_nms_sigma, pad_to_max_output_size)
self.assertEqual(num_selected.numpy(), 1)
@test_util.xla_allow_fallback(
"non_max_suppression with dynamic output shape unsupported.")
def testDataTypes(self):
# Test case for GitHub issue 20199.
boxes_np = [[0, 0, 1, 1], [0, 0.1, 1, 1.1], [0, -0.1, 1, 0.9],
[0, 10, 1, 11], [0, 10.1, 1, 11.1], [0, 100, 1, 101]]
scores_np = [0.9, 0.75, 0.6, 0.95, 0.5, 0.3]
max_output_size_np = 3
iou_threshold_np = 0.5
score_threshold_np = float("-inf")
# Note: There are multiple versions of non_max_suppression v2, v3, v4.
# gen_image_ops.non_max_suppression_v2:
for input_dtype in [np.float16, np.float32]:
for threshold_dtype in [np.float16, np.float32]:
with self.cached_session():
boxes = constant_op.constant(boxes_np, dtype=input_dtype)
scores = constant_op.constant(scores_np, dtype=input_dtype)
max_output_size = constant_op.constant(max_output_size_np)
iou_threshold = constant_op.constant(
iou_threshold_np, dtype=threshold_dtype)
selected_indices = gen_image_ops.non_max_suppression_v2(
boxes, scores, max_output_size, iou_threshold)
selected_indices = self.evaluate(selected_indices)
self.assertAllClose(selected_indices, [3, 0, 5])
# gen_image_ops.non_max_suppression_v3
for input_dtype in [np.float16, np.float32]:
for threshold_dtype in [np.float16, np.float32]:
# XLA currently requires dtypes to be equal.
if input_dtype == threshold_dtype or not test_util.is_xla_enabled():
with self.cached_session():
boxes = constant_op.constant(boxes_np, dtype=input_dtype)
scores = constant_op.constant(scores_np, dtype=input_dtype)
max_output_size = constant_op.constant(max_output_size_np)
iou_threshold = constant_op.constant(
iou_threshold_np, dtype=threshold_dtype)
score_threshold = constant_op.constant(
score_threshold_np, dtype=threshold_dtype)
selected_indices = gen_image_ops.non_max_suppression_v3(
boxes, scores, max_output_size, iou_threshold, score_threshold)
selected_indices = self.evaluate(selected_indices)
self.assertAllClose(selected_indices, [3, 0, 5])
# gen_image_ops.non_max_suppression_v4.
for input_dtype in [np.float16, np.float32]:
for threshold_dtype in [np.float16, np.float32]:
with self.cached_session():
boxes = constant_op.constant(boxes_np, dtype=input_dtype)
scores = constant_op.constant(scores_np, dtype=input_dtype)
max_output_size = constant_op.constant(max_output_size_np)
iou_threshold = constant_op.constant(
iou_threshold_np, dtype=threshold_dtype)
score_threshold = constant_op.constant(
score_threshold_np, dtype=threshold_dtype)
selected_indices, _ = gen_image_ops.non_max_suppression_v4(
boxes, scores, max_output_size, iou_threshold, score_threshold)
selected_indices = self.evaluate(selected_indices)
self.assertAllClose(selected_indices, [3, 0, 5])
# gen_image_ops.non_max_suppression_v5.
soft_nms_sigma_np = float(0.0)
for dtype in [np.float16, np.float32]:
with self.cached_session():
boxes = constant_op.constant(boxes_np, dtype=dtype)
scores = constant_op.constant(scores_np, dtype=dtype)
max_output_size = constant_op.constant(max_output_size_np)
iou_threshold = constant_op.constant(iou_threshold_np, dtype=dtype)
score_threshold = constant_op.constant(score_threshold_np, dtype=dtype)
soft_nms_sigma = constant_op.constant(soft_nms_sigma_np, dtype=dtype)
selected_indices, _, _ = gen_image_ops.non_max_suppression_v5(
boxes, scores, max_output_size, iou_threshold, score_threshold,
soft_nms_sigma)
selected_indices = self.evaluate(selected_indices)
self.assertAllClose(selected_indices, [3, 0, 5])
def testZeroIOUThreshold(self):
boxes_np = [[0, 0, 1, 1], [0, 0.1, 1, 1.1], [0, -0.1, 1, 0.9],
[0, 10, 1, 11], [0, 10.1, 1, 11.1], [0, 100, 1, 101]]
scores_np = [1., 1., 1., 1., 1., 1.]
max_output_size_np = 3
iou_threshold_np = 0.0
with self.cached_session():
boxes = constant_op.constant(boxes_np)
scores = constant_op.constant(scores_np)
max_output_size = constant_op.constant(max_output_size_np)
iou_threshold = constant_op.constant(iou_threshold_np)
selected_indices = image_ops.non_max_suppression(
boxes, scores, max_output_size, iou_threshold)
self.assertAllClose(selected_indices, [0, 3, 5])
|
NonMaxSuppressionTest
|
python
|
dagster-io__dagster
|
python_modules/libraries/dagster-sling/dagster_sling/components/sling_replication_collection/component.py
|
{
"start": 1820,
"end": 2558
}
|
class ____(Resolvable):
path: str
op: Optional[OpSpec] = None
translation: Optional[
Annotated[
TranslationFn[Mapping[str, Any]],
TranslationFnResolver(
template_vars_for_translation_fn=lambda data: {"stream_definition": data}
),
]
] = None
include_metadata: Annotated[
list[SlingMetadataAddons],
Resolver.default(
description="Optionally include additional metadata in materializations generated while executing your Sling models",
examples=[
["row_count"],
["row_count", "column_metadata"],
],
),
] = field(default_factory=list)
|
SlingReplicationSpecModel
|
python
|
django__django
|
django/core/serializers/base.py
|
{
"start": 6504,
"end": 7162
}
|
class ____:
"""
Abstract base deserializer class.
"""
def __init__(self, stream_or_string, **options):
"""
Init this serializer given a stream or a string
"""
self.options = options
if isinstance(stream_or_string, str):
self.stream = StringIO(stream_or_string)
else:
self.stream = stream_or_string
def __iter__(self):
return self
def __next__(self):
"""Iteration interface -- return the next item in the stream"""
raise NotImplementedError(
"subclasses of Deserializer must provide a __next__() method"
)
|
Deserializer
|
python
|
run-llama__llama_index
|
llama-index-integrations/llms/llama-index-llms-vllm/tests/test_integration.py
|
{
"start": 584,
"end": 4499
}
|
class ____(VCRTestCase):
# replace to local_vllm(), it requires vllm installed and fail ..stream.. tests due to Not Implemented
vllm = remote_vllm()
# drop it to record new cassete files
def _get_vcr_kwargs(self, **kwargs):
return {"record_mode": RecordMode.NONE}
def test_completion(self):
completion = self.vllm.complete(prompt)
assert isinstance(completion, CompletionResponse)
assert isinstance(completion.text, str)
assert len(completion.text) > 0
assert prompt in completion.text
def test_acompletion(self):
completion = asyncio.run(self.vllm.acomplete(prompt))
assert isinstance(completion, CompletionResponse)
assert isinstance(completion.text, str)
assert len(completion.text) > 0
assert prompt in completion.text
def test_chat(self):
chat = self.vllm.chat([ChatMessage(content=prompt, role=MessageRole.USER)])
assert isinstance(chat.message, ChatMessage)
assert chat.message.role == MessageRole.ASSISTANT
assert isinstance(chat.message.content, str)
assert len(chat.message.content) > 0
assert prompt in chat.message.content
def test_achat(self):
chat = asyncio.run(
self.vllm.achat([ChatMessage(content=prompt, role=MessageRole.USER)])
)
assert isinstance(chat.message, ChatMessage)
assert chat.message.role == MessageRole.ASSISTANT
assert isinstance(chat.message.content, str)
assert len(chat.message.content) > 0
assert prompt in chat.message.content
def test_stream_completion(self):
stream = list(self.vllm.stream_complete(prompt))
first = stream[0]
completion = stream[-1]
for i in first, completion:
assert isinstance(i, CompletionResponse)
assert i.text.count(prompt) == 1
assert completion.text.count(first.text) == 1
assert first.text.count(completion.text) == 0
def test_astream_completion(self):
async def concat():
return [c async for c in await self.vllm.astream_complete(prompt)]
stream = asyncio.run(concat())
first = stream[0]
assert isinstance(first, CompletionResponse)
assert first.text.count(prompt) == 1, "no repeats please"
completion = stream[-1]
assert isinstance(completion, CompletionResponse)
assert completion.text.count(first.text) == 1, "no repeats please"
assert completion.text not in first.text
def test_stream_chat(self):
stream = list(
self.vllm.stream_chat([ChatMessage(content=prompt, role=MessageRole.USER)])
)
first = stream[0]
chat = stream[-1]
for i in first, chat:
assert isinstance(i, ChatResponse)
assert isinstance(i.message, ChatMessage)
assert i.message.role == MessageRole.ASSISTANT
assert i.message.content.count(prompt) == 1
assert chat.message.content.count(first.message.content) == 1
assert chat.message.content not in first.message.content, "not equal"
def test_astream_chat(self):
async def concat():
return [
c
async for c in await self.vllm.astream_chat(
[ChatMessage(content=prompt, role=MessageRole.USER)]
)
]
stream = asyncio.run(concat())
first = stream[0]
chat = stream[-1]
for i in first, chat:
assert isinstance(i, ChatResponse)
assert isinstance(i.message, ChatMessage)
assert i.message.role == MessageRole.ASSISTANT
assert i.message.content.count(prompt) == 1
assert chat.message.content.count(first.message.content) == 1
assert chat.message.content not in first.message.content, "not equal"
|
TestVllmIntegration
|
python
|
pytorch__pytorch
|
test/fx/quantization.py
|
{
"start": 2193,
"end": 2626
}
|
class ____(NoObserver):
def quantize(self, quantizer, node, load_arg):
return torch.relu(
load_arg(node.args[0])
) # torch.relu works directly on quantized tensors?
# these ops have quantized equivalents that do not need any extra information
@register_pattern(torch.nn.ReLU)
@register_pattern(torch.nn.AvgPool2d)
@register_pattern(torch.nn.MaxPool2d)
@register_pattern(torch.nn.AdaptiveAvgPool2d)
|
Relu
|
python
|
xlwings__xlwings
|
xlwings/_xlwindows.py
|
{
"start": 52626,
"end": 53983
}
|
class ____(base_classes.Characters):
def __init__(self, parent, xl, start=None, length=None):
self.parent = parent
self.xl = xl
self.start = start if start else 1
self.length = length if length else xl().Count
@property
def api(self):
return self.xl(self.start, self.length)
@property
def text(self):
return self.xl(self.start, self.length).Text
@property
def font(self):
return Font(self, self.xl(self.start, self.length).Font)
def __getitem__(self, item):
if isinstance(item, slice):
if (item.start and item.start < 0) or (item.stop and item.stop < 0):
raise ValueError(
self.__class__.__name__
+ " object does not support slicing with negative indexes"
)
start = item.start + 1 if item.start else 1
length = item.stop + 1 - start if item.stop else self.length + 1 - start
return Characters(parent=self, xl=self.xl, start=start, length=length)
else:
if item >= 0:
return Characters(parent=self, xl=self.xl, start=item + 1, length=1)
else:
return Characters(
parent=self, xl=self.xl, start=len(self.text) + 1 + item, length=1
)
|
Characters
|
python
|
airbytehq__airbyte
|
airbyte-ci/connectors/pipelines/tests/test_helpers/test_execution/test_run_steps.py
|
{
"start": 603,
"end": 14807
}
|
class ____(Step):
title = "Test Step"
async def _run(self, result_status=StepStatus.SUCCESS) -> StepResult:
return StepResult(step=self, status=result_status)
@pytest.mark.anyio
@pytest.mark.parametrize(
"desc, steps, expected_results, options",
[
(
"All consecutive steps succeed",
[
[StepToRun(id="step1", step=TestStep(test_context))],
[StepToRun(id="step2", step=TestStep(test_context))],
[StepToRun(id="step3", step=TestStep(test_context))],
[StepToRun(id="step4", step=TestStep(test_context))],
],
{"step1": StepStatus.SUCCESS, "step2": StepStatus.SUCCESS, "step3": StepStatus.SUCCESS, "step4": StepStatus.SUCCESS},
RunStepOptions(fail_fast=True),
),
(
"Steps all succeed with parallel steps",
[
[StepToRun(id="step1", step=TestStep(test_context))],
[
StepToRun(id="step2", step=TestStep(test_context)),
StepToRun(id="step3", step=TestStep(test_context)),
],
[StepToRun(id="step4", step=TestStep(test_context))],
],
{"step1": StepStatus.SUCCESS, "step2": StepStatus.SUCCESS, "step3": StepStatus.SUCCESS, "step4": StepStatus.SUCCESS},
RunStepOptions(fail_fast=True),
),
(
"Steps after a failed step are skipped, when fail_fast is True",
[
[StepToRun(id="step1", step=TestStep(test_context))],
[StepToRun(id="step2", step=TestStep(test_context), args={"result_status": StepStatus.FAILURE})],
[StepToRun(id="step3", step=TestStep(test_context))],
[StepToRun(id="step4", step=TestStep(test_context))],
],
{"step1": StepStatus.SUCCESS, "step2": StepStatus.FAILURE, "step3": StepStatus.SKIPPED, "step4": StepStatus.SKIPPED},
RunStepOptions(fail_fast=True),
),
(
"Steps after a failed step are not skipped, when fail_fast is False",
[
[StepToRun(id="step1", step=TestStep(test_context))],
[StepToRun(id="step2", step=TestStep(test_context), args={"result_status": StepStatus.FAILURE})],
[StepToRun(id="step3", step=TestStep(test_context))],
[StepToRun(id="step4", step=TestStep(test_context))],
],
{"step1": StepStatus.SUCCESS, "step2": StepStatus.FAILURE, "step3": StepStatus.SUCCESS, "step4": StepStatus.SUCCESS},
RunStepOptions(fail_fast=False),
),
(
"fail fast has no effect on parallel steps",
[
[StepToRun(id="step1", step=TestStep(test_context))],
[
StepToRun(id="step2", step=TestStep(test_context)),
StepToRun(id="step3", step=TestStep(test_context)),
],
[StepToRun(id="step4", step=TestStep(test_context))],
],
{"step1": StepStatus.SUCCESS, "step2": StepStatus.SUCCESS, "step3": StepStatus.SUCCESS, "step4": StepStatus.SUCCESS},
RunStepOptions(fail_fast=False),
),
(
"Nested parallel steps execute properly",
[
[StepToRun(id="step1", step=TestStep(test_context))],
[
[StepToRun(id="step2", step=TestStep(test_context))],
[StepToRun(id="step3", step=TestStep(test_context))],
[
StepToRun(id="step4", step=TestStep(test_context)),
StepToRun(id="step5", step=TestStep(test_context)),
],
],
[StepToRun(id="step6", step=TestStep(test_context))],
],
{
"step1": StepStatus.SUCCESS,
"step2": StepStatus.SUCCESS,
"step3": StepStatus.SUCCESS,
"step4": StepStatus.SUCCESS,
"step5": StepStatus.SUCCESS,
"step6": StepStatus.SUCCESS,
},
RunStepOptions(fail_fast=True),
),
(
"When fail_fast is True, nested parallel steps skip at the first failure",
[
[StepToRun(id="step1", step=TestStep(test_context))],
[
[StepToRun(id="step2", step=TestStep(test_context))],
[StepToRun(id="step3", step=TestStep(test_context))],
[
StepToRun(id="step4", step=TestStep(test_context)),
StepToRun(id="step5", step=TestStep(test_context), args={"result_status": StepStatus.FAILURE}),
],
],
[StepToRun(id="step6", step=TestStep(test_context))],
],
{
"step1": StepStatus.SUCCESS,
"step2": StepStatus.SUCCESS,
"step3": StepStatus.SUCCESS,
"step4": StepStatus.SUCCESS,
"step5": StepStatus.FAILURE,
"step6": StepStatus.SKIPPED,
},
RunStepOptions(fail_fast=True),
),
(
"When fail_fast is False, nested parallel steps do not skip at the first failure",
[
[StepToRun(id="step1", step=TestStep(test_context))],
[
[StepToRun(id="step2", step=TestStep(test_context))],
[StepToRun(id="step3", step=TestStep(test_context))],
[
StepToRun(id="step4", step=TestStep(test_context)),
StepToRun(id="step5", step=TestStep(test_context), args={"result_status": StepStatus.FAILURE}),
],
],
[StepToRun(id="step6", step=TestStep(test_context))],
],
{
"step1": StepStatus.SUCCESS,
"step2": StepStatus.SUCCESS,
"step3": StepStatus.SUCCESS,
"step4": StepStatus.SUCCESS,
"step5": StepStatus.FAILURE,
"step6": StepStatus.SUCCESS,
},
RunStepOptions(fail_fast=False),
),
(
"When fail_fast is False, consecutive steps still operate as expected",
[
StepToRun(id="step1", step=TestStep(test_context)),
StepToRun(id="step2", step=TestStep(test_context)),
StepToRun(id="step3", step=TestStep(test_context)),
StepToRun(id="step4", step=TestStep(test_context)),
],
{"step1": StepStatus.SUCCESS, "step2": StepStatus.SUCCESS, "step3": StepStatus.SUCCESS, "step4": StepStatus.SUCCESS},
RunStepOptions(fail_fast=False),
),
(
"skip_steps skips the specified steps",
[
StepToRun(id="step1", step=TestStep(test_context)),
StepToRun(id="step2", step=TestStep(test_context)),
StepToRun(id="step3", step=TestStep(test_context)),
StepToRun(id="step4", step=TestStep(test_context)),
],
{"step1": StepStatus.SUCCESS, "step2": StepStatus.SKIPPED, "step3": StepStatus.SUCCESS, "step4": StepStatus.SUCCESS},
RunStepOptions(fail_fast=False, skip_steps=["step2"]),
),
(
"step is skipped if the dependency fails",
[
[StepToRun(id="step1", step=TestStep(test_context))],
[StepToRun(id="step2", step=TestStep(test_context), args={"result_status": StepStatus.FAILURE})],
[StepToRun(id="step3", step=TestStep(test_context), depends_on=["step2"])],
],
{"step1": StepStatus.SUCCESS, "step2": StepStatus.FAILURE, "step3": StepStatus.SKIPPED},
RunStepOptions(fail_fast=False),
),
],
)
async def test_run_steps_output(desc, steps, expected_results, options):
results = await run_steps(steps, options=options)
for step_id, expected_status in expected_results.items():
assert results[step_id].status == expected_status, desc
@pytest.mark.anyio
async def test_run_steps_throws_on_invalid_order():
concurrent_steps = [
StepToRun(id="step1", step=TestStep(test_context)),
StepToRun(id="step2", step=TestStep(test_context), depends_on=["step1"]),
]
with pytest.raises(InvalidStepConfiguration):
await run_steps(concurrent_steps)
@pytest.mark.anyio
async def test_run_steps_concurrent():
ran_at = {}
class SleepStep(Step):
title = "Sleep Step"
async def _run(self, name, sleep) -> StepResult:
await anyio.sleep(sleep)
ran_at[name] = time.time()
return StepResult(step=self, status=StepStatus.SUCCESS)
steps = [
StepToRun(id="step1", step=SleepStep(test_context), args={"name": "step1", "sleep": 2}),
StepToRun(id="step2", step=SleepStep(test_context), args={"name": "step2", "sleep": 2}),
StepToRun(id="step3", step=SleepStep(test_context), args={"name": "step3", "sleep": 2}),
StepToRun(id="step4", step=SleepStep(test_context), args={"name": "step4", "sleep": 0}),
]
await run_steps(steps)
# assert that step4 is the first step to finish
assert ran_at["step4"] < ran_at["step1"]
assert ran_at["step4"] < ran_at["step2"]
assert ran_at["step4"] < ran_at["step3"]
@pytest.mark.anyio
async def test_run_steps_concurrency_of_1():
ran_at = {}
class SleepStep(Step):
title = "Sleep Step"
async def _run(self, name, sleep) -> StepResult:
ran_at[name] = time.time()
await anyio.sleep(sleep)
return StepResult(step=self, status=StepStatus.SUCCESS)
steps = [
StepToRun(id="step1", step=SleepStep(test_context), args={"name": "step1", "sleep": 1}),
StepToRun(id="step2", step=SleepStep(test_context), args={"name": "step2", "sleep": 1}),
StepToRun(id="step3", step=SleepStep(test_context), args={"name": "step3", "sleep": 1}),
StepToRun(id="step4", step=SleepStep(test_context), args={"name": "step4", "sleep": 1}),
]
await run_steps(steps, options=RunStepOptions(concurrency=1))
# Assert that they run sequentially
assert ran_at["step1"] < ran_at["step2"]
assert ran_at["step2"] < ran_at["step3"]
assert ran_at["step3"] < ran_at["step4"]
@pytest.mark.anyio
async def test_run_steps_sequential():
ran_at = {}
class SleepStep(Step):
title = "Sleep Step"
async def _run(self, name, sleep) -> StepResult:
await anyio.sleep(sleep)
ran_at[name] = time.time()
return StepResult(step=self, status=StepStatus.SUCCESS)
steps = [
[StepToRun(id="step1", step=SleepStep(test_context), args={"name": "step1", "sleep": 1})],
[StepToRun(id="step1", step=SleepStep(test_context), args={"name": "step2", "sleep": 1})],
[StepToRun(id="step3", step=SleepStep(test_context), args={"name": "step3", "sleep": 1})],
[StepToRun(id="step4", step=SleepStep(test_context), args={"name": "step4", "sleep": 0})],
]
await run_steps(steps)
# assert that steps are run in order
assert ran_at["step1"] < ran_at["step2"]
assert ran_at["step2"] < ran_at["step3"]
assert ran_at["step3"] < ran_at["step4"]
@pytest.mark.anyio
async def test_run_steps_passes_results():
"""
Example pattern
StepToRun(
id=CONNECTOR_TEST_STEP_ID.INTEGRATION,
step=IntegrationTests(context),
args=_create_integration_step_args_factory(context),
depends_on=[CONNECTOR_TEST_STEP_ID.BUILD],
),
StepToRun(
id=CONNECTOR_TEST_STEP_ID.ACCEPTANCE,
step=AcceptanceTests(context, True),
args=lambda results: {"connector_under_test_container": results[CONNECTOR_TEST_STEP_ID.BUILD].output[LOCAL_BUILD_PLATFORM]},
depends_on=[CONNECTOR_TEST_STEP_ID.BUILD],
),
"""
class Simple(Step):
title = "Test Step"
async def _run(self, arg1, arg2) -> StepResult:
output = f"{arg1}:{arg2}"
return StepResult(step=self, status=StepStatus.SUCCESS, output=output)
async def async_args(results):
return {"arg1": results["step2"].output, "arg2": "4"}
steps = [
[StepToRun(id="step1", step=Simple(test_context), args={"arg1": "1", "arg2": "2"})],
[StepToRun(id="step2", step=Simple(test_context), args=lambda results: {"arg1": results["step1"].output, "arg2": "3"})],
[StepToRun(id="step3", step=Simple(test_context), args=async_args)],
]
results = await run_steps(steps)
assert results["step1"].output == "1:2"
assert results["step2"].output == "1:2:3"
assert results["step3"].output == "1:2:3:4"
@pytest.mark.anyio
@pytest.mark.parametrize(
"invalid_args",
[
1,
True,
"string",
[1, 2],
None,
],
)
async def test_run_steps_throws_on_invalid_args(invalid_args):
steps = [
[StepToRun(id="step1", step=TestStep(test_context), args=invalid_args)],
]
with pytest.raises(ExceptionGroup) as exc:
await run_steps(steps)
assert len(exc.value.exceptions) == 1
assert isinstance(exc.value.exceptions[0], TypeError)
@pytest.mark.anyio
async def test_run_steps_with_params():
steps = [StepToRun(id="step1", step=TestStep(test_context))]
options = RunStepOptions(fail_fast=True, step_params={"step1": {"--param1": ["value1"]}})
TestStep.accept_extra_params = False
with pytest.raises(ExceptionGroup) as exc:
await run_steps(steps, options=options)
assert len(exc.value.exceptions) == 1
assert isinstance(exc.value.exceptions[0], ValueError)
assert steps[0].step.params_as_cli_options == []
TestStep.accept_extra_params = True
await run_steps(steps, options=options)
assert steps[0].step.params_as_cli_options == ["--param1=value1"]
|
TestStep
|
python
|
altair-viz__altair
|
tools/schemapi/codegen.py
|
{
"start": 1191,
"end": 5150
}
|
class ____:
nonkeyword: bool
required: set[str]
kwds: set[str]
invalid_kwds: set[str]
additional: bool
schema_info: SchemaInfo
def iter_args(
self,
group: Iterable[str] | AttrGetter[ArgInfo, set[str]],
*more_groups: Iterable[str] | AttrGetter[ArgInfo, set[str]],
exclude: str | Iterable[str] | None = None,
) -> Iterator[tuple[str, SchemaInfo]]:
r"""
Yields (property_name, property_info).
Useful for signatures and docstrings.
Parameters
----------
group, \*more_groups
Each group will independently sorted, and chained.
exclude
Property name(s) to omit if they appear during iteration.
"""
props = self.schema_info.properties
it = chain.from_iterable(
sorted(g) for g in self._normalize_groups(group, *more_groups)
)
if exclude is not None:
exclude = {exclude} if isinstance(exclude, str) else set(exclude)
for p in it:
if p not in exclude:
yield p, props[p]
else:
for p in it:
yield p, props[p]
def _normalize_groups(
self, *groups: Iterable[str] | AttrGetter[ArgInfo, set[str]]
) -> Iterator[set[str]]:
for group in groups:
if isinstance(group, set):
yield group
elif isinstance(group, Iterable):
yield set(group)
elif callable(group):
result = group(self)
if isinstance(result, set):
yield result
else:
yield from result
else:
msg = (
f"Expected all cases to be reducible to a `set[str]`,"
f" but got {type(group).__name__!r}"
)
raise TypeError(msg)
arg_required_kwds: AttrGetter[ArgInfo, set[str]] = attrgetter("required", "kwds")
arg_invalid_kwds: AttrGetter[ArgInfo, set[str]] = attrgetter("invalid_kwds")
arg_kwds: AttrGetter[ArgInfo, set[str]] = attrgetter("kwds")
def get_args(info: SchemaInfo) -> ArgInfo:
"""Return the list of args & kwds for building the __init__ function."""
# TODO: - set additional properties correctly
# - handle patternProperties etc.
required: set[str] = set()
kwds: set[str] = set()
invalid_kwds: set[str] = set()
# TODO: specialize for anyOf/oneOf?
if info.is_empty() or info.is_anyOf():
nonkeyword = True
additional = True
elif info.is_object():
invalid_kwds = {p for p in info.required if not is_valid_identifier(p)} | {
p for p in info.properties if not is_valid_identifier(p)
}
required = {p for p in info.required if is_valid_identifier(p)}
kwds = {p for p in info.properties if is_valid_identifier(p)}
kwds -= required
nonkeyword = False
additional = True
# additional = info.additionalProperties or info.patternProperties
else:
nonkeyword = True
additional = False
if info.is_allOf():
# recursively call function on all children
msg = f"Branch is reachable with:\n{info.raw_schema!r}"
raise NotImplementedError(msg)
arginfo: list[ArgInfo] = [get_args(child) for child in info.allOf]
nonkeyword = all(args.nonkeyword for args in arginfo)
required = {args.required for args in arginfo}
kwds = {args.kwds for args in arginfo}
kwds -= required
invalid_kwds = {args.invalid_kwds for args in arginfo}
additional = all(args.additional for args in arginfo)
return ArgInfo(
nonkeyword=nonkeyword,
required=required,
kwds=kwds,
invalid_kwds=invalid_kwds,
additional=additional,
schema_info=info,
)
|
ArgInfo
|
python
|
numba__numba
|
numba/core/base.py
|
{
"start": 43387,
"end": 44302
}
|
class ____(object):
"""
A wrapper object to call an implementation function with some predefined
(context, signature) arguments.
The wrapper also forwards attribute queries, which is important.
"""
def __init__(self, imp, context, sig):
self._callable = _wrap_missing_loc(imp)
self._imp = self._callable()
self._context = context
self._sig = sig
def __call__(self, builder, args, loc=None):
res = self._imp(self._context, builder, self._sig, args, loc=loc)
self._context.add_linking_libs(getattr(self, 'libs', ()))
return res
def __getattr__(self, item):
return getattr(self._imp, item)
def __repr__(self):
return "<wrapped %s>" % repr(self._callable)
def _has_loc(fn):
"""Does function *fn* take ``loc`` argument?
"""
sig = utils.pysignature(fn)
return 'loc' in sig.parameters
|
_wrap_impl
|
python
|
jmcnamara__XlsxWriter
|
xlsxwriter/test/comparison/test_chart_font06.py
|
{
"start": 315,
"end": 2628
}
|
class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_font06.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "bar"})
chart.axis_ids = [49407488, 53740288]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series({"values": "=Sheet1!$A$1:$A$5"})
chart.add_series({"values": "=Sheet1!$B$1:$B$5"})
chart.add_series({"values": "=Sheet1!$C$1:$C$5"})
chart.set_title(
{
"name": "Title",
"name_font": {
"name": "Calibri",
"pitch_family": 34,
"charset": 0,
"color": "yellow",
},
}
)
chart.set_x_axis(
{
"name": "XXX",
"name_font": {
"name": "Courier New",
"pitch_family": 49,
"charset": 0,
"color": "#92D050",
},
"num_font": {
"name": "Arial",
"pitch_family": 34,
"charset": 0,
"color": "#00B0F0",
},
}
)
chart.set_y_axis(
{
"name": "YYY",
"name_font": {
"name": "Century",
"pitch_family": 18,
"charset": 0,
"color": "red",
},
"num_font": {
"bold": 1,
"italic": 1,
"underline": 1,
"color": "#7030A0",
},
}
)
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
|
TestCompareXLSXFiles
|
python
|
huggingface__transformers
|
src/transformers/models/vit/modeling_vit.py
|
{
"start": 5269,
"end": 8272
}
|
class ____(nn.Module):
"""
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
Transformer.
"""
def __init__(self, config: ViTConfig):
super().__init__()
image_size, patch_size = config.image_size, config.patch_size
num_channels, hidden_size = config.num_channels, config.hidden_size
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
self.image_size = image_size
self.patch_size = patch_size
self.num_channels = num_channels
self.num_patches = num_patches
self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
def forward(self, pixel_values: torch.Tensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
batch_size, num_channels, height, width = pixel_values.shape
if num_channels != self.num_channels:
raise ValueError(
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
f" Expected {self.num_channels} but got {num_channels}."
)
if not interpolate_pos_encoding:
if height != self.image_size[0] or width != self.image_size[1]:
raise ValueError(
f"Input image size ({height}*{width}) doesn't match model"
f" ({self.image_size[0]}*{self.image_size[1]})."
)
embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
return embeddings
# Copied from transformers.models.bert.modeling_bert.eager_attention_forward
def eager_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Optional[torch.Tensor],
scaling: Optional[float] = None,
dropout: float = 0.0,
**kwargs: Unpack[TransformersKwargs],
):
if scaling is None:
scaling = query.size(-1) ** -0.5
# Take the dot product between "query" and "key" to get the raw attention scores.
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
if attention_mask is not None:
attention_mask = attention_mask[:, :, :, : key.shape[-2]]
attn_weights = attn_weights + attention_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
attn_output = torch.matmul(attn_weights, value)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
|
ViTPatchEmbeddings
|
python
|
pyqtgraph__pyqtgraph
|
pyqtgraph/examples/customGraphicsItem.py
|
{
"start": 271,
"end": 1954
}
|
class ____(pg.GraphicsObject):
def __init__(self, data):
pg.GraphicsObject.__init__(self)
self.data = data ## data must have fields: time, open, close, min, max
self.generatePicture()
def generatePicture(self):
## pre-computing a QPicture object allows paint() to run much more quickly,
## rather than re-drawing the shapes every time.
self.picture = QtGui.QPicture()
p = QtGui.QPainter(self.picture)
p.setPen(pg.mkPen('w'))
w = (self.data[1][0] - self.data[0][0]) / 3.
for (t, open, close, min, max) in self.data:
p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
if open > close:
p.setBrush(pg.mkBrush('r'))
else:
p.setBrush(pg.mkBrush('g'))
p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open))
p.end()
def paint(self, p, *args):
p.drawPicture(0, 0, self.picture)
def boundingRect(self):
## boundingRect _must_ indicate the entire area that will be drawn on
## or else we will get artifacts and possibly crashing.
## (in this case, QPicture does all the work of computing the bouning rect for us)
return QtCore.QRectF(self.picture.boundingRect())
data = [ ## fields are (time, open, close, min, max).
(1., 10, 13, 5, 15),
(2., 13, 17, 9, 20),
(3., 17, 14, 11, 23),
(4., 14, 15, 5, 19),
(5., 15, 9, 8, 22),
(6., 9, 15, 8, 16),
]
item = CandlestickItem(data)
plt = pg.plot()
plt.addItem(item)
plt.setWindowTitle('pyqtgraph example: customGraphicsItem')
if __name__ == '__main__':
pg.exec()
|
CandlestickItem
|
python
|
keras-team__keras
|
keras/src/backend/torch/core.py
|
{
"start": 23020,
"end": 24369
}
|
class ____(torch.autograd.Function):
"""Enables custom forward & backward passes for gradient computation."""
@staticmethod
def forward(ctx, forward_fn, *args, **kwargs):
"""Forward pass computation specification.
Args:
ctx: Context object.
forward_fn: Function to compute forward pass.
*args: Arguments for the forward pass.
**kwargs: Keyword arguments for the forward pass.
"""
ctx.forward_fn = forward_fn
ctx.save_for_backward(*args)
try:
output, ctx.grad_fn = forward_fn(*args, **kwargs)
except:
output = forward_fn(*args, **kwargs)
ctx.grad_fn = lambda *args, **kwargs: torch.full((), float("nan"))
return output
@staticmethod
def backward(ctx, grad_output):
"""Backward pass computation specification.
Args:
ctx: Context object.
grad_output: Gradient with respect to the output.
"""
args = ctx.saved_tensors
grad_fn = ctx.grad_fn
if grad_fn is None:
raise ValueError("grad_fn must be provided for custom gradient")
grads = grad_fn(*args, upstream=grad_output)
if not isinstance(grads, tuple):
grads = (grads,)
return (None,) + grads
|
CustomGradientFunction
|
python
|
pytorch__pytorch
|
test/onnx/test_pytorch_onnx_onnxruntime.py
|
{
"start": 5515,
"end": 492971
}
|
class ____(onnx_test_common._TestONNXRuntime):
def test_fuse_conv_bn1d(self):
class Fuse(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = torch.nn.Conv1d(16, 33, 3, stride=2)
self.bn = torch.nn.BatchNorm1d(33)
def forward(self, x):
out = self.conv(x)
return self.bn(out)
model = Fuse()
x = torch.randn(20, 16, 50, requires_grad=True)
self.run_test(model, (x,))
def test_fuse_conv_bn2d(self):
class Fuse(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = torch.nn.Conv2d(
3, 2, kernel_size=1, stride=2, padding=3, bias=False
)
self.bn = torch.nn.BatchNorm2d(2)
def forward(self, x):
out = self.conv(x)
return self.bn(out)
model = Fuse()
x = torch.randn(2, 3, 2, 2, requires_grad=True)
self.run_test(model, (x,))
def test_fuse_conv_bn3d(self):
class Fuse(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = torch.nn.Conv3d(
3, 2, (3, 5, 2), stride=(2, 1, 1), padding=(3, 2, 0), bias=False
)
self.bn = torch.nn.BatchNorm3d(2)
def forward(self, x):
out = self.conv(x)
return self.bn(out)
model = Fuse()
x = torch.randn(2, 3, 10, 50, 100, requires_grad=True)
self.run_test(model, (x,), rtol=1e-3, atol=1e-6)
def test_fuse_conv_in_block(self):
class Fuse(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = torch.nn.Conv1d(
in_channels=5,
out_channels=5,
kernel_size=3,
stride=1,
padding=2,
dilation=1,
)
self.bn = torch.nn.BatchNorm1d(5)
def forward(self, x):
results_available = True
if x.sum() > -1:
results_available = False
if results_available:
x = self.conv(x)
x = self.bn(x)
return x
model = Fuse()
x = torch.randn(2, 5, 9, requires_grad=True)
self.run_test(
torch.jit.script(model),
(x,),
input_names=["x"],
dynamic_axes={"x": [0, 2]},
rtol=1e-3,
atol=1e-6,
)
def test_conv_tbc(self):
from torch.nn.modules.utils import _single
class ConvTBC(torch.nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, padding=0):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = _single(kernel_size)
self.padding = _single(padding)
self.weight = torch.nn.Parameter(
Tensor(self.kernel_size[0], in_channels, out_channels)
)
self.bias = torch.nn.Parameter(Tensor(out_channels))
self.reset_parameters()
def reset_parameters(self):
torch.nn.init.xavier_normal_(self.weight)
torch.nn.init.zeros_(self.bias)
def conv_tbc(self, input):
return torch.conv_tbc(
input.contiguous(), self.weight, self.bias, self.padding[0]
)
def forward(self, input):
return self.conv_tbc(input)
in_channels = 3
out_channels = 5
kernel_size = 5
model = ConvTBC(in_channels, out_channels, kernel_size, padding=0)
x = torch.randn(10, 7, in_channels, requires_grad=True)
self.run_test(model, (x,), atol=1e-5)
def test_reshape_constant_fold(self):
class Reshape(torch.nn.Module):
def __init__(
self,
):
super().__init__()
self.weight = torch.nn.Buffer(torch.ones(5))
def forward(self, x):
scale_1 = self.weight.reshape(1, -1, 1, 1)
return x * scale_1
x = torch.randn(4, 5)
self.run_test(Reshape(), (x,), rtol=1e-3, atol=1e-5)
def run_word_language_model(self, model_name):
ntokens = 50
emsize = 5
nhid = 5
nlayers = 5
dropout = 0.2
tied = False
batchsize = 5
if model_name == "GRU":
model = word_language_model.RNNModelWithTensorHidden(
model_name, ntokens, emsize, nhid, nlayers, dropout, tied, batchsize
)
elif model_name == "LSTM":
model = word_language_model.RNNModelWithTupleHidden(
model_name, ntokens, emsize, nhid, nlayers, dropout, tied, batchsize
)
else:
model = word_language_model.RNNModel(
model_name, ntokens, emsize, nhid, nlayers, dropout, tied, batchsize
)
x = torch.arange(0, ntokens).long().view(-1, batchsize)
# Only support CPU version, since tracer is not working in GPU RNN.
self.run_test(model, (x, model.hidden))
def get_image(self, rel_path: str, size: tuple[int, int]) -> Tensor:
from PIL import Image
from torchvision import transforms
data_dir = os.path.join(os.path.dirname(__file__), "assets")
path = os.path.join(data_dir, *rel_path.split("/"))
image = Image.open(path).convert("RGB").resize(size, Image.BILINEAR)
return transforms.ToTensor()(image)
def get_test_images(self) -> tuple[list[Tensor], list[Tensor]]:
return (
[self.get_image("grace_hopper_517x606.jpg", (100, 320))],
[self.get_image("rgb_pytorch.png", (250, 380))],
)
def test_paste_mask_in_image(self):
masks = torch.rand(10, 1, 26, 26)
boxes = torch.rand(10, 4)
boxes[:, 2:] += torch.rand(10, 2)
boxes *= 50
o_im_s = (100, 100)
from torchvision.models.detection.roi_heads import paste_masks_in_image
out = paste_masks_in_image(masks, boxes, o_im_s)
jit_trace = torch.jit.trace(
paste_masks_in_image,
(masks, boxes, [torch.tensor(o_im_s[0]), torch.tensor(o_im_s[1])]),
)
out_trace = jit_trace(
masks, boxes, [torch.tensor(o_im_s[0]), torch.tensor(o_im_s[1])]
)
assert torch.all(out.eq(out_trace))
masks2 = torch.rand(20, 1, 26, 26)
boxes2 = torch.rand(20, 4)
boxes2[:, 2:] += torch.rand(20, 2)
boxes2 *= 100
o_im_s2 = (200, 200)
from torchvision.models.detection.roi_heads import paste_masks_in_image
out2 = paste_masks_in_image(masks2, boxes2, o_im_s2)
out_trace2 = jit_trace(
masks2, boxes2, [torch.tensor(o_im_s2[0]), torch.tensor(o_im_s2[1])]
)
assert torch.all(out2.eq(out_trace2))
def test_heatmaps_to_keypoints(self):
maps = torch.rand(10, 1, 26, 26)
rois = torch.rand(10, 4)
from torchvision.models.detection.roi_heads import heatmaps_to_keypoints
out = heatmaps_to_keypoints(maps, rois)
jit_trace = torch.jit.trace(heatmaps_to_keypoints, (maps, rois))
out_trace = jit_trace(maps, rois)
assert torch.all(out[0].eq(out_trace[0]))
assert torch.all(out[1].eq(out_trace[1]))
maps2 = torch.rand(20, 2, 21, 21)
rois2 = torch.rand(20, 4)
from torchvision.models.detection.roi_heads import heatmaps_to_keypoints
out2 = heatmaps_to_keypoints(maps2, rois2)
out_trace2 = jit_trace(maps2, rois2)
assert torch.all(out2[0].eq(out_trace2[0]))
assert torch.all(out2[1].eq(out_trace2[1]))
def test_word_language_model_RNN_TANH(self):
self.run_word_language_model("RNN_TANH")
def test_word_language_model_RNN_RELU(self):
self.run_word_language_model("RNN_RELU")
@skipScriptTest() # scripting prim::unchecked_cast prim::setattr
def test_word_language_model_LSTM(self):
self.run_word_language_model("LSTM")
def test_word_language_model_GRU(self):
self.run_word_language_model("GRU")
def test_index_1d(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[0]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
def test_index_2d_1dimslice(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[0:1, :]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
def test_index_2d_sliceint(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[1, :]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
def test_index_2d_neg_slice(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[0:-1, :]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
@skipIfUnsupportedMinOpsetVersion(9)
def test_index_mask(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[torch.tensor([0, 1, 0], dtype=torch.uint8)]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
class MyModel(torch.nn.Module):
def forward(self, input):
return input[torch.tensor([0, 1, 0], dtype=torch.bool)]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
@skipIfUnsupportedMinOpsetVersion(9)
def test_data(self):
class Data(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return x.new_zeros(x.data.size())
x = torch.randn(3, 4)
self.run_test(Data(), x, input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(Data(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_mask_nd(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[input > 0]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), m1)
@skipScriptTest()
def test_dict(self):
class MyModel(torch.nn.Module):
def forward(self, x_in):
x_out = {}
x_out["test_key_out"] = torch.add(
x_in[list(x_in.keys())[0]], # noqa: RUF015
list(x_in.keys())[0], # noqa: RUF015
)
return x_out
x = {torch.tensor(1.0): torch.randn(1, 2, 3)}
self.run_test(MyModel(), (x,))
@skipScriptTest()
def test_dict_str(self):
class MyModel(torch.nn.Module):
def forward(self, x_in):
x_out = {}
x_out["test_key_out"] = torch.add(x_in["test_key_in"], 2.0)
return x_out
x = {"test_key_in": torch.randn(1, 2, 3)}
self.run_test(MyModel(), (x,))
@skipScriptTest() # User-defined class not supported
def test_dict_output(self):
class DictModelOutput(OrderedDict):
tensor_out: Tensor
tuple_out: Optional[tuple[Tensor]] = None
list_out: Optional[list[Tensor]] = None
class MyModel(torch.nn.Module):
def forward(self, a, b, c, d):
return DictModelOutput(
tensor_out=a,
tuple_out=(b, c),
list_out=[d],
)
a = torch.randn(2, 3)
b = torch.randn(2, 3)
c = torch.randn(2, 3)
d = torch.randn(2, 3)
self.run_test(MyModel(), (a, b, c, d))
def test_tuple_output(self):
class MyModel(torch.nn.Module):
def forward(self, a, b, c, d):
return a, (b, c), d
a = torch.randn(2, 3)
b = torch.randn(2, 3)
c = torch.randn(2, 3)
d = torch.randn(2, 3)
self.run_test(MyModel(), (a, b, c, d))
def test_nested_tuple_output(self):
class MyModel(torch.nn.Module):
def forward(self, a, b, c, d):
return a, ((b,), (c, d))
a = torch.randn(2, 3)
b = torch.randn(2, 3)
c = torch.randn(2, 3)
d = torch.randn(2, 3)
self.run_test(MyModel(), (a, b, c, d))
def test_tuple_input(self):
class TupleModel(torch.nn.Module):
def forward(self, a: tuple[Tensor, Tensor]):
return a
x = (torch.randn(3, 4), torch.randn(4, 3))
self.run_test(TupleModel(), input_args=(x,))
def test_tuple_primitive_input(self):
class TupleModel(torch.nn.Module):
def forward(self, a: tuple[int, Tensor], b):
return a[0], a[1] + b
x = (3, torch.randn(4, 3))
y = torch.randn(4, 3)
self.run_test(TupleModel(), input_args=(x, y))
def test_nested_tuple_input(self):
class NestedTupleModel(torch.nn.Module):
def forward(self, a, b: tuple[Tensor, tuple[Tensor, Tensor]]):
return a + b[0] + b[1][0] + b[1][1]
x = torch.randn(4, 5)
y = (torch.randn(4, 5), (torch.randn(1, 5), torch.randn(4, 1)))
self.run_test(NestedTupleModel(), input_args=(x, y))
@skipScriptTest() # Needs https://github.com/pytorch/rfcs/pull/21
@skipIfUnsupportedMinOpsetVersion(15)
def test_mixed_optional_default_none(self):
class Model(torch.nn.Module):
def forward(
self,
x,
y: Optional[Tensor] = None,
z: Optional[Tensor] = None,
):
if y is not None:
return x + y
if z is not None:
return x + z
return x
x = torch.randn(2, 3)
y = torch.randn(2, 3)
z = torch.randn(2, 3)
model = Model()
# Without kwargs dict.
self.run_test(model, (x, y, None))
self.run_test(model, (x, None, z))
# With kwargs dict.
self.run_test(model, (x,), {"y": y, "z": None})
self.run_test(model, (x,), {"y": None, "z": z})
self.run_test(model, (x,), {"z": z})
self.run_test(model, (x,), {"y": y})
@skipScriptTest() # tracing eliminates None inputs so it works differently. See _script version below.
@skipIfUnsupportedMinOpsetVersion(15)
def test_mixed_optional_default_tensor(self):
class Model(torch.nn.Module):
def forward(
self,
x,
y: Optional[Tensor] = torch.ones(2, 3),
z: Optional[Tensor] = torch.zeros(2, 3),
):
if y is not None:
return x + y
if z is not None:
return x + z
return x
x = torch.randn(2, 3)
y = torch.randn(2, 3)
z = torch.randn(2, 3)
model = Model()
self.run_test(model, (x, y, None))
self.run_test(model, (x, None, z))
@skipTraceTest() # tracing is verified with different set of inputs. See above.
@skipIfUnsupportedMinOpsetVersion(15)
def test_mixed_optional_default_tensor_script(self):
class Model(torch.nn.Module):
def forward(
self,
x,
y: Optional[Tensor] = torch.ones(2, 3),
z: Optional[Tensor] = torch.zeros(2, 3),
):
if y is not None:
return x + y
if z is not None:
return x + z
return x
x = torch.randn(2, 3)
y = torch.randn(2, 3)
z = torch.randn(2, 3)
model = torch.jit.script(Model())
self.run_test(model, (x, y, z), input_names=("x", "y", "z"))
self.run_test(model, (x,), {"y": y, "z": z}, input_names=("x", "y", "z"))
self.run_test(model, (x,), {"y": y}, input_names=("x", "y"))
for example_inputs, example_kwargs in (
((x, y, None), {}),
((x, None, z), {}),
((x,), {"y": y, "z": None}),
((x,), {"y": None, "z": z}),
):
with self.assertRaisesRegex(
ValueError, "args contained 1 None's after flattening."
):
self.run_test(
model, example_inputs, example_kwargs, input_names=("x", "y", "z")
)
@skipScriptTest() # Needs https://github.com/pytorch/rfcs/pull/21
@skipIfUnsupportedMinOpsetVersion(15)
def test_all_optional_default_none(self):
class Model(torch.nn.Module):
def forward(self, x: Optional[Tensor] = None, y: Optional[Tensor] = None):
if x is not None:
return x
if y is not None:
return y
else:
return torch.tensor(-1.0)
x = torch.randn(2, 3)
model = Model()
self.run_test(model, (x, None))
self.run_test(
model,
(),
{"x": x, "y": None},
# y disappears in tracing.
input_names=("x",),
)
@skipScriptTest() # tracing eliminates None inputs so it works differently. See _script version below.
@skipIfUnsupportedMinOpsetVersion(15)
def test_all_optional_default_tensor(self):
class Model(torch.nn.Module):
def forward(
self,
x: Optional[Tensor] = torch.ones(2, 3),
y: Optional[Tensor] = torch.zeros(2, 3),
):
if x is not None:
return x
elif y is not None:
return y
else:
return torch.tensor(-1.0)
x = torch.randn(2, 3)
y = torch.randn(2, 3)
model = Model()
self.run_test(model, (x, None))
self.run_test(model, (None, y))
# tracing means y is never used so it's removed from the exported model inputs,
# and we fail when trying to run ORT.
with self.assertRaisesRegex(ValueError, "got too many positional inputs"):
self.run_test(model, (x, y))
@skipTraceTest() # tracing is verified with different set of inputs. See above.
@skipIfUnsupportedMinOpsetVersion(15)
def test_all_optional_default_tensor_script(self):
class Model(torch.nn.Module):
def forward(
self,
x: Optional[Tensor] = torch.ones(2, 3),
y: Optional[Tensor] = torch.zeros(2, 3),
):
if x is not None:
return x
elif y is not None:
return y
else:
return torch.tensor(-1.0)
x = torch.randn(2, 3)
y = torch.randn(2, 3)
model = torch.jit.script(Model())
# Optional supports None inputs
self.run_test(model, (x,))
# NOTE: default value is not supported on ONNX, so torch and ONNX has
# different behavior
with self.assertRaisesRegex(AssertionError, "Tensor-likes are not close!"):
self.run_test(model, (), {"y": y}, input_names=["y"])
self.run_test(model, (x, y))
self.run_test(model, (), {"x": x, "y": y}, input_names=("x", "y"))
@skipIfUnsupportedMinOpsetVersion(9)
def test_logit(self):
class Logit(torch.nn.Module):
def __init__(self, eps):
super().__init__()
self.eps = eps
def forward(self, x):
return x.logit(self.eps)
model = Logit(eps=1e-6)
self.run_test(model, torch.randn(1, 3, 640, 640))
class Atleast1d(torch.nn.Module):
def forward(self, t, w, x, y, z):
return torch.atleast_1d((t, w, x, y, z))
class Atleast2d(torch.nn.Module):
def forward(self, t, w, x, y, z):
return torch.atleast_2d((t, w, x, y, z))
class Atleast3d(torch.nn.Module):
def forward(self, t, w, x, y, z):
return torch.atleast_3d((t, w, x, y, z))
class Atleast1dTensor(torch.nn.Module):
def forward(self, x):
return torch.atleast_1d(x)
class Atleast2dTensor(torch.nn.Module):
def forward(self, x):
return torch.atleast_2d(x)
class Atleast3dTensor(torch.nn.Module):
def forward(self, x):
return torch.atleast_3d(x)
@skipScriptTest() # tracing uses prim::ListUnpack to avoid onnx::SequenceConstruct
@skipIfUnsupportedMinOpsetVersion(11)
@common_utils.parametrize("module_class", (Atleast1d, Atleast2d, Atleast3d))
def test_atleast_nd_list_input(self, module_class: torch.nn.Module):
inputs = (
torch.tensor(1.0),
torch.randn(2),
torch.randn(2, 3),
torch.randn(2, 3, 4),
torch.randn(2, 3, 4, 5),
)
self.run_test(module_class(), inputs)
@skipScriptTest() # tracing uses prim::ListUnpack to avoid onnx::SequenceConstruct
@skipIfUnsupportedMinOpsetVersion(11)
@common_utils.parametrize(
"module_class", (Atleast1dTensor, Atleast2dTensor, Atleast3dTensor)
)
@common_utils.parametrize(
"inputs",
[
torch.tensor(1.0),
torch.randn(2),
torch.randn(2, 3),
torch.randn(2, 3, 4),
torch.randn(2, 3, 4, 5),
],
)
def test_atleast_nd_single_tensor_input(
self, module_class: torch.nn.Module, inputs: torch.Tensor
):
self.run_test(module_class(), inputs)
@skipScriptTest() # Needs https://github.com/pytorch/rfcs/pull/21
@skipIfUnsupportedMinOpsetVersion(15)
def test_mixed_optional(self):
class Model(torch.nn.Module):
def forward(self, x, y: Optional[Tensor]):
if y is not None:
return x + y
return x
x = torch.randn(2, 3)
model = Model()
self.run_test(model, (x, None))
self.run_test(model, (x, x))
@skipScriptTest() # Needs https://github.com/pytorch/rfcs/pull/21
@skipIfUnsupportedMinOpsetVersion(15)
def test_tuple_of_optional(self):
class Model(torch.nn.Module):
def forward(self, x, y: tuple[Optional[Tensor], Optional[Tensor]]):
if y[0] is not None:
return x + y[0]
if y[1] is not None:
return x + y[1]
return x
x = torch.randn(2, 3)
y1 = torch.randn(2, 3)
self.run_test(Model(), (x, (None, y1)))
@skipScriptTest() # tracing eliminates None inputs so it works differently. See _script version below.
@skipIfUnsupportedMinOpsetVersion(15)
def test_tuple_of_optional_default_tensor(self):
class Model(torch.nn.Module):
def forward(
self,
x,
y: tuple[Optional[Tensor], Optional[Tensor]] = (
torch.zeros(2, 3),
torch.zeros(2, 3),
),
):
y0, y1 = y
if y0 is not None:
return x + y0
if y1 is not None:
return x + y1
return x
x = torch.randn(2, 3)
y1 = torch.randn(2, 3)
self.run_test(Model(), (x, (None, y1)))
@skipTraceTest() # tracing is verified with different set of inputs. See above.
@skipIfUnsupportedMinOpsetVersion(15)
def test_tuple_of_optional_default_tensor_script(self):
class Model(torch.nn.Module):
def forward(
self,
x,
y: tuple[Optional[Tensor], Optional[Tensor]] = (
torch.zeros(2, 3),
torch.zeros(2, 3),
),
):
y0, y1 = y
if y0 is not None:
return x + y0
if y1 is not None:
return x + y1
return x
x = torch.randn(2, 3)
y0 = torch.randn(2, 3)
y1 = torch.randn(2, 3)
model = torch.jit.script(Model())
with self.assertRaisesRegex(
ValueError, "args contained 1 None's after flattening."
):
self.run_test(model, (x, (None, y1)))
self.run_test(model, (x, (y0, y1)))
# export succeeds, but running ORT through run_test would fail because the exported model
# has the inputs flattened into 3 inputs.
torch.onnx.export(
model,
(x, {"y": (y0, y1)}),
io.BytesIO(),
opset_version=self.opset_version,
dynamo=False,
)
def test_primitive_input_integer(self):
class Model(torch.nn.Module):
def forward(self, x: int, y):
return x + y
x = 3
y = torch.randint(10, (2, 3, 4))
self.run_test(Model(), (x, y))
@skipDtypeChecking
def test_primitive_input_floating(self):
class Model(torch.nn.Module):
def forward(self, x: float, y):
return x + y
x = 3.0
y = torch.randn(2, 3, 4)
self.run_test(Model(), (x, y))
def test_primitive_input_bool(self):
class Model(torch.nn.Module):
def forward(self, flag: bool, x, y):
if flag:
return x
else:
return y
flag = True
x = torch.randn(2, 3, 4)
y = torch.randn(2, 3, 4)
self.run_test(torch.jit.script(Model()), (flag, x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_cste_script(self):
class MyModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.zeros(x.size(0)), torch.ones(
(x.size(1), x.size(0)), dtype=torch.int64
)
x = torch.randn(3, 4)
self.run_test(MyModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(MyModel(), x, remained_onnx_input_idx=[])
def test_scalar_tensor(self):
class test(torch.nn.Module):
def forward(self, input):
return torch.scalar_tensor(input.size(0)), torch.scalar_tensor(
input.size(1), dtype=torch.int64
)
x = torch.randn(2, 3, 4)
y = torch.randn(7, 8, 9)
model = test()
self.run_test(
model,
x,
additional_test_inputs=[y],
input_names=["input_1"],
dynamic_axes={"input_1": [0, 1, 2]},
)
def test_tensor(self):
class ScalarInputModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return torch.tensor(input.shape[1])
x = torch.randn(3, 4)
self.run_test(
ScalarInputModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1]}
)
self.run_test(ScalarInputModel(), x, remained_onnx_input_idx=[])
class TensorInputModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return torch.tensor([input.shape[0], input.shape[1]])
x = torch.randn(3, 4)
self.run_test(
TensorInputModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1]}
)
self.run_test(TensorInputModel(), x, remained_onnx_input_idx=[])
class FloatInputModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return torch.tensor([float(input)])
x = torch.randn(1)
self.run_test(FloatInputModel(), x)
class InputWithDtypeModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return torch.tensor(input.shape[1], dtype=torch.long)
x = torch.randn(3, 4)
self.run_test(
InputWithDtypeModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1]}
)
self.run_test(InputWithDtypeModel(), x, remained_onnx_input_idx=[])
class MixedInputModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return torch.tensor([input.shape[0], int(input)])
x = torch.randn(1)
self.run_test(MixedInputModel(), x)
def test_hardtanh(self):
model = torch.nn.Hardtanh(-1.5, 2.5)
x = torch.arange(-5, 5).to(dtype=torch.float32)
self.run_test(model, x)
def test_hardtanh_script_with_default_values(self):
class MyModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.nn.functional.hardtanh(x)
x = torch.arange(-5, 5).to(dtype=torch.float32)
self.run_test(MyModel(), x)
def test_hardswish(self):
model = torch.nn.Hardswish()
x = torch.rand(3, 3).to(dtype=torch.float32)
self.run_test(model, x)
# Testing edge cases
x = torch.tensor(3).to(dtype=torch.float32)
self.run_test(model, x)
x = torch.tensor(-3).to(dtype=torch.float32)
self.run_test(model, x)
def test_hardswish_script(self):
class MyModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.nn.functional.hardswish(x)
x = torch.rand(3, 3).to(dtype=torch.float32)
self.run_test(MyModel(), x)
def test_hardsigmoid(self):
model = torch.nn.Hardsigmoid()
x = torch.rand(3, 3).to(dtype=torch.float32)
self.run_test(model, x)
# corner cases
x = torch.tensor(3).to(dtype=torch.float32)
self.run_test(model, x)
x = torch.tensor(-3).to(dtype=torch.float32)
self.run_test(model, x)
def test_tanhshrink(self):
model = torch.nn.Tanhshrink()
x = torch.rand(3, 3).to(dtype=torch.float32)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_hardshrink(self):
model = torch.nn.Hardshrink()
x = torch.rand(3, 3).to(dtype=torch.float32)
self.run_test(model, x)
# Testing edge cases
x = torch.tensor(0.5).to(dtype=torch.float32)
self.run_test(model, x)
x = torch.tensor(-0.5).to(dtype=torch.float32)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_hardshrink_dtype(self):
x = torch.rand(3, 3).to(dtype=torch.float64)
self.run_test(torch.nn.Hardshrink(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_softshrink(self):
model = torch.nn.Softshrink()
x = torch.rand(3, 3).to(dtype=torch.float32)
self.run_test(model, x)
# Testing edge cases
x = torch.tensor(0.5).to(dtype=torch.float32)
self.run_test(model, x)
x = torch.tensor(-0.5).to(dtype=torch.float32)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_softshrink_dtype(self):
x = torch.rand(3, 3).to(dtype=torch.float64)
self.run_test(torch.nn.Softshrink(), x)
def test_clamp(self):
class ClampModel(torch.nn.Module):
def forward(self, x):
return x.clamp(-0.5, 0.5)
x = torch.randn(3, 4)
self.run_test(ClampModel(), x)
class ClampMinModel(torch.nn.Module):
def forward(self, x):
return x.clamp(min=-0.5)
x = torch.randn(3, 4)
self.run_test(ClampMinModel(), x)
class ClampMaxModel(torch.nn.Module):
def forward(self, x):
return x.clamp(max=0.5)
x = torch.randn(3, 4)
self.run_test(ClampMaxModel(), x)
@skipIfUnsupportedMinOpsetVersion(8)
def test_clamp_dyn(self):
class ClampMaxModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return x.clamp(None, x.size(0))
x = torch.arange(16).view(4, 4).float()
self.run_test(ClampMaxModel(), x)
class ClampMinModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return x.clamp(x.size(0), None)
x = torch.arange(16).view(4, 4).float()
self.run_test(ClampMinModel(), x)
class ClampMinMaxModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return x.clamp(x.size(0), x.size(1))
x = torch.arange(16).view(2, 8).float()
self.run_test(ClampMinMaxModel(), x)
class ClampTensorModel(torch.nn.Module):
def forward(self, x, min, max):
return x.clamp(min, max)
x = torch.randn(3, 4)
y = torch.randn(3, 4)
z = torch.randn(3, 4)
self.run_test(ClampTensorModel(), (x, y, z))
class ClampTensorMinModel(torch.nn.Module):
def forward(self, x, min):
return x.clamp(min=min)
self.run_test(ClampTensorMinModel(), (x, y))
class ClampTensorMaxModel(torch.nn.Module):
def forward(self, x, max):
return x.clamp(max=max)
self.run_test(ClampTensorMaxModel(), (x, z))
@skipIfUnsupportedMinOpsetVersion(9)
def test_full_trace(self):
class FullModel(torch.nn.Module):
def forward(self, x):
return torch.full((3, 4), x, dtype=torch.long)
x = torch.tensor(12)
self.run_test(FullModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_full_script(self):
class FullModelScripting(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.full((3, 4), x, dtype=torch.long)
x = torch.tensor(12)
self.run_test(FullModelScripting(), x)
def test_fuse_addmm(self):
class AddmmModel(torch.nn.Module):
def forward(self, x):
return torch.mm(x, x) + x
x = torch.ones(3, 3)
self.run_test(AddmmModel(), x)
def test_maxpool(self):
model = torch.nn.MaxPool1d(2, stride=1)
x = torch.randn(20, 16, 50)
self.run_test(model, x)
def test_conv(self):
class TraceModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv1 = torch.nn.Conv1d(16, 33, 3, stride=2)
self.conv2 = torch.nn.Conv2d(
16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1)
)
self.conv3 = torch.nn.Conv3d(
16, 33, (3, 5, 2), stride=(2, 1, 1), padding=(4, 2, 0)
)
def forward(self, input1, input2, input3):
return self.conv1(input1), self.conv2(input2), self.conv3(input3)
x1 = torch.randn(20, 16, 50)
x2 = torch.randn(20, 16, 50, 50)
x3 = torch.randn(20, 16, 10, 50, 50)
self.run_test(TraceModel(), (x1, x2, x3), atol=10e-5)
def test_conv_str_padding(self):
class TraceModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv1 = torch.nn.Conv1d(16, 33, 3, padding="valid")
self.conv2 = torch.nn.Conv2d(
16, 33, (3, 5), stride=1, padding="valid", dilation=(3, 1)
)
self.conv3 = torch.nn.Conv3d(
16, 33, (3, 5, 2), stride=1, padding="same"
)
def forward(self, input1, input2, input3):
return self.conv1(input1), self.conv2(input2), self.conv3(input3)
x1 = torch.randn(20, 16, 50)
x2 = torch.randn(20, 16, 50, 50)
x3 = torch.randn(20, 16, 10, 50, 50)
self.run_test(TraceModel(), (x1, x2, x3), atol=10e-5)
def test_conv_shape_inference(self):
class Model(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv2 = torch.nn.Conv2d(
16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1)
)
def forward(self, input):
return self.conv2(input) + 2
x = torch.randn(20, 16, 50, 100)
self.run_test(
Model(), x, atol=10e-5, input_names=["x"], dynamic_axes={"x": [0]}
)
def test_conv_transpose(self):
class TraceModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv1 = torch.nn.ConvTranspose1d(16, 33, 3, stride=2)
self.conv2 = torch.nn.ConvTranspose2d(
16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1)
)
self.conv3 = torch.nn.ConvTranspose3d(
16, 33, (3, 5, 2), stride=(2, 1, 1), padding=(4, 2, 0)
)
def forward(self, input1, input2, input3):
return self.conv1(input1), self.conv2(input2), self.conv3(input3)
x1 = torch.randn(20, 16, 10)
x2 = torch.randn(20, 16, 10, 10)
x3 = torch.randn(20, 16, 10, 10, 10)
self.run_test(TraceModel(), (x1, x2, x3), atol=10e-5)
def test_numpy_T(self):
class NumpyTranspose(torch.nn.Module):
def forward(self, x):
return x.T
self.run_test(NumpyTranspose(), torch.randn(4, 7))
# Conversion of Transpose depends on input shape to be known.
# The following test only works when onnx shape inference is enabled.
def test_transpose_infer_shape(self):
class TransposeModule(torch.jit.ScriptModule):
def __init__(self) -> None:
super().__init__()
self.conv = torch.nn.Conv2d(3, 1, 3, stride=2)
@torch.jit.script_method
def forward(self, x):
x = self.conv(x)
return x.transpose(0, 1)
x = torch.randn(32, 3, 64, 64)
y = torch.randn(16, 3, 8, 64)
self.run_test(
TransposeModule(),
x,
input_names=["x"],
dynamic_axes={"x": [0, 2]},
additional_test_inputs=[y],
)
def squeeze_model_tests(self, d, x1, x2):
class Squeeze(torch.nn.Module):
def __init__(self, d):
super().__init__()
self.d = d
def forward(self, x):
if self.d is not None:
return torch.squeeze(x, dim=self.d)
else:
return torch.squeeze(x)
x2 = [] if x2 is None else [x2]
if len(x2) > 0:
self.run_test(
Squeeze(d),
x1,
input_names=["input"],
dynamic_axes={"input": {0: "0", 1: "1", 2: "2"}},
additional_test_inputs=x2,
)
else:
self.run_test(Squeeze(d), x1)
def test_squeeze_without_no_op(self):
x = torch.randn(2, 1, 4)
self.squeeze_model_tests(1, x, None)
@skipIfUnsupportedMinOpsetVersion(11)
def test_squeeze_dynamic(self):
x_squeeze = torch.randn(2, 1, 4)
x_noop = torch.randn(2, 2, 3)
self.squeeze_model_tests(1, x_squeeze, x_noop)
def test_squeeze_neg_without_no_op(self):
x = torch.randn(2, 1, 4)
self.squeeze_model_tests(-2, x, None)
@skipIfUnsupportedMinOpsetVersion(11)
def test_squeeze_neg(self):
x_squeeze = torch.randn(2, 1, 4)
x_noop = torch.randn(2, 2, 3)
self.squeeze_model_tests(-2, x_squeeze, x_noop)
def test_squeeze_all_dims(self):
x_squeeze = torch.randn(2, 1, 4)
x_noop = torch.randn(2, 2, 3)
self.squeeze_model_tests(None, x_squeeze, x_noop)
@skipIfUnsupportedMinOpsetVersion(11)
def test_squeeze_no_op(self):
x_noop = torch.randn(2, 1, 4)
x_squeeze = torch.randn(2, 2, 1)
self.squeeze_model_tests(2, x_noop, x_squeeze)
@skipIfUnsupportedMinOpsetVersion(11)
def test_squeeze_runtime_dim(self):
class Squeeze(torch.nn.Module):
def forward(self, d1, d2):
t = torch.zeros(d1[0], d2[0])
return t.squeeze(0)
d1 = torch.tensor([1])
d3 = torch.tensor([3])
d4 = torch.tensor([4])
self.run_test(Squeeze(), (d1, d4), additional_test_inputs=[(d3, d4)])
self.run_test(Squeeze(), (d3, d4), additional_test_inputs=[(d1, d3)])
def test_squeeze(self):
class Squeeze(torch.nn.Module):
def forward(self, x):
return torch.squeeze(x, dim=-2)
x = torch.randn(2, 1, 4)
self.run_test(Squeeze(), x)
@skipIfUnsupportedMinOpsetVersion(13)
def test_squeeze_dynamic_dim(self):
class Squeeze(torch.nn.Module):
def forward(self, x, dim: int):
return torch.squeeze(x, dim)
x = torch.randn(2, 1, 4)
dim = 1
self.run_test(Squeeze(), (x, dim))
def test_unsqueeze(self):
class Unsqueeze(torch.nn.Module):
def forward(self, x):
return torch.unsqueeze(x, dim=-2)
x = torch.randn(2, 3, 4)
self.run_test(Unsqueeze(), x)
@skipIfUnsupportedMinOpsetVersion(13)
def test_unsqueeze_dynamic_dim(self):
class Unsqueeze(torch.nn.Module):
def forward(self, x, dim: int):
return torch.unsqueeze(x, dim)
x = torch.randn(2, 1, 4)
dim = -1
self.run_test(Unsqueeze(), (x, dim))
def test_maxpool_default_stride(self):
class MaxPoolModel(torch.nn.Module):
def forward(self, x):
return torch.nn.functional.max_pool2d(x, 2)
model = MaxPoolModel()
x = torch.randn(10, 20, 16, 50)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(8)
def test_maxpool_adaptive(self):
model = torch.nn.AdaptiveMaxPool1d((5), return_indices=False)
x = torch.randn(20, 16, 50, requires_grad=True)
y = torch.randn(32, 16, 50, requires_grad=True)
self.run_test(
model,
x,
input_names=["x"],
dynamic_axes={"x": [0]},
additional_test_inputs=[y],
)
def test_maxpool_2d(self):
model = torch.nn.MaxPool2d(5, padding=(1, 2))
x = torch.randn(1, 20, 16, 50, requires_grad=True)
self.run_test(model, x)
def test_maxpool_1d_ceil(self):
model = torch.nn.MaxPool1d(3, 2, ceil_mode=True)
x = torch.randn(20, 16, 50)
self.run_test(model, x)
def test_maxpool_2d_ceil(self):
model = torch.nn.MaxPool2d(3, 2, ceil_mode=True)
x = torch.randn(20, 16, 50, 32)
self.run_test(model, x)
def test_maxpool_3d_ceil(self):
model = torch.nn.MaxPool3d(3, 2, ceil_mode=True)
x = torch.randn(20, 16, 50, 44, 31)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(10)
def test_maxpool_dynamic(self):
class test(torch.nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
norm_layer = functools.partial(torch.nn.BatchNorm2d, eps=0.0009)
self.avgpool = torch.nn.MaxPool2d((2, 2), stride=2, ceil_mode=True)
self.conv = torch.nn.Conv2d(
in_channels, out_channels, kernel_size=1, stride=1, bias=False
)
self.norm = norm_layer(out_channels)
def forward(self, x):
return self.norm(self.conv(self.avgpool(x)))
model = test(8, 16)
inputs = torch.randn(2, 8, 64, 64)
self.run_test(
model,
inputs,
input_names=["input_0"],
dynamic_axes={"input_0": {3: "x", 2: "y"}, "output_0": {3: "x", 2: "y"}},
output_names=["output_0"],
)
# TODO: Enable maxpool-ceil family after ONNX 1.15.1+ is bumped
@skipIfUnsupportedMaxOpsetVersion(9)
def test_maxpool_1d_ceil_corner(self):
model = torch.nn.MaxPool1d(
kernel_size=1, dilation=1, stride=2, ceil_mode=True, return_indices=False
)
x = torch.randn(1, 3, 32)
self.run_test(model, x)
@skipIfUnsupportedMaxOpsetVersion(9)
def test_maxpool_2d_ceil_corner(self):
model = torch.nn.MaxPool2d(
kernel_size=[1, 1],
dilation=[1, 1],
stride=[2, 2],
ceil_mode=True,
return_indices=False,
)
x = torch.randn(1, 3, 32, 32)
self.run_test(model, x)
@skipIfUnsupportedMaxOpsetVersion(9)
def test_maxpool_3d_ceil_corner(self):
model = torch.nn.MaxPool3d(
kernel_size=[7, 8, 4],
dilation=[1, 1, 1],
stride=[10, 11, 3],
padding=[2, 2, 2],
ceil_mode=True,
return_indices=False,
)
x = torch.randn(1, 3, 51, 52, 45)
self.run_test(model, x)
@skipIfUnsupportedMaxOpsetVersion(9)
@skipIfUnsupportedMinOpsetVersion(8)
def test_maxpool_1d_ceil_corner_with_indices(self):
model = torch.nn.MaxPool1d(
kernel_size=1, dilation=1, stride=2, ceil_mode=True, return_indices=True
)
x = torch.randn(1, 3, 32)
self.run_test(model, x)
@skipIfUnsupportedMaxOpsetVersion(9)
@skipIfUnsupportedMinOpsetVersion(8)
def test_maxpool_2d_ceil_corner_with_indices(self):
model = torch.nn.MaxPool2d(
kernel_size=[1, 1],
dilation=[1, 1],
stride=[2, 2],
ceil_mode=True,
return_indices=True,
)
x = torch.randn(1, 3, 32, 32)
self.run_test(model, x)
@skipIfUnsupportedMaxOpsetVersion(9)
@skipIfUnsupportedMinOpsetVersion(8)
def test_maxpool_3d_ceil_corner_with_indices(self):
model = torch.nn.MaxPool3d(
kernel_size=[7, 8, 4],
dilation=[1, 1, 1],
stride=[10, 11, 3],
padding=[2, 2, 2],
ceil_mode=True,
return_indices=True,
)
x = torch.randn(1, 3, 51, 52, 45)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(8)
def test_maxpool_with_indices(self):
model = torch.nn.MaxPool1d(2, stride=1, return_indices=True)
x = torch.randn(20, 16, 50)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(10)
def test_maxpool_dilation(self):
model = torch.nn.MaxPool1d(2, stride=1, dilation=2)
x = torch.randn(20, 16, 50)
self.run_test(model, x)
def test_avgpool_default_stride(self):
class AvgPoolModel(torch.nn.Module):
def forward(self, x):
return torch.nn.functional.avg_pool2d(x, 2)
model = AvgPoolModel()
x = torch.randn(10, 20, 16, 50)
self.run_test(model, x)
def test_avgpool(self):
model = torch.nn.AvgPool1d(2, stride=1)
x = torch.randn(20, 16, 50)
self.run_test(model, x)
def test_avgpool_1d_ceil(self):
model = torch.nn.AvgPool1d(3, 2, ceil_mode=True)
x = torch.randn(1, 1, 7)
self.run_test(model, x)
# TODO: ceil_mode is not included in the test, because of
# https://github.com/microsoft/onnxruntime/issues/16203
# The ORT and PyTorch has different calculation for ceil_mode (the last value).
@common_utils.parametrize(
"padding",
(0, 1),
)
@common_utils.parametrize(
"count_include_pad",
(True, False),
)
def test_avgpool_2d(self, padding, count_include_pad):
model = torch.nn.AvgPool2d(
3,
3,
padding=padding,
count_include_pad=count_include_pad,
)
x = torch.randn(20, 16, 50, 32)
self.run_test(model, x)
# TODO: ceil_mode is not included in the test, because of
# https://github.com/microsoft/onnxruntime/issues/16203
# The ORT and PyTorch has different calculation for ceil_mode (the last value).
# the issue requires fix in onnx(21) (https://github.com/onnx/onnx/issues/5711)
# a fix in ORT is planned. After the fixes in place, we can add ceil_mode to the test.
@skipIfUnsupportedMinOpsetVersion(21)
def test_avgpool_3d_ceil(self):
model = torch.nn.AvgPool3d(3, 2, ceil_mode=True)
x = torch.randn(20, 16, 50, 44, 31)
y = torch.randn(32, 8, 50, 44, 31)
self.run_test(
model,
x,
input_names=["x"],
dynamic_axes={"x": [0, 1]},
additional_test_inputs=[y],
)
@skipIfUnsupportedMinOpsetVersion(10)
def test_avgpool_dynamic(self):
class test(torch.nn.Module):
def __init__(self, in_channels, out_channels):
super().__init__()
norm_layer = functools.partial(torch.nn.BatchNorm2d, eps=0.0009)
self.avgpool = torch.nn.AvgPool2d(
(2, 2), stride=2, ceil_mode=True, count_include_pad=False
)
self.conv = torch.nn.Conv2d(
in_channels, out_channels, kernel_size=1, stride=1, bias=False
)
self.norm = norm_layer(out_channels)
def forward(self, x):
return self.norm(self.conv(self.avgpool(x)))
model = test(8, 16)
inputs = torch.randn(2, 8, 64, 64)
self.run_test(
model,
inputs,
input_names=["input_0"],
dynamic_axes={"input_0": {3: "x", 2: "y"}, "output_0": {3: "x", 2: "y"}},
output_names=["output_0"],
)
@skipIfUnsupportedMinOpsetVersion(9)
def test_floating_point(self):
class FloatingPoint(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
if x.is_floating_point():
return x.new_zeros(x.shape)
return x.new_zeros(x.shape)
x = torch.randn(2, 3, 4)
self.run_test(
FloatingPoint(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]}
)
self.run_test(FloatingPoint(), x, remained_onnx_input_idx=[])
class FloatingPoint(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
if x.size(0) > 1:
a = x + 2
if a.is_floating_point():
return x + 1
return x + 1
return x
x = torch.randn(2, 3, 4)
self.run_test(FloatingPoint(), x)
# Operator rank mismatch between outputs of two branches for opsets below 11.
@skipIfUnsupportedMinOpsetVersion(11)
def test_floating_point_infer_dtype(self):
class FloatingPoint(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
if x.size(0) > 1:
a = x + 2
if a.is_floating_point():
return x.new_zeros(x.shape[1:])
return x.new_zeros(x.shape)
return x
x = torch.randn(2, 3, 4)
self.run_test(
FloatingPoint(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]}
)
self.run_test(FloatingPoint(), x, remained_onnx_input_idx=[])
class FloatingPoint(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
if x.size(0) > 1:
a = x + 2
if a.is_floating_point():
return x + 1
return x
return x
x = torch.randn(2, 3, 4).to(torch.int32)
self.run_test(FloatingPoint(), x)
@skipIfUnsupportedMinOpsetVersion(12)
def test_prim_min(self):
@torch.jit.script
def list_append(boxes: list[Tensor]):
temp = []
for i, b in enumerate(
boxes
): # enumerate is creating a prim::min op in torch graph
temp.append(torch.full_like(b[:, 1], i))
return temp[0]
class Min(torch.nn.Module):
def forward(self, x):
boxes = [x for _ in range(3)]
return list_append(boxes)
x = torch.rand(5, 5)
self.run_test(Min(), (x,))
class M(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
i = 3
return min(x[i], i)
x = torch.arange(6, dtype=torch.int64)
self.run_test(M(), (x,))
def test_arithmetic(self):
class ArithmeticModule(torch.nn.Module):
def forward(self, x):
x = x + 2
x = x - 4
x = x * 6
x = x / 8
return x
x = torch.randn(2, 3, 4)
self.run_test(ArithmeticModule(), x)
def test_arithmetic_prim_long(self):
class ArithmeticModule(torch.nn.Module):
def forward(self, x, y: int):
x = x + y
x = x - y
x = x * (y * 3)
x = x / (y * 4)
return x
x = torch.randn(2, 3, 4)
y = 2
self.run_test(ArithmeticModule(), (x, y))
class ArithmeticModule(torch.nn.Module):
def forward(self, x):
x = x + 2
x = x - 3
return x.shape[0]
x = torch.randn(2, 3, 4)
self.run_test(ArithmeticModule(), x, remained_onnx_input_idx=[])
@skipDtypeChecking
def test_arithmetic_prim_float(self):
class ArithmeticModule(torch.nn.Module):
def forward(self, x, y: float):
x = x + y
x = x - y
x = x * (y * 3)
x = x / (y * 4)
return x
x = torch.randn(2, 3, 4)
y = 2.5
self.run_test(ArithmeticModule(), (x, y))
class ArithmeticModule(torch.nn.Module):
def forward(self, x):
x = x + 2
x = x - 3
return x.shape[1] / 2
x = torch.randn(2, 3, 4)
self.run_test(ArithmeticModule(), x, remained_onnx_input_idx=[])
@skipDtypeChecking
def test_arithmetic_prim_bool(self):
class ArithmeticModule(torch.nn.Module):
def forward(self, x, y: int, z: bool, t: float):
x = x + y
x = x - y
if z:
x = x * (y * 3)
x = x / (y * 4)
return x / t, z
x = torch.randn(2, 3, 4)
y = 2
z = False
t = 2.5
self.run_test(ArithmeticModule(), (x, y, z, t))
class ArithmeticModule(torch.nn.Module):
def forward(self, x: int, y: int):
return x == y
x = 3
y = 2
self.run_test(ArithmeticModule(), (x, y))
@skipScriptTest(
15,
reason="In trace: Outputs that are always None are removed. \
In script: Outputs that are always None are removed before opset 15. \
After opset 15, we replace the None in output with Optional node.",
)
def test_tuple_with_none_outputs(self):
class TupleModel(torch.nn.Module):
def forward(self, x):
return (x, (x, None, (x, None)))
x = torch.randn(3, 4)
self.run_test(TupleModel(), (x,))
# In scripting the first transpose node do not carry shape and dtype info.
# The following test only works when onnx shape inference is enabled.
def test_arithmetic_infer_dtype(self):
class ArithmeticModule(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
x = x.t()
x = x + 2
x = x - 4
x = x * 6
x = x / 8
return x
x = torch.randn(2, 3)
self.run_test(ArithmeticModule(), x)
@unittest.skip("Floor division on ONNX is inconsistent with eager (see #78411)")
def test_floor_div(self):
class FloorDivModule(torch.nn.Module):
def forward(self, x, y):
return (
x // 3,
x // 2.0,
x.to(dtype=torch.float64) // 3,
x.to(dtype=torch.float64) // 2.0,
x.to(dtype=torch.int64) // 3,
x.to(dtype=torch.int64) // 2.0,
x // (y + 1.0).to(dtype=torch.int64),
x // y,
x.to(dtype=torch.float64) // y.to(dtype=torch.int64),
x.to(dtype=torch.float64) // y.to(dtype=torch.float64),
x.to(dtype=torch.int64) // y.to(dtype=torch.int64),
x.to(dtype=torch.int64) // y,
)
x = torch.arange(-2, 4).reshape(2, 3, 1)
y = torch.arange(1, 2 * 3 * 4 + 1).reshape(2, 3, 4)
self.run_test(FloorDivModule(), (x, y))
@unittest.skip("Floor division on ONNX is inconsistent with eager (see #78411)")
def test_floor_div_script(self):
class FloorDivModule(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x, y):
return x // 3, x // 2.0, x // y
x = torch.arange(-2, 4).reshape(2, 3, 1)
y = torch.randn(2, 3, 4)
self.run_test(FloorDivModule(), (x, y))
@unittest.skip("Floor division on ONNX is inconsistent with eager (see #78411)")
@skipIfUnsupportedMinOpsetVersion(9)
def test_floordiv(self):
class FloordivModule(torch.nn.Module):
def forward(self, x):
return x.new_zeros(x.size(2) // x.size(1))
x = torch.randn(2, 3, 4)
self.run_test(
FloordivModule(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]}
)
self.run_test(FloordivModule(), (x,), remained_onnx_input_idx=[])
def test_div(self):
class DivModule(torch.nn.Module):
def forward(self, x, y):
return x / y, torch.true_divide(x, y)
x = torch.randn(2, 3, 4).to(torch.int)
y = torch.arange(1, 2 * 3 * 4 + 1).reshape(2, 3, 4).to(torch.int)
self.run_test(DivModule(), (x, y))
self.run_test(DivModule(), (x.float(), y.float()))
# Note: div cannot (generally) be exported via scripting
# since its type promotion logic is dependent on knowing the scalar types
# of the input tensors. That is, the ONNX graph is dependent on the
# data type of the inputs. This makes it appropriate for tracing only.
def test_div_promotion_trace(self):
class DivModule(torch.nn.Module):
def forward(self, x, y):
return x / y, torch.true_divide(x, y)
x = torch.randn(2, 3, 4).to(torch.int)
y = torch.arange(1, 2 * 3 * 4 + 1).reshape(2, 3, 4).to(torch.int)
with common_utils.set_default_dtype(torch.float):
self.run_test(torch.jit.trace(DivModule(), (x, y)), (x, y))
with common_utils.set_default_dtype(torch.double):
self.run_test(torch.jit.trace(DivModule(), (x, y)), (x, y))
# In scripting x, y do not carry shape and dtype info.
# The following test only works when onnx shape inference is enabled.
def test_div_promotion_script(self):
class DivModule(torch.nn.Module):
def forward(self, x, y):
# Add transpose to hide shape/type information
# Otherwise shape and type are still available from input.
x = x.transpose(1, 2)
y = y.transpose(1, 2)
return x / y, torch.true_divide(x, y)
x = torch.randn(2, 3, 4).to(torch.int)
y = torch.arange(1, 2 * 3 * 4 + 1).reshape(2, 3, 4).to(torch.int)
# 1. x,y are int, and output is float.
# This can be handled by the default case, where both are cast to float.
# It works even if type of x, y are unknown.
with common_utils.set_default_dtype(torch.float):
self.run_test(torch.jit.script(DivModule()), (x, y))
# 2. x,y are int, and output is double.
# This can be handled by the default case, where both are cast to double.
# It works even if type of x, y are unknown.
with common_utils.set_default_dtype(torch.double):
self.run_test(torch.jit.script(DivModule()), (x, y))
# 3. x is int, y is double, and output is double.
# This can only be handled when both type of x and y are known.
x = torch.randn(2, 3, 4).to(torch.int)
y = torch.arange(1, 2 * 3 * 4 + 1).reshape(2, 3, 4).to(torch.double)
self.run_test(torch.jit.script(DivModule()), (x, y))
@skipDtypeChecking
def test_div_rounding_mode(self):
class TrueDivModule(torch.nn.Module):
def forward(self, x, y):
return (
x.div(y, rounding_mode=None),
torch.div(x, y, rounding_mode=None),
)
class TruncDivModule(torch.nn.Module):
def forward(self, x, y):
return (
x.div(y, rounding_mode="trunc"),
torch.div(x, y, rounding_mode="trunc"),
)
class FloorDivModule(torch.nn.Module):
def forward(self, x, y):
return (
x.div(y, rounding_mode="floor"),
torch.div(x, y, rounding_mode="floor"),
)
modules = [TrueDivModule(), TruncDivModule(), FloorDivModule()]
x = (torch.randn(2, 3, 4) * 100).to(torch.int)
y = torch.arange(1, 2 * 3 * 4 + 1).reshape(2, 3, 4).to(torch.int)
for module in modules:
self.run_test(module, (x, y))
self.run_test(torch.jit.trace(module, (x, y)), (x, y))
self.run_test(torch.jit.script(module), (x, y))
x = torch.randn(2, 3, 4)
y = torch.rand(2, 3, 4) * 10.0 + 0.1
for module in modules:
self.run_test(module, (x, y))
self.run_test(torch.jit.trace(module, (x, y)), (x, y))
self.run_test(torch.jit.script(module), (x, y))
def test_slice_trace(self):
class MyModule(torch.nn.Module):
def forward(self, x):
return x[0:1]
x = torch.randn(3)
self.run_test(MyModule(), x)
def test_slice_neg(self):
class NegSlice(torch.nn.Module):
def forward(self, x):
return x[-1:]
x = torch.randn(3, 4, 5)
self.run_test(NegSlice(), x)
def test_slice_neg_large(self):
class NegSlice(torch.nn.Module):
def forward(self, x):
return x[:, :, -3:-1, :, -1]
x = torch.randn(3, 4, 5, 6, 7)
self.run_test(NegSlice(), x)
def test_slice_neg_large_negone(self):
class NegSlice(torch.nn.Module):
def forward(self, x):
return x[:, :, :, :, -1]
x = torch.randn(3, 4, 5, 6, 7)
self.run_test(NegSlice(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_slice_with_input_index(self):
class InputIndexSlice(torch.nn.Module):
def forward(self, x, y):
x[: y.size(0), 0, :] = y
return x
x = torch.zeros((56, 6, 256))
y = torch.rand((22, 256))
self.run_test(InputIndexSlice(), (x, y))
@skipIfUnsupportedMinOpsetVersion(11)
@skipScriptTest() # Torchscript doesn't support 1d index.
def test_slice_with_1d_input_index(self):
class InputIndexSlice(torch.nn.Module):
def forward(self, x, y):
x[:y, 0, :] = y
return x
x = torch.zeros((56, 6, 256))
y = torch.tensor([5], dtype=torch.int64)
self.run_test(InputIndexSlice(), (x, y))
@skipIfUnsupportedMinOpsetVersion(11)
def test_slice_with_input_step_size(self):
class InputIndexSlice(torch.nn.Module):
def forward(self, x, y, z):
x[:y:z, 0::z, :] = 1
return x
x = torch.zeros((56, 6, 256))
y = torch.tensor(5, dtype=torch.int64)
z = torch.tensor(2, dtype=torch.int64)
self.run_test(InputIndexSlice(), (x, y, z))
@skipIfUnsupportedMinOpsetVersion(10)
@skipScriptTest() # scripting tuple/list append
def test_slice_dynamic(self):
class DynamicSliceExportMod(torch.nn.Module):
def forward(self, x):
results = []
for i in range(4):
results.append(x[: x.size(0) - i, i : x.size(2), i:3])
return tuple(results)
x = torch.rand(5, 5, 5)
y = torch.randn(6, 7, 8)
self.run_test(
DynamicSliceExportMod(),
x,
additional_test_inputs=[y],
input_names=["input_1"],
output_names=["output_1"],
dynamic_axes={"input_1": [0, 1, 2], "output_1": [0, 1, 2]},
)
@skipIfUnsupportedMinOpsetVersion(10)
def test_slice_dynamic_script(self):
class DynamicSliceModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return x[1 : x.size(1)]
x = torch.rand(1, 2)
self.run_test(DynamicSliceModel(), x)
@skipIfUnsupportedMinOpsetVersion(10)
def test_slice_dynamic_shape_script(self):
class DynamicSliceModel(torch.nn.Module):
def forward(self, x):
return x.new_zeros(x.shape[1 : x.size(2)])
x = torch.rand(1, 2, 3, 4)
self.run_test(
DynamicSliceModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2, 3]}
)
self.run_test(DynamicSliceModel(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(10)
@skipScriptTest() # scripting tuple/list append
def test_slice_dynamic_to_end(self):
class DynamicSliceExportMod(torch.nn.Module):
def forward(self, x):
results = []
for i in range(4):
results.append(x[:, i:, x.size(2) - 5])
return tuple(results)
x = torch.rand(5, 5, 5)
self.run_test(
DynamicSliceExportMod(),
x,
dynamic_axes={"input_1": [0, 1, 2], "output_1": [0, 1, 2]},
)
def test_square(self):
class Square(torch.nn.Module):
def forward(self, x):
return torch.square(x)
x = torch.randn(2, 3, 4)
self.run_test(Square(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_arange_dynamic(self):
class ArangeModel(torch.nn.Module):
def forward(self, input):
return (
torch.arange(input.shape[0]),
torch.arange(12),
torch.arange(start=input.shape[0], end=input.shape[0] + 5),
)
x = torch.randn(5, 3, 2)
y = torch.randn(8, 3, 2)
self.run_test(
ArangeModel(),
x,
additional_test_inputs=[y],
input_names=["input_1"],
output_names=["output_1", "output_2", "output_3"],
dynamic_axes={"input_1": [0], "output_1": [0]},
)
self.run_test(
torch.jit.script(ArangeModel()),
x,
additional_test_inputs=[y],
input_names=["input_1"],
output_names=["output_1", "output_2", "output_3"],
dynamic_axes={"input_1": [0], "output_1": [0]},
)
@skipIfUnsupportedMinOpsetVersion(9)
def test_dynamic_arange_out(self):
class ArangeOutModel(torch.nn.Module):
def forward(self, end):
out_t = torch.tensor([1], dtype=torch.int64)
return torch.arange(end, out=out_t)
x = torch.tensor(8)
self.run_test(ArangeOutModel(), (x))
@skipIfUnsupportedMinOpsetVersion(9)
def test_dynamic_arange_start_out(self):
class ArangeStartOutModel(torch.nn.Module):
def forward(self, start, end):
out_t = torch.tensor([1], dtype=torch.int64)
return torch.arange(start.size(0), end, out=out_t)
x = torch.randn(2, 3, 4)
y = torch.tensor(8)
self.run_test(
ArangeStartOutModel(),
(x, y),
input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2]},
)
self.run_test(ArangeStartOutModel(), (x, y), remained_onnx_input_idx=[1])
@skipIfUnsupportedMinOpsetVersion(9)
def test_linspace(self):
class LinspaceModel(torch.nn.Module):
def forward(self, start, end, steps):
return torch.linspace(start, end, steps)
x = torch.tensor(3, dtype=torch.float)
y = torch.tensor(10, dtype=torch.float)
z = torch.tensor(5, dtype=torch.int)
self.run_test(LinspaceModel(), (x, y, z))
@skipIfUnsupportedMinOpsetVersion(9)
def test_linspace_negative_start(self):
class LinspaceModel(torch.nn.Module):
def forward(self, start, end, steps):
return torch.linspace(start, end, steps)
x = torch.tensor(-1, dtype=torch.float)
y = torch.tensor(1, dtype=torch.float)
z = torch.tensor(6, dtype=torch.int)
self.run_test(LinspaceModel(), (x, y, z))
@skipIfUnsupportedMinOpsetVersion(9)
def test_arange_with_floats_out(self):
class ArangeModelEnd(torch.nn.Module):
def forward(self, end):
out_t = torch.tensor([1], dtype=torch.float)
return torch.arange(end, out=out_t)
y = torch.tensor(8.5, dtype=torch.float)
self.run_test(ArangeModelEnd(), (y))
class ArangeModelStep(torch.nn.Module):
def forward(self, start, end):
out_t = torch.tensor([1], dtype=torch.float)
return torch.arange(start.size(0), end, 1.5, out=out_t)
x = torch.randn(2, 3, 4)
y = torch.tensor(8.5, dtype=torch.float)
self.run_test(
ArangeModelStep(),
(x, y),
input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2]},
)
self.run_test(ArangeModelStep(), (x, y), remained_onnx_input_idx=[1])
@skipIfUnsupportedMinOpsetVersion(9)
def test_arange_with_floats(self):
class ArangeModelEnd(torch.nn.Module):
def forward(self, end):
return torch.arange(end)
y = torch.tensor(8.5, dtype=torch.float)
self.run_test(ArangeModelEnd(), (y))
class ArangeModelStep(torch.nn.Module):
def forward(self, start, end):
return torch.arange(start.size(0), end, 1.5)
x = torch.randn(2, 3, 4)
y = torch.tensor(8.5, dtype=torch.float)
self.run_test(
ArangeModelStep(),
(x, y),
input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2]},
)
self.run_test(ArangeModelStep(), (x, y), remained_onnx_input_idx=[1])
class ArangeModelStepNeg(torch.nn.Module):
def forward(self, start, end):
return torch.arange(end, start.size(0), -1.5)
x = torch.randn(2, 3, 4)
y = torch.tensor(8.5, dtype=torch.float)
self.run_test(
ArangeModelStepNeg(),
(x, y),
input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2]},
)
self.run_test(ArangeModelStepNeg(), (x, y), remained_onnx_input_idx=[1])
class ArangeModelStart(torch.nn.Module):
def forward(self, start, end):
return torch.arange(start.size(0), end)
x = torch.randn(2, 3, 4)
y = torch.tensor(8.5, dtype=torch.float)
self.run_test(
ArangeModelStart(),
(x, y),
input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2]},
)
self.run_test(ArangeModelStart(), (x, y), remained_onnx_input_idx=[1])
@skipIfUnsupportedMinOpsetVersion(9)
def test_arange_with_floats_override(self):
class ArangeModelEnd(torch.nn.Module):
def forward(self, end):
return torch.arange(end, dtype=torch.int64)
y = torch.tensor(8.5, dtype=torch.float)
self.run_test(ArangeModelEnd(), (y))
class ArangeModelStep(torch.nn.Module):
def forward(self, start, end):
return torch.arange(start.size(0), end, 1.5, dtype=torch.int64)
x = torch.randn(2, 3, 4)
y = torch.tensor(8.5, dtype=torch.float)
self.run_test(
ArangeModelStep(),
(x, y),
input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2]},
)
self.run_test(ArangeModelStep(), (x, y), remained_onnx_input_idx=[1])
@skipIfUnsupportedMinOpsetVersion(11)
def test_arange_out(self):
class ArangeOutModel(torch.nn.Module):
def forward(self, end):
out_t = torch.tensor([1], dtype=torch.float)
return torch.arange(end, out=out_t)
x = torch.tensor(8.5, dtype=torch.float)
self.run_test(ArangeOutModel(), (x))
@skipIfUnsupportedMinOpsetVersion(11)
def test_arange_start_out(self):
class ArangeStartOutModel(torch.nn.Module):
def forward(self, start, end):
out_t = torch.tensor([1], dtype=torch.float)
return torch.arange(start.size(0), end, out=out_t)
x = torch.randn(2, 3, 4)
y = torch.tensor(8.5, dtype=torch.float)
self.run_test(
ArangeStartOutModel(),
(x, y),
input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2]},
)
self.run_test(ArangeStartOutModel(), (x, y), remained_onnx_input_idx=[1])
@skipIfUnsupportedMinOpsetVersion(11)
def test_arange_no_type(self):
class ArangeModel(torch.nn.Module):
def forward(self, end):
return torch.arange(end), torch.arange(0, end)
x = torch.tensor(6.2, dtype=torch.float)
self.run_test(ArangeModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_size(self):
class SizeModel(torch.nn.Module):
def forward(self, input):
return (
torch.arange(input.size(0)),
torch.arange(input.size(-1)),
torch.ones(input.shape),
)
x = torch.randn(5, 3, 2)
self.run_test(SizeModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(SizeModel(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
@skipScriptTest() # x.stride() not scriptable
def test_as_strided(self):
class Model(torch.nn.Module):
def forward(self, x):
chunk_size = list(x.size())
chunk_size[1] = chunk_size[1] * 2 - 1
chunk_stride = list(x.stride())
chunk_stride[1] = chunk_stride[1] // 2
return x.as_strided(
(3, 3, 3), (1, 4, 2), storage_offset=2
), x.as_strided(chunk_size, chunk_stride)
x = torch.randn(5, 8, 7)
self.run_test(Model(), x)
@skipScriptTest() # Ellipses followed by tensor indexing not scriptable
def test_tensor_index_advanced_indexing_ellipsis(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[..., torch.tensor([2, 1]), torch.tensor([0, 3])]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), (m1,))
def test_tensor_index_advanced_indexing(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[
:,
torch.tensor([[0, 2], [1, 1]]),
:,
torch.tensor([2, 1]),
torch.tensor([0, 3]),
]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), (m1,))
class MyModel(torch.nn.Module):
def forward(self, input):
return input[
:, torch.tensor([0, 2]), None, 2:4, torch.tensor([[1, 3], [4, 0]])
]
self.run_test(MyModel(), (m1,))
class MyModel(torch.nn.Module):
def forward(self, input):
return input[
:,
torch.tensor([0, 2]),
torch.tensor([1]),
2:4,
torch.tensor([[1], [4]]),
]
self.run_test(MyModel(), (m1,))
def test_tensor_index_advanced_indexing_consecutive(self):
class MyModel(torch.nn.Module):
def forward(self, input):
return input[
:, torch.tensor([0, 2]), torch.tensor([[1, 3], [4, 0]]), None
]
m1 = torch.randn(3, 4, 5, 6, 7)
self.run_test(MyModel(), (m1,))
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put(self):
class IndexPutModel(torch.nn.Module):
def forward(self, x, ind, update):
x[ind] = update
return x
x = torch.randn(3, 4)
ind = torch.tensor([1], dtype=torch.long)
update = torch.ones(4)
self.run_test(IndexPutModel(), (x, ind, update))
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_singular(self):
class IndexPutBoolModel(torch.nn.Module):
def forward(self, mask, indices):
mask[indices] = True
return mask
mask = torch.zeros(100, dtype=torch.bool)
indices = (torch.rand(25) * mask.shape[0]).to(torch.int64)
self.run_test(IndexPutBoolModel(), (mask, indices))
class IndexPutFloatModel(torch.nn.Module):
def forward(self, mask, indices):
mask[indices] = torch.tensor(5.5)
return mask
mask = torch.rand(100, dtype=torch.float)
indices = (torch.rand(50) * mask.shape[0]).to(torch.int64)
self.run_test(IndexPutFloatModel(), (mask, indices))
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_accumulate(self):
class IndexPutModel(torch.nn.Module):
def forward(self, x, ind, update):
return x.index_put((ind,), update, accumulate=True)
x = torch.randn(3, 4)
ind = torch.tensor([2], dtype=torch.long)
update = torch.ones(4)
self.run_test(IndexPutModel(), (x, ind, update))
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_slice_index(self):
class IndexPutModel(torch.nn.Module):
def forward(self, x, update):
x[1:2, 1:3, torch.tensor([1])] += update
return x
x = torch.randn(3, 4, 5)
update = torch.tensor([10, 15]).view(1, 2, 1)
self.run_test(IndexPutModel(), (x, update))
class IndexPutModel2(torch.nn.Module):
def forward(self, x, update):
x[torch.tensor([0, 2]), torch.tensor([1, 2])] += update
return x
x = torch.randn(3, 4, 5)
update = torch.randn(2, 5)
self.run_test(IndexPutModel2(), (x, update))
class IndexPutModel3(torch.nn.Module):
def forward(self, x, update):
x[torch.tensor([0, 2]), 1:2] += update
return x
x = torch.randn(3, 4, 5)
update = torch.tensor([10, 15]).view(2, 1, 1)
self.run_test(IndexPutModel3(), (x, update))
class IndexPutModel4(torch.nn.Module):
def forward(self, x, update):
x[torch.tensor([0, 2]), 2] += update
return x
x = torch.randn(3, 4, 5)
update = torch.tensor([10, 15]).view(2, 1)
self.run_test(IndexPutModel4(), (x, update))
class IndexPutModel5(torch.nn.Module):
def forward(self, x, update):
x[1:3, torch.tensor([0, 2]), 2] += update
return x
x = torch.randn(3, 4, 5)
update = torch.tensor([10, 15]).view(2, 1)
self.run_test(IndexPutModel5(), (x, update))
class IndexPutModel6(torch.nn.Module):
def forward(self, x, update):
x[1:3, 0] = update
return x
x = torch.randn(3, 4, 5)
update = torch.arange(2 * 5).to(torch.float).view(2, 5)
self.run_test(IndexPutModel6(), (x, update))
class IndexPutModel7(torch.nn.Module):
def forward(self, x, update):
x[1:, 0] = update
return x
x = torch.randn(3, 4, 5)
update = torch.arange(2 * 5).to(torch.float).view(2, 5)
self.run_test(IndexPutModel7(), (x, update))
class IndexPutModel8(torch.nn.Module):
def forward(self, x, update):
x[:3, 0] = update
return x
x = torch.randn(3, 4, 5)
update = torch.arange(3 * 5).to(torch.float).view(3, 5)
self.run_test(IndexPutModel8(), (x, update))
class IndexPutModel9(torch.nn.Module):
def forward(self, poses):
w = 32
x = poses[:, :, 0] - (w - 1) // 2
boxes = torch.zeros([poses.shape[0], 17, 4])
boxes[:, :, 0] = x
return boxes
x = torch.zeros([2, 17, 3], dtype=torch.int64)
self.run_test(IndexPutModel9(), (x,))
class IndexPutModel10(torch.nn.Module):
def forward(self, x, ind, update):
x[ind, 1:3] = update.view(1, 1, 1, 5).expand(2, 2, 2, 5)
return x
x = torch.randn(3, 4, 5)
ind = torch.tensor([[0, 2], [1, 1]])
update = torch.randn(5)
self.run_test(IndexPutModel10(), (x, ind, update))
@skipIfUnsupportedMinOpsetVersion(11)
@skipScriptTest() # Ellipses followed by tensor indexing not scriptable
def test_index_put_ellipsis(self):
class IndexPutModel(torch.nn.Module):
def forward(self, x, update):
x[..., torch.tensor([2, 1, 3]), 2:4] += update
return x
x = torch.randn(3, 4, 5, 6, 7)
update = torch.randn(3, 1, 1, 3, 2)
self.run_test(IndexPutModel(), (x, update))
class IndexPutModel2(torch.nn.Module):
def forward(self, x, update):
x[2, ..., torch.tensor([2, 1, 3]), 2:4] += update
return x
x = torch.randn(3, 4, 5, 6, 7)
update = torch.randn(4, 1, 3, 2)
self.run_test(IndexPutModel2(), (x, update))
@unittest.skip(
"regression in 1.18: https://github.com/microsoft/onnxruntime/issues/20855"
)
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_loop(self):
@torch.jit.script
def ngram_attention_bias(
sequence_length: int, ngram: int, device: torch.device, dtype: torch.dtype
):
bias = torch.ones(
(ngram, sequence_length), device=device, dtype=dtype
) * float("-inf")
for stream_idx in range(ngram):
for i in range(sequence_length):
bias = bias * 2
bias[stream_idx, i] = 5
bias = bias * 5
bias[0, 0] = 5
for stream_idx in range(ngram):
for i in range(sequence_length):
bias[stream_idx, i] = 5
bias[0, i] = 5
return bias
class ScriptModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.ngram = 2
self.max_target_positions = 512
def forward(self, hidden_states):
seq_length, batch_size = hidden_states.shape[:2]
predict_causal_mask = ngram_attention_bias(
self.max_target_positions,
self.ngram,
hidden_states.device,
hidden_states.dtype,
)
predict_causal_mask = predict_causal_mask[:, :seq_length]
return predict_causal_mask
x = torch.randn(6, 2)
y = torch.randn(4, 1)
self.run_test(
ScriptModel(),
x,
input_names=["x"],
dynamic_axes={"x": {0: "seq_length", 1: "batch_size"}},
additional_test_inputs=[y],
)
@skipIfUnsupportedMinOpsetVersion(11)
def test_copy_(self):
class CopyModel(torch.nn.Module):
def forward(self, x, data):
x[1:3] = data
return x
x = torch.randn(3, 4)
update = torch.randn(2, 4)
self.run_test(CopyModel(), (x, update))
# mixed slice and select
class CopyModel2(torch.nn.Module):
def forward(self, x, data):
x[1:3, 0] = data
return x
x = torch.randn(3, 4)
update = torch.tensor([0], dtype=torch.float32)
self.run_test(CopyModel2(), (x, update))
update = torch.tensor([2, 3], dtype=torch.float32)
self.run_test(CopyModel2(), (x, update))
update = torch.randn(2)
self.run_test(CopyModel2(), (x, update))
class CopyModel3(torch.nn.Module):
def forward(self, x, data):
x[1, 1:3] = data
return x
x = torch.randn(3, 4)
update = torch.tensor([0], dtype=torch.float32)
self.run_test(CopyModel3(), (x, update))
update = torch.tensor([2, 3], dtype=torch.float32)
self.run_test(CopyModel3(), (x, update))
update = torch.randn(2)
self.run_test(CopyModel3(), (x, update))
class CopyModel4(torch.nn.Module):
def forward(self, x, ind, data):
x[ind] = data
return x
x = torch.randn(3, 4)
ind = torch.tensor(2)
data = torch.randn(4)
self.run_test(CopyModel4(), (x, ind, data))
class CopyModel5(torch.nn.Module):
def forward(self, x, mask):
if mask is not None:
x.copy_(mask)
return x
x = torch.randn(3, 4)
mask = torch.randn(3, 1)
self.run_test(CopyModel5(), (x, mask))
@skipIfUnsupportedMinOpsetVersion(11)
@skipScriptTest() # Model not scriptable (output with shape doesn't match the broadcast shape)
def test_copy_tracing(self):
class CopyModel(torch.nn.Module):
def forward(self, x, data):
x[1, 1:3] = data
return x
x = torch.randn(3, 4)
update = torch.randn(1, 2)
self.run_test(CopyModel(), (x, update))
@skipIfUnsupportedMinOpsetVersion(11)
def test_copy_ellipsis(self):
class CopyModel(torch.nn.Module):
def forward(self, x, update):
x[..., 1] = update
return x
x = torch.randn(2, 3, 4)
update = torch.ones(1)
self.run_test(CopyModel(), (x, update))
x = torch.randn(2, 3, 4, 5, 6)
update = torch.ones(1)
self.run_test(CopyModel(), (x, update))
@skipIfUnsupportedMinOpsetVersion(11)
def test_copy_ellipsis_script(self):
class CopyModel(torch.nn.Module):
def forward(self, x, update):
# Insert reshape node to ensure no shape/type info for
# x in scripting, without onnx shape inference.
x = x.reshape(4, 3, 5, 6)
x[2, ..., 1:3] = update
return x
x = torch.randn(3, 4, 5, 6)
update = torch.ones(1)
self.run_test(CopyModel(), (x, update))
@skipIfUnsupportedMinOpsetVersion(10)
def test_flip(self):
class MyModule(torch.nn.Module):
def forward(self, x):
return torch.flip(x, dims=[0])
x = torch.tensor(np.arange(6.0).reshape(2, 3))
self.run_test(MyModule(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_randint(self):
class RandInt(torch.nn.Module):
def forward(self, x):
randint = torch.randint(1, 10, x.shape)
x = 0 * randint + x
return x
x = torch.randn(2, 3, 4)
self.run_test(RandInt(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_randint_value(self):
class RandInt(torch.nn.Module):
def forward(self, x):
# This randint call always returns 3
return torch.randint(3, 4, x.shape) + x
x = torch.randn(2, 3, 4)
self.run_test(RandInt(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_randint_like(self):
class RandInt(torch.nn.Module):
def forward(self, x):
# This randint call always returns 3
return torch.randint_like(x, 3, 4) + x
x = torch.randn(2, 3, 4)
self.run_test(RandInt(), x)
def test_randn(self):
class RandN(torch.nn.Module):
def forward(self, x):
return torch.mul(x, (torch.randn(2, 3, 4) + x).size(0))
x = torch.randn(2, 3, 4)
self.run_test(RandN(), x)
def test_rand(self):
class Rand(torch.nn.Module):
def forward(self, x):
return torch.mul(x, (torch.rand(2, 3, 4) + x).size(0))
x = torch.randn(2, 3, 4)
self.run_test(Rand(), x)
def test_randn_dtype(self):
class RandN(torch.nn.Module):
def forward(self, x):
# The resulting node's dtype should be double.
return (
x.to(torch.float32)
* torch.randn(2, 3, 4, dtype=torch.double)
* torch.tensor(0, dtype=torch.float32)
)
x = torch.randn(2, 3, 4)
self.run_test(RandN(), x)
def test_rand_dtype(self):
class Rand(torch.nn.Module):
def forward(self, x):
# The resulting node's dtype should be double.
return (
x.to(torch.float32)
* torch.rand(2, 3, 4, dtype=torch.double)
* torch.tensor(0, dtype=torch.float32)
)
x = torch.randn(2, 3, 4)
self.run_test(Rand(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_randn_dynamic_size(self):
class RandN(torch.nn.Module):
def forward(self, x):
return torch.mul(x, torch.randn(x.size()).size(1))
x = torch.randn(2, 3, 4)
self.run_test(RandN(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_rand_dynamic_size(self):
class Rand(torch.nn.Module):
def forward(self, x):
return torch.mul(x, torch.rand(x.size()).size(1))
x = torch.randn(2, 3, 4)
self.run_test(Rand(), x)
def test_randn_like(self):
class RandNLike(torch.nn.Module):
def forward(self, x):
return torch.mul(x, torch.randn_like(x).size(0))
x = torch.randn(2, 3, 4)
self.run_test(RandNLike(), x)
self.run_test(torch.jit.script(RandNLike()), x)
def test_rand_like(self):
class RandLike(torch.nn.Module):
def forward(self, x):
return torch.mul(x, torch.rand_like(x).size(0))
x = torch.randn(2, 3, 4)
self.run_test(RandLike(), x)
self.run_test(torch.jit.script(RandLike()), x)
def test_randn_like_dtype(self):
class RandNLike(torch.nn.Module):
def forward(self, x):
# The resulting node's dtype should be double.
return (
x.to(torch.float32)
* torch.randn_like(x, dtype=torch.double)
* torch.tensor(0, dtype=torch.float32)
)
x = torch.randn(2, 3, 4)
self.run_test(RandNLike(), x)
def test_rand_like_dtype(self):
class RandLike(torch.nn.Module):
def forward(self, x):
# The resulting node's dtype should be double.
return (
x.to(torch.float32)
* torch.rand_like(x, dtype=torch.double)
* torch.tensor(0, dtype=torch.float32)
)
x = torch.randn(2, 3, 4)
self.run_test(RandLike(), x)
def test_bernoulli(self):
class Bernoulli(torch.nn.Module):
def forward(self, x):
return torch.mul(x, torch.bernoulli(x).size(0))
x = torch.empty(3, 3).uniform_(0, 1)
self.run_test(Bernoulli(), x)
x = torch.empty(2, 3, 3, dtype=torch.double).uniform_(0, 1)
self.run_test(Bernoulli(), x)
def test_bernoulli_p(self):
class Bernoulli_float(torch.nn.Module):
def forward(self, x):
return torch.mul(x, torch.bernoulli(x, 0.2).size(0))
class Bernoulli_tensor(torch.nn.Module):
def forward(self, x):
return torch.mul(x, torch.rand_like(x).bernoulli_(x).size(0))
x = torch.rand(3, 3)
self.run_test(Bernoulli_float(), x)
self.run_test(Bernoulli_tensor(), x)
x = torch.rand(2, 3, 3, dtype=torch.double)
self.run_test(Bernoulli_float(), x)
self.run_test(Bernoulli_tensor(), x)
@unittest.skip("Bug in ORT, skip test until rel-1.11.")
@skipIfUnsupportedMinOpsetVersion(14)
def test_reshape_allowzero(self):
class ReshapeModel(torch.nn.Module):
def forward(self, x):
x = x.reshape(3, 4, 0)
return x
x = torch.randn(0, 3, 4)
self.run_test(ReshapeModel(), x)
def test_reshape_different_rank(self):
class ReshapeModel(torch.nn.Module):
def forward(self, x):
x = x.reshape(-1, 2, 4, 4, 5, 5)
return x
x = torch.randn(1, 32, 5, 5)
self.run_test(ReshapeModel(), x)
def _interpolate(self, x, mode, use_size, is_upsample, align_corners=False):
class MyModel(torch.nn.Module):
__constants__ = [
"mode",
"use_size",
"is_upsample",
"size",
"scale",
"size_array",
"scale_array",
"align_corners",
]
def __init__(self, mode, use_size, is_upsample, align_corners):
super().__init__()
self.mode = mode
self.use_size = use_size
self.is_upsample = is_upsample
self.align_corners = align_corners
self.scale = 2.0 if self.is_upsample else 0.5
self.size = 24 if self.is_upsample else 2
if x.dim() == 3:
self.scale_array = [2.3]
self.size_array = [16]
elif x.dim() == 4:
self.scale_array = [2.3, 3.1]
self.size_array = [16, 32]
else:
self.scale_array = [2.3, 3.1, 4.6]
self.size_array = [16, 32, 64]
def forward(self, x):
if self.use_size:
if self.align_corners:
return torch.nn.functional.interpolate(
x, mode=self.mode, size=self.size, align_corners=True
), torch.nn.functional.interpolate(
x, mode=self.mode, size=self.size_array, align_corners=True
)
return torch.nn.functional.interpolate(
x, mode=self.mode, size=self.size
), torch.nn.functional.interpolate(
x, mode=self.mode, size=self.size_array
)
if self.align_corners:
return torch.nn.functional.interpolate(
x,
mode=self.mode,
scale_factor=self.scale,
recompute_scale_factor=False,
), torch.nn.functional.interpolate(
x,
mode=self.mode,
scale_factor=self.scale_array,
recompute_scale_factor=False,
)
return torch.nn.functional.interpolate(
x,
mode=self.mode,
scale_factor=self.scale,
recompute_scale_factor=False,
), torch.nn.functional.interpolate(
x,
mode=self.mode,
scale_factor=self.scale_array,
recompute_scale_factor=False,
)
model = MyModel(mode, use_size, is_upsample, align_corners)
self.run_test(model, x, atol=1e-6)
def _interpolate_tests(self, is_upsample):
# - cubic mode is not supported for opsets below 11;
# - linear mode does not match for opsets below 11;
modes = ["nearest", "linear", "bicubic"]
if self.opset_version < 11:
modes = ["nearest"]
x = [
torch.randn(1, 2, 6, requires_grad=True),
torch.randn(1, 2, 4, 6, requires_grad=True),
torch.randn(1, 2, 4, 4, 6, requires_grad=True),
]
for mode in modes:
for xi in x:
mode_i = mode
# TODO: enable bicubic downsample when ORT precision loss fixed
if mode == "bicubic" and xi.dim() != 4:
continue
elif mode == "linear":
if xi.dim() == 3:
# TODO : enable when linear mode is implemented for 1d inputs in ORT
continue
elif xi.dim() == 4:
mode_i = "bilinear"
elif xi.dim() == 5:
# TODO : enable when linear mode is implemented for 3d inputs in ORT
mode_i = "trilinear"
continue
self._interpolate(xi, mode_i, True, is_upsample)
# test with align_corners if supported
if mode != "nearest":
self._interpolate(xi, mode_i, True, is_upsample, True)
# the following cases, require dynamic sizes/scales,
# which which is not supported for opset_version < 9
if self.opset_version >= 9:
self._interpolate(xi, mode_i, True, is_upsample)
# test with align_corners if supported
if mode != "nearest":
self._interpolate(xi, mode_i, False, is_upsample, True)
self._interpolate(xi, mode_i, False, is_upsample)
# ONNX export failed on interpolate scripting because dynamic size not supported for opsets below 9.
@skipIfUnsupportedMinOpsetVersion(9)
def test_interpolate_upsample(self):
self._interpolate_tests(True)
@skipIfUnsupportedMaxOpsetVersion(8)
@skipScriptTest() # Scripting supported for opsets > 8. See test_interpolate_upsample
def test_interpolate_upsample_trace(self):
self._interpolate_tests(True)
@skipIfUnsupportedMinOpsetVersion(9)
def test_interpolate_function_substitution(self):
class ScriptModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.nn.functional.interpolate(
x, mode="nearest", scale_factor=2.0
)
class ScriptModule(torch.jit.ScriptModule):
def __init__(self) -> None:
super().__init__()
self.submodule = ScriptModel()
@torch.jit.script_method
def forward(self, input):
return self.submodule(input)
x = torch.randn(1, 2, 4, 4, 6)
self.run_test(ScriptModule(), (x,))
@torch.jit.script
def script_method(x):
return torch.nn.functional.interpolate(x, mode="nearest", scale_factor=2.0)
class TracingModule(torch.nn.Module):
def forward(self, x):
return script_method(x)
self.run_test(TracingModule(), (x,))
@skipIfUnsupportedMinOpsetVersion(10)
def test_interpolate_downsample(self):
self._interpolate_tests(False)
@skipIfUnsupportedMinOpsetVersion(11)
def test_interpolate_half_pixel(self):
# testing whether it uses "half_pixel" or "pytorch_half_pixel"
# see https://github.com/onnx/onnx/blob/main/docs/Operators.md#Resize
class MyModel(torch.nn.Module):
def __init__(self, mode, size):
super().__init__()
self.mode = mode
self.size = size
def forward(self, x):
return torch.nn.functional.interpolate(
x, mode=self.mode, size=self.size
)
modes = ["linear", "bicubic"]
x = [
torch.randn(1, 2, 6, requires_grad=True),
torch.randn(1, 2, 4, 6, requires_grad=True),
torch.randn(1, 2, 4, 4, 6, requires_grad=True),
]
for mode in modes:
for xi in x:
mode_i = mode
if mode == "bicubic" and xi.dim() != 4:
continue
elif mode == "linear":
if xi.dim() == 4:
mode_i = "bilinear"
elif xi.dim() == 5:
mode_i = "trilinear"
for i in range(xi.dim() - 2):
size = list(xi.shape[2:])
size[i] = 1
self.run_test(MyModel(mode_i, size), xi)
@skipIfUnsupportedMinOpsetVersion(11)
def test_interpolate_no_shape(self):
class MyModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x, y):
x = torch.add(x, x)
out1 = torch.nn.functional.interpolate(
x, mode="bilinear", size=(16, 16), align_corners=False
)
out2 = torch.nn.functional.interpolate(
x, mode="nearest", size=(int(y.size(0)), int(y.size(1)))
)
return out1, out2
x = torch.randn(1, 2, 4, 4, requires_grad=True)
y = torch.randn(16, 16, requires_grad=True)
self.run_test(
MyModel(),
(x, y),
input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2, 3], "y": [0, 1]},
)
self.run_test(MyModel(), (x, y), remained_onnx_input_idx=[0])
@skipScriptTest() # scripting raises OnnxRuntimeError
def test_interpolate_adaptive_pooling_error(self):
x = torch.randn(1, 2, 6, requires_grad=True)
with self.assertRaises(RuntimeError) as cm:
self._interpolate(x, "area", True, True)
with self.assertRaises(RuntimeError) as cm:
self._interpolate(x, "area", False, True)
def test_groupnorm(self):
model = torch.nn.GroupNorm(3, 6, 0.002)
x = torch.randn(4, 6, 36, 36, 18)
self.run_test(model, x)
model = torch.nn.GroupNorm(1, 6, 0.002)
x = torch.randn(4, 6, 180, 180)
self.run_test(model, x)
model = torch.nn.GroupNorm(6, 6, 0.002)
x = torch.randn(4, 6, 180, 180)
self.run_test(model, x)
def test_groupnorm_noaffine(self):
model = torch.nn.GroupNorm(4, 8, 0.002, affine=False)
x = torch.randn(3, 8, 224, 224)
self.run_test(model, x)
model = torch.nn.GroupNorm(1, 6, 0.002, affine=False)
x = torch.randn(4, 6, 180, 180)
self.run_test(model, x)
model = torch.nn.GroupNorm(6, 6, 0.002, affine=False)
x = torch.randn(4, 6, 180, 180)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_list_unpack_scripted(self):
class ListUnpack(torch.nn.Module):
def forward(self, x):
a, b = x.shape
return x.new_zeros((a, b))
x = torch.randn(2, 3)
self.run_test(
torch.jit.script(ListUnpack()),
x,
input_names=["x"],
dynamic_axes={"x": [0, 1]},
)
self.run_test(torch.jit.script(ListUnpack()), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_list_unpack_scripted_runs_without_error_with_constructed_list_as_input(
self,
):
class PackUnpack(torch.nn.Module):
"""Create and unpack a list of tensors.
When scripted, it should produce a graph similar to
```
graph(%self : __torch__.PackUnpack,
%a.1 : Tensor,
%b.1 : Tensor):
%packed.1 : Tensor[] = prim::ListConstruct(%a.1, %b.1)
%c.1 : Tensor, %8 : Tensor = prim::ListUnpack(%packed.1)
return (%c.1)
```
"""
def forward(self, a, b):
packed = [a, b]
c, _ = packed
return c
self.run_test(
torch.jit.script(PackUnpack()),
(torch.tensor(0), torch.tensor([42])),
remained_onnx_input_idx=[0],
)
@skipIfUnsupportedMinOpsetVersion(9)
def test_list_unpack_slice_scripted(self):
class ListUnpackSlice(torch.nn.Module):
def forward(self, x):
a, b = x.shape[2:]
return x.new_zeros((a, b))
x = torch.randn(2, 3, 4, 5)
self.run_test(
torch.jit.script(ListUnpackSlice()),
x,
input_names=["x"],
dynamic_axes={"x": [0, 1, 2, 3]},
)
self.run_test(
torch.jit.script(ListUnpackSlice()), x, remained_onnx_input_idx=[]
)
@skipDtypeChecking
def test_pow(self):
class PowModule(torch.nn.Module):
def forward(self, x, y):
return x.pow(y)
x = torch.randn(2, 3, 4)
y = torch.randn(2, 3, 4)
self.run_test(PowModule(), (x, y))
x = torch.randint(10, (2, 3, 4))
y = torch.randint(10, (2, 3, 4)).to(dtype=torch.int32)
self.run_test(PowModule(), (x, y))
x = torch.randint(10, (2, 3, 4))
y = torch.randint(10, (2, 3, 4))
self.run_test(PowModule(), (x, y))
x = torch.randn(2, 3, 4).to(dtype=torch.float64)
y = torch.randint(10, (2, 3, 4))
self.run_test(PowModule(), (x, y))
class PowModule2(torch.nn.Module):
def forward(self, x):
return torch.pow(2, x)
x = torch.randn(1, 10)
self.run_test(PowModule2(), (x,))
x = torch.randint(10, (2, 3, 4))
self.run_test(PowModule2(), (x,))
x = torch.randn(1, 10).to(dtype=torch.float64)
self.run_test(PowModule2(), (x,))
class PowModule3(torch.nn.Module):
def forward(self, x, y):
return y[torch.pow(2, x)]
x = torch.randint(5, (2, 3, 4))
y = torch.rand(100)
self.run_test(PowModule3(), (x, y))
# the arithmeticOps(Add\Sub\Mul\Div\Gemm\Pow\Mod) with low precision include unit8 will be failed in ORT
# add to(dtype=torch.long) to avoid ORT output type does not match expected type.
# will be fixed in ONNX version 14.
@skipIfUnsupportedMaxOpsetVersion(13)
@skipDtypeChecking
def test_arithmeticOps_with_low_precision(self):
class AddModule(torch.nn.Module):
def forward(self, x, y):
return x + y
class SubModule(torch.nn.Module):
def forward(self, x, y):
return x - y
class MulModule(torch.nn.Module):
def forward(self, x, y):
return x * y
class DivModule(torch.nn.Module):
def forward(self, x, y):
return x / y
class PowModule(torch.nn.Module):
def forward(self, x, y):
return x.pow(y)
x = torch.tensor([2, 3, 5], dtype=torch.uint8)
y = torch.tensor([2, 3, 5], dtype=torch.uint8)
z = torch.tensor([1], dtype=torch.uint8)
self.run_test(AddModule(), (x, y))
self.run_test(SubModule(), (x, y))
self.run_test(MulModule(), (x, y))
self.run_test(DivModule(), (x, y))
self.run_test(PowModule(), (x, z))
x = torch.tensor([2, 3, 5], dtype=torch.int8)
y = torch.tensor([2, 3, 5], dtype=torch.int8)
z = torch.tensor([1], dtype=torch.int8)
self.run_test(AddModule(), (x, y))
self.run_test(SubModule(), (x, y))
self.run_test(MulModule(), (x, y))
self.run_test(DivModule(), (x, y))
self.run_test(PowModule(), (x, z))
x = torch.tensor([2, 3, 5], dtype=torch.int16)
y = torch.tensor([2, 3, 5], dtype=torch.int16)
z = torch.tensor([1], dtype=torch.int16)
self.run_test(AddModule(), (x, y))
self.run_test(SubModule(), (x, y))
self.run_test(MulModule(), (x, y))
self.run_test(DivModule(), (x, y))
self.run_test(PowModule(), (x, z))
x = torch.tensor([2, 3, 5], dtype=torch.uint8)
y = torch.tensor([2, 3, 5], dtype=torch.float32)
z = torch.tensor([1], dtype=torch.float64)
self.run_test(AddModule(), (x, y))
self.run_test(SubModule(), (x, y))
self.run_test(MulModule(), (x, y))
self.run_test(DivModule(), (x, y))
self.run_test(PowModule(), (x, z))
x = torch.tensor([2, 3, 5], dtype=torch.uint8)
y = torch.tensor([2, 3, 5], dtype=torch.int64)
z = torch.tensor([1], dtype=torch.int32)
self.run_test(AddModule(), (x, y))
self.run_test(SubModule(), (x, y))
self.run_test(MulModule(), (x, y))
self.run_test(DivModule(), (x, y))
self.run_test(PowModule(), (x, z))
def test_mul_bool(self):
class MyModel(torch.nn.Module):
def forward(self, x, y):
return torch.mul(x, y)
x_t = torch.tensor([True, False, True, False])
y_t = torch.tensor([True, True, False, False])
z_t = torch.tensor([1.0, 2.0, 3.0, 0.0])
self.run_test(MyModel(), (x_t, y_t))
self.run_test(MyModel(), (x_t, z_t))
self.run_test(MyModel(), (z_t, y_t))
# fmod was added in version 10
@skipIfUnsupportedMinOpsetVersion(10)
@skipIfUnsupportedMaxOpsetVersion(13)
def test_mod_with_low_precision(self):
class ModModule(torch.nn.Module):
def forward(self, x, y):
return torch.fmod(x, y).to(dtype=torch.long)
x = torch.tensor([2, 3, 5], dtype=torch.uint8)
y = torch.tensor([2, 3, 5], dtype=torch.uint8)
self.run_test(ModModule(), (x, y))
x = torch.tensor([2, 3, 5], dtype=torch.int8)
y = torch.tensor([2, 3, 5], dtype=torch.int8)
self.run_test(ModModule(), (x, y))
x = torch.tensor([2, 3, 5], dtype=torch.int16)
y = torch.tensor([2, 3, 5], dtype=torch.int16)
self.run_test(ModModule(), (x, y))
x = torch.tensor([2, 3, 5], dtype=torch.uint8)
y = torch.tensor([2, 3, 5], dtype=torch.int32)
self.run_test(ModModule(), (x, y))
x = torch.tensor([2, 3, 5], dtype=torch.uint8)
y = torch.tensor([2, 3, 5], dtype=torch.float64)
self.run_test(ModModule(), (x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_empty_constant_shape(self):
class Zeros(torch.nn.Module):
def forward(self, x):
y = torch.zeros(())
y += x
return y
x = torch.tensor(42.0)
self.run_test(Zeros(), x)
class Ones(torch.nn.Module):
def forward(self, x):
y = torch.ones(())
y += x
return y
x = torch.tensor(42.0)
self.run_test(Ones(), x)
class Full(torch.nn.Module):
def forward(self, x):
y = torch.full((), 1.0)
y += x
return y
x = torch.tensor(42.0)
self.run_test(Full(), x)
class Empty(torch.nn.Module):
def forward(self, x):
y = torch.empty(()).fill_(0)
y += x
return y
x = torch.tensor(42.0)
self.run_test(Empty(), x)
def test_std(self):
class StandardDeviation(torch.nn.Module):
def forward(self, input):
return torch.std(input, unbiased=False)
x = torch.randn(2, 3, 4)
model = StandardDeviation()
self.run_test(model, x)
class StandardDeviationUnbiased(torch.nn.Module):
def forward(self, input):
return torch.std(input, unbiased=True)
model = StandardDeviationUnbiased()
self.run_test(model, x)
def test_std_along_dims(self):
class StandardDeviation(torch.nn.Module):
def forward(self, input):
return torch.std(input, dim=(0, 1), unbiased=False)
x = torch.randn(2, 3, 4)
model = StandardDeviation()
self.run_test(model, x)
class StandardDeviationUnbiased(torch.nn.Module):
def forward(self, input):
return torch.std(input, dim=(0, 1), unbiased=True)
x = torch.randn(2, 3, 4)
model = StandardDeviationUnbiased()
self.run_test(model, x)
def test_std_keepdim(self):
class StandardDeviation(torch.nn.Module):
def forward(self, input):
return torch.std(input, dim=(0, 1), unbiased=False, keepdim=True)
x = torch.randn(2, 3, 4)
model = StandardDeviation()
self.run_test(model, x)
class StandardDeviationUnbiased(torch.nn.Module):
def forward(self, input):
return torch.std(input, dim=(0, 1), unbiased=True, keepdim=True)
x = torch.randn(2, 3, 4)
model = StandardDeviationUnbiased()
self.run_test(model, x)
def test_std_correction(self):
class StandardDeviation(torch.nn.Module):
def forward(self, input):
return torch.std(input, dim=(0, 1), correction=3, keepdim=True)
x = torch.randn(2, 3, 4)
model = StandardDeviation()
self.run_test(model, x)
def test_var(self):
class Variance(torch.nn.Module):
def forward(self, input):
return torch.var(input, unbiased=False)
x = torch.randn(2, 3, 4)
model = Variance()
self.run_test(model, x)
class VarianceUnbiased(torch.nn.Module):
def forward(self, input):
return torch.var(input, unbiased=True)
model = VarianceUnbiased()
self.run_test(model, x)
class VarianceSqrt(torch.nn.Module):
def forward(self, input):
y = torch.var(input, 1)
return torch.sqrt(y + 1e-8)
x = torch.randn(1, 2, 3, 300, 300)
model = VarianceSqrt()
self.run_test(model, x)
def test_var_along_dims(self):
class Variance(torch.nn.Module):
def forward(self, input):
return torch.var(input, dim=(0, 1), unbiased=False)
x = torch.randn(2, 3, 4)
model = Variance()
self.run_test(model, x)
class VarianceUnbiased(torch.nn.Module):
def forward(self, input):
return torch.var(input, dim=(0, 1), unbiased=True)
x = torch.randn(2, 3, 4)
model = VarianceUnbiased()
self.run_test(model, x)
def test_var_keepdim(self):
class Variance(torch.nn.Module):
def forward(self, input):
return torch.var(input, dim=(0, 1), unbiased=False, keepdim=True)
x = torch.randn(2, 3, 4)
model = Variance()
self.run_test(model, x)
class VarianceUnbiased(torch.nn.Module):
def forward(self, input):
return torch.var(input, dim=(0, 1), unbiased=True, keepdim=True)
x = torch.randn(2, 3, 4)
model = VarianceUnbiased()
self.run_test(model, x)
def test_var_correction(self):
class Variance(torch.nn.Module):
def forward(self, input):
return torch.var(input, dim=(0, 1), correction=3, keepdim=True)
x = torch.randn(2, 3, 4)
model = Variance()
self.run_test(model, x)
def test_var_mean(self):
class Variance(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, unbiased=False)
x = torch.randn(2, 3, 4)
model = Variance()
self.run_test(model, x)
class VarianceUnbiased(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, unbiased=True)
model = VarianceUnbiased()
self.run_test(model, x)
def test_var_mean_along_dims(self):
class Variance(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, dim=(0, 1), unbiased=False)
x = torch.randn(2, 3, 4)
model = Variance()
self.run_test(model, x)
class VarianceUnbiased(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, dim=(0, 1), unbiased=True)
x = torch.randn(2, 3, 4)
model = VarianceUnbiased()
self.run_test(model, x)
def test_var_mean_mixed_dims(self):
class ReverseDims(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, dim=(2, 1), unbiased=False)
x = torch.randn(2, 3, 4)
model = ReverseDims()
self.run_test(model, x)
class SkipDims(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, dim=(0, 2), unbiased=False)
x = torch.randn(2, 3, 4)
model = SkipDims()
self.run_test(model, x)
class NonZeroDims(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, dim=(1, 2), unbiased=False)
x = torch.randn(2, 3, 4)
model = NonZeroDims()
self.run_test(model, x)
def test_var_mean_keepdim(self):
class Variance(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, dim=(0, 1), unbiased=False, keepdim=True)
x = torch.randn(2, 3, 4)
model = Variance()
self.run_test(model, x)
class VarianceUnbiased(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, dim=(0, 1), unbiased=True, keepdim=True)
x = torch.randn(2, 3, 4)
model = VarianceUnbiased()
self.run_test(model, x)
def test_var_mean_correction(self):
class Variance(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, dim=(0, 1), correction=3, keepdim=True)
x = torch.randn(2, 3, 4)
model = Variance()
self.run_test(model, x)
def test_std_mean(self):
class StandardDeviation(torch.nn.Module):
def forward(self, input):
return torch.std_mean(input, unbiased=False)
x = torch.randn(2, 3, 4)
model = StandardDeviation()
self.run_test(model, x)
class StandardDeviationUnbiased(torch.nn.Module):
def forward(self, input):
return torch.std_mean(input, unbiased=True)
model = StandardDeviationUnbiased()
self.run_test(model, x)
def test_std_mean_along_dims(self):
class StandardDeviation(torch.nn.Module):
def forward(self, input):
return torch.std_mean(input, dim=(0, 1), unbiased=False)
x = torch.randn(2, 3, 4)
model = StandardDeviation()
self.run_test(model, x)
class VarianceUnbiased(torch.nn.Module):
def forward(self, input):
return torch.std_mean(input, dim=(0, 1), unbiased=True)
x = torch.randn(2, 3, 4)
model = VarianceUnbiased()
self.run_test(model, x)
def test_std_mean_keepdim(self):
class StandardDeviation(torch.nn.Module):
def forward(self, input):
return torch.std_mean(input, dim=(0, 1), unbiased=False, keepdim=True)
x = torch.randn(2, 3, 4)
model = StandardDeviation()
self.run_test(model, x)
class StandardDeviationUnbiased(torch.nn.Module):
def forward(self, input):
return torch.std_mean(input, dim=(0, 1), unbiased=True, keepdim=True)
x = torch.randn(2, 3, 4)
model = StandardDeviationUnbiased()
self.run_test(model, x)
def test_std_mean_correction(self):
class StandardDeviation(torch.nn.Module):
def forward(self, input):
return torch.var_mean(input, dim=(0, 1), correction=3, keepdim=True)
x = torch.randn(2, 3, 4)
model = StandardDeviation()
self.run_test(model, x)
def test_bitshift(self):
class BitshiftModel(torch.nn.Module):
def forward(self, input):
return (
input >> 1,
input << 3,
input >> torch.tensor([1, 2]),
input << 4,
)
input = torch.arange(24, dtype=torch.int64).reshape(3, 4, 2)
self.run_test(BitshiftModel(), input)
@skipIfUnsupportedMinOpsetVersion(18)
def test_bitwise_and(self):
class BitwiseAndModel(torch.nn.Module):
def forward(self, input, other):
return (
input & 20,
torch.bitwise_and(input, other),
other & torch.tensor([1, 2], dtype=torch.int32),
)
input = torch.randint(0, 255, (3, 4, 2), dtype=torch.uint8)
other = torch.randint(-128, 127, (3, 4, 2), dtype=torch.int8)
self.run_test(BitwiseAndModel(), (input, other))
# uint8 not implemented in ORT for Mul used in
# exporting bitshift for opset_version < 10
@skipIfUnsupportedMinOpsetVersion(11)
def test_bitshift_uint8(self):
class BitshiftModel(torch.nn.Module):
def forward(self, input, input2):
return (
input >> 1,
input << 3,
input2 >> torch.tensor([1, 2], dtype=torch.uint8),
input2 << 4,
)
input = torch.arange(24, dtype=torch.uint8).reshape(3, 4, 2)
input2 = torch.arange(24, dtype=torch.uint8).reshape(3, 4, 2)
self.run_test(BitshiftModel(), (input, input2))
def test_narrow(self):
class NarrowModel(torch.nn.Module):
def forward(self, input):
return torch.narrow(input, 0, 0, 2)
x = torch.randn(3, 3, requires_grad=True)
self.run_test(NarrowModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_narrow_dynamic(self):
class NarrowModel(torch.nn.Module):
def forward(self, input):
return torch.narrow(input, 0, 0, input.shape[0] - 1)
x = torch.randn(3, 3, requires_grad=True)
self.run_test(NarrowModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_index_fill(self):
class IndexFillModel(torch.nn.Module):
def forward(self, input):
index = torch.tensor([2, 0])
return input.index_fill(2, index, -1)
x = torch.randn(3, 4, 5, requires_grad=True)
self.run_test(IndexFillModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_index_copy(self):
class IndexCopyModel(torch.nn.Module):
def __init__(self, dim):
super().__init__()
self.dim = dim
def forward(self, input):
index = torch.tensor([2, 0])
source = torch.ones(3, 2, 5)
return input.index_copy(self.dim, index, source)
x = torch.randn(3, 4, 5, requires_grad=True)
for dim in (1, -2):
self.run_test(IndexCopyModel(dim), x)
def test_select(self):
class Select(torch.nn.Module):
def forward(self, x):
return x[:, 1]
x = torch.randn(3, 4)
self.run_test(Select(), x)
def test_select_negative_index(self):
class Select(torch.nn.Module):
def forward(self, x):
return x[:, -1]
x = torch.randn(3, 4)
self.run_test(Select(), x)
def test_index_select_constant_scaler_index(self):
class IndexSelectScalerIndexModel(torch.nn.Module):
def forward(self, x):
index = 2
return torch.index_select(x, 1, torch.tensor(index))
x = torch.randn(3, 4)
self.run_test(IndexSelectScalerIndexModel(), x)
def test_index_select_scaler_index(self):
class IndexSelectScalerIndexModel(torch.nn.Module):
def __init__(self, index_base):
super().__init__()
self.index_base = torch.tensor(index_base)
def forward(self, x, index_offset):
index = self.index_base + index_offset
return torch.index_select(x, 1, index)
x = torch.randn(3, 4)
offset = 2
index_offset = torch.tensor(offset)
base = 1
self.run_test(IndexSelectScalerIndexModel(base), (x, index_offset))
def test_take(self):
class TakeModel(torch.nn.Module):
def forward(self, x, y):
return torch.take(x, y)
x = torch.randn(6, 4, 3, 3)
y = torch.tensor([4, 1, 7, 15, 63])
self.run_test(TakeModel(), (x, y))
def test_topk(self):
class MyModule(torch.nn.Module):
def forward(self, x):
return torch.topk(x, 3)
x = torch.arange(1.0, 6.0, requires_grad=True)
self.run_test(MyModule(), x)
@skipIfUnsupportedMinOpsetVersion(10)
def test_topk_int32_k(self):
class Model(torch.nn.Module):
def forward(self, x, k):
return torch.topk(x, k)
x = torch.arange(1.0, 6.0)
k = torch.tensor(3, dtype=torch.int32)
self.run_test(Model(), (x, k))
@skipIfUnsupportedMinOpsetVersion(11)
def test_topk_smallest_unsorted(self):
class MyModule(torch.nn.Module):
def forward(self, x, k):
# When sorted=False, order of elements in the output tensors
# are not expected to match between PyTorch and ORT
topk_unsorted = torch.topk(x, k, largest=False, sorted=False)
topk_sorted = torch.topk(x, k, largest=False, sorted=True)
return topk_sorted, torch.sort(topk_unsorted.values).values
x = torch.arange(1.0, 6.0, requires_grad=True)
k = torch.tensor(3)
self.run_test(MyModule(), (x, k))
@skipIfUnsupportedMinOpsetVersion(10)
def test_topk_script(self):
class MyModuleDynamic(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x, k):
return torch.topk(x, k)
x = torch.arange(1.0, 6.0, requires_grad=True)
k = torch.tensor(3)
self.run_test(MyModuleDynamic(), (x, k))
@skipScriptTest() # Python builtin apply of FunctionMeta object is currently not supported in Torchscript.
@skipIfUnsupportedMinOpsetVersion(11) # Clip op min is an input since opset 11.
def test_auto_grad(self):
class MyClip(torch.autograd.Function):
@staticmethod
def forward(ctx, input, scalar):
ctx.save_for_backward(input)
return input.clamp(min=scalar)
class MyRelu(torch.autograd.Function):
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input)
return input.clamp(min=0)
def symbolic_python_op(g, *args, **kwargs):
name = kwargs["name"]
if name == "MyClip":
return g.op("Clip", args[0], args[1])
elif name == "MyRelu":
return g.op("Relu", args[0])
else:
# TODO(justinchuby): Remove reference to internal names in symbolic_helper
return torch.onnx.symbolic_helper._unimplemented(
"prim::PythonOp", "unknown node kind: " + name
)
torch.onnx.register_custom_op_symbolic("prim::PythonOp", symbolic_python_op, 1)
self.addCleanup(torch.onnx.unregister_custom_op_symbolic, "prim::PythonOp", 1)
class MyClipModule(torch.nn.Module):
def forward(self, x, min):
return MyClip.apply(x, min)
x = torch.randn(3, 3)
min = torch.tensor([0.0])
self.run_test(MyClipModule(), (x, min))
class MyReluModule(torch.nn.Module):
def forward(self, x):
return MyRelu.apply(x)
x = torch.randn(3, 3)
self.run_test(MyReluModule(), x)
def test_clip_int(self):
class MyClipInt(torch.nn.Module):
def forward(self, x):
return torch.clamp(x, 0, 1)
self.run_test(MyClipInt(), torch.randn(3, 3).to(torch.int64))
def test_relu_int(self):
self.run_test(torch.nn.ReLU(), torch.randn(3, 3).to(torch.int32))
def test_pad_int(self):
class MyPadInt(torch.nn.Module):
def forward(self, x):
return torch.nn.functional.pad(x, (1, 1))
self.run_test(MyPadInt(), torch.randn(3, 3).to(torch.int32))
def test_min_int(self):
class MyMinInt(torch.nn.Module):
def forward(self, x):
return torch.min(x, x + 1)
self.run_test(MyMinInt(), torch.randn(3, 3).to(torch.int32))
def test_max_int(self):
class MyMaxnInt(torch.nn.Module):
def forward(self, x):
return torch.max(x, x + 1)
self.run_test(MyMaxnInt(), torch.randn(3, 3).to(torch.int32))
@skipIfUnsupportedOpsetVersion([7])
def test_normalize(self):
class Model(torch.nn.Module):
def forward(self, x):
return torch.nn.functional.normalize(x)
x = torch.randn(3, 3)
self.run_test(Model(), x)
def test_norm_with_dtype(self):
class Model(torch.nn.Module):
def forward(self, x):
# TODO(bowbao): There is a slight gap in today's test infrastructure
# to directly test aten ops. OpInfo `torch.norm`` in `common_methods_invocations.py`
# will not decompose to below aten op.
return torch.ops.aten.norm(
x, p=2, dim=[1], keepdim=True, dtype=torch.float64
)
x = torch.randn(3, 3)
self.run_test(Model(), x)
def test_layer_norm(self):
# As layer_norm works on the last D dimension, please keep
# this test case at least three dimension to prevent the
# situation of axis=2 mapping to the same axis as axis=-2
for elementwise_affine in (True, False):
for bias in (True, False):
model = torch.nn.LayerNorm(
[10, 10, 10], elementwise_affine=elementwise_affine, bias=bias
)
x = torch.randn(20, 5, 10, 10, 10)
self.run_test(model, x)
def test_batchnorm1d(self):
x = torch.randn(10, 10)
model = torch.nn.BatchNorm1d(10, affine=True)
self.run_test(model, x)
x = torch.randn(10, 10, 128)
self.run_test(model, x)
def test_batchnorm1d_noaffine(self):
x = torch.randn(10, 10)
model = torch.nn.BatchNorm1d(10, affine=False)
self.run_test(model, x)
x = torch.randn(10, 10, 128)
self.run_test(model, x)
def test_batchnorm1d_norunningstats(self):
x = torch.randn(10, 10)
model = torch.nn.BatchNorm1d(10, track_running_stats=False)
self.run_test(model, x)
x = torch.randn(10, 10, 128)
self.run_test(model, x)
def test_batchnorm2d(self):
x = torch.randn(10, 3, 128, 128)
model = torch.nn.BatchNorm2d(3, affine=True)
self.run_test(model, x)
def test_batchnorm2d_noaffine(self):
x = torch.randn(10, 3, 128, 128)
model = torch.nn.BatchNorm2d(3, affine=False)
self.run_test(model, x)
def test_batchnorm2d_norunningstats(self):
x = torch.randn(10, 3, 128, 128)
model = torch.nn.BatchNorm2d(3, track_running_stats=False)
self.run_test(model, x)
def test_batchnorm3d(self):
x = torch.randn(10, 3, 64, 64, 64)
model = torch.nn.BatchNorm3d(3, affine=True)
self.run_test(model, x)
def test_batchnorm3d_noaffine(self):
x = torch.randn(10, 3, 64, 64, 64)
model = torch.nn.BatchNorm3d(3, affine=False)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(
9
) # Because ConstantOfShape op is not supported for opset < 9
def test_instancenorm1d_runningstats(self):
x = torch.randn(10, 5, 128)
model = torch.nn.InstanceNorm1d(5, affine=True, track_running_stats=True)
self.run_test(model, x)
model = torch.nn.InstanceNorm1d(5, affine=False, track_running_stats=True)
self.run_test(model, x)
def test_instancenorm1d_norunningstats(self):
x = torch.randn(10, 5, 128)
model = torch.nn.InstanceNorm1d(5, affine=True, track_running_stats=False)
self.run_test(model, x)
model = torch.nn.InstanceNorm1d(5, affine=False, track_running_stats=False)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(
9
) # Because ConstantOfShape op is not supported for opset < 9
def test_instancenorm2d_runningstats(self):
x = torch.randn(10, 3, 128, 128)
model = torch.nn.InstanceNorm2d(3, affine=True, track_running_stats=True)
self.run_test(model, x)
model = torch.nn.InstanceNorm2d(3, affine=False, track_running_stats=True)
self.run_test(model, x)
def test_instancenorm2d_norunningstats(self):
x = torch.randn(10, 3, 128, 128)
model = torch.nn.InstanceNorm2d(3, affine=True, track_running_stats=False)
self.run_test(model, x)
model = torch.nn.InstanceNorm2d(3, affine=False, track_running_stats=False)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(
9
) # Because ConstantOfShape op is not supported for opset < 9
def test_instancenorm3d_runningstats(self):
x = torch.randn(10, 3, 64, 64, 64)
model = torch.nn.InstanceNorm3d(3, affine=True, track_running_stats=True)
self.run_test(model, x)
model = torch.nn.InstanceNorm3d(3, affine=False, track_running_stats=True)
self.run_test(model, x)
def test_instancenorm3d_norunningstats(self):
x = torch.randn(10, 3, 64, 64, 64)
model = torch.nn.InstanceNorm3d(3, affine=True, track_running_stats=False)
self.run_test(model, x)
model = torch.nn.InstanceNorm3d(3, affine=False, track_running_stats=False)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_scatter_with_scalar(self):
class ScatterModel(torch.nn.Module):
def forward(self, input, indices):
values = 1.0
return input.scatter(1, indices, values)
input = torch.tensor(
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], dtype=torch.float64
)
indices = torch.tensor([[1, 0], [0, 1], [0, 1]], dtype=torch.int64)
self.run_test(ScatterModel(), input_args=(input, indices))
@skipIfUnsupportedMinOpsetVersion(9)
def test_scatter_with_scalar_different_types(self):
# Tests the case when scalar src (updates values) type is different
# from self type. Happens only with scalar src - PyTorch does not
# allow this when src is a tensor.
class ScatterModel(torch.nn.Module):
def forward(self, input, indices):
values = 1.0
return input.scatter(1, indices, values)
input = torch.tensor(
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], dtype=torch.float32
)
indices = torch.tensor([[1, 0], [0, 1], [0, 1]], dtype=torch.int64)
self.run_test(ScatterModel(), input_args=(input, indices))
@skipIfUnsupportedMinOpsetVersion(9)
def test_scatter(self):
class ScatterModel(torch.nn.Module):
def forward(self, input, indices, values):
return input.scatter(1, indices, values)
input = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
indices = torch.tensor([[1, 0], [0, 1], [0, 1]], dtype=torch.int64)
values = torch.tensor([[1.0, 1.1], [2.0, 2.1], [3.0, 3.1]])
self.run_test(ScatterModel(), input_args=(input, indices, values))
input = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
indices = torch.tensor([[1, 0], [0, 2], [0, 1]], dtype=torch.int64)
values = torch.tensor([[1.0, 1.1], [2.0, 2.1], [3.0, 3.1]])
self.run_test(ScatterModel(), (input, indices, values))
input = torch.zeros(3, 4, 5, 6)
indices = torch.tensor([[1, 0], [0, 2], [0, 1]], dtype=torch.int64)
indices = indices.view(3, 2, 1, 1).expand(3, 2, 5, 6)
values = torch.arange(3 * 2 * 5 * 6, dtype=torch.float32).view(3, 2, 5, 6)
self.run_test(ScatterModel(), (input, indices, values))
input = torch.zeros(3, 4, 2)
indices = torch.tensor([[[1, 0], [0, 2]], [[1, 1], [0, 1]], [[2, 1], [2, 2]]])
values = torch.arange(3 * 2 * 2, dtype=torch.float32).view(3, 2, 2)
self.run_test(ScatterModel(), (input, indices, values))
@skipIfUnsupportedMinOpsetVersion(9)
def test_scatter_add(self):
class ScatterModel(torch.nn.Module):
def forward(self, input, indices, values):
return input.scatter_add(1, indices, values)
input = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
indices = torch.tensor([[1, 0], [0, 1], [0, 1]], dtype=torch.int64)
values = torch.tensor([[1.0, 1.1], [2.0, 2.1], [3.0, 3.1]])
self.run_test(ScatterModel(), input_args=(input, indices, values))
@torch.jit.script
def scatter_sum(src: Tensor, index: Tensor):
size = src.size()
out = torch.zeros(size, dtype=src.dtype)
return out.scatter_add_(1, index, src)
class ScatterModel(torch.nn.Module):
def forward(self, src, index):
return scatter_sum(src, index)
src = torch.rand(3, 2)
index = torch.tensor([[0, 1], [0, 1], [0, 1]], dtype=torch.int64)
self.run_test(ScatterModel(), (src, index))
@skipIfUnsupportedMinOpsetVersion(16)
def test_scatter_add_index_not_unique(self):
class ScatterModel(torch.nn.Module):
def forward(self, input, indices, values):
return input.scatter_add(1, indices, values)
input = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
indices = torch.tensor([[0, 0], [1, 1], [2, 2]], dtype=torch.int64)
values = torch.tensor([[1.0, 1.1], [2.0, 2.1], [3.0, 3.1]])
self.run_test(ScatterModel(), input_args=(input, indices, values))
@torch.jit.script
def scatter_sum(src: Tensor, index: Tensor):
size = src.size()
out = torch.zeros(size, dtype=src.dtype)
return out.scatter_add_(1, index, src)
class ScatterModel(torch.nn.Module):
def forward(self, src, index):
return scatter_sum(src, index)
src = torch.rand(3, 2)
index = torch.tensor([[0, 0], [1, 1], [0, 1]], dtype=torch.int64)
self.run_test(ScatterModel(), (src, index))
@skipIfUnsupportedMinOpsetVersion(16)
def test_scatter_add_different_size_index_src(self):
class ScatterModel(torch.nn.Module):
def forward(self, input, indices, src):
return input.scatter_add(0, indices, src)
src = torch.ones((2, 5))
input = torch.zeros(3, 5, dtype=src.dtype)
indices = torch.tensor([[0, 1, 2, 0, 0]])
self.run_test(ScatterModel(), input_args=(input, indices, src))
@common_utils.parametrize(
"src, indices",
[
common_utils.subtest(
[torch.ones((1, 5)), torch.tensor([[0, 1, 2, 0, 0]])],
name="src_indices_dynamic_combination1",
),
common_utils.subtest(
[torch.ones((2, 5)), torch.tensor([[0, 1, 2, 0, 0], [1, 0, 2, 1, 2]])],
name="src_indices_dynamic_combination2",
),
common_utils.subtest(
[torch.ones((3, 5)), torch.tensor([[0, 1, 2, 0, 0], [1, 0, 2, 1, 2]])],
name="src_indices_dynamic_combination3",
),
common_utils.subtest(
[torch.ones((3, 5)), torch.tensor([[0, 1, 2, 0], [1, 0, 2, 1]])],
name="src_indices_dynamic_combination4",
),
],
)
@skipIfUnsupportedMinOpsetVersion(16)
def test_scatter_add_dynamic_index(self, src, indices):
class ScatterModel(torch.nn.Module):
def forward(self, input, indices, src):
return input.scatter_add(0, indices, src)
input = torch.zeros(3, 5, dtype=src.dtype)
self.run_test(
ScatterModel(),
input_args=(input, indices, src),
input_names=["input", "indices", "src"],
dynamic_axes={"indices": {0: "a", 1: "b"}, "src": {0: "c", 1: "d"}},
)
@skipIfUnsupportedMinOpsetVersion(16)
def test_scatter_reduce(self):
class Model(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
def forward(self, x, index, input):
y_max = input.scatter_reduce(0, index, x, reduce="amax")
y_sum = input.scatter_reduce(0, index, x, reduce="sum")
y_min = input.scatter_reduce(0, index, x, reduce="amin")
y_mul = input.scatter_reduce(0, index, x, reduce="prod")
return y_max, y_sum, y_min, y_mul
model = Model()
model.eval()
src = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
index = torch.tensor([0, 1, 0, 1, 2, 1])
input = torch.tensor([1.0, 2.0, 3.0, 8.0])
self.run_test(model, (src, index, input))
@skipIfUnsupportedMinOpsetVersion(16)
def test_scatter_reduce_self_rank_zero(self):
class Model(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
def forward(self, x, index, input):
y_max = input.scatter_reduce(0, index, x, reduce="amax")
y_sum = input.scatter_reduce(0, index, x, reduce="sum")
y_min = input.scatter_reduce(0, index, x, reduce="amin")
y_mul = input.scatter_reduce(0, index, x, reduce="prod")
return y_max, y_sum, y_min, y_mul
model = Model()
model.eval()
empty_tensor = torch.tensor([])
empty_idx = torch.tensor([], dtype=torch.int64)
self.run_test(model, (empty_tensor, empty_idx, empty_tensor))
@skipIfUnsupportedMinOpsetVersion(9)
def test_bucketize(self):
class BucketModel(torch.nn.Module):
def forward(self, input, boundaries):
return torch.bucketize(input, boundaries), torch.bucketize(
input, boundaries, right=True
)
input = torch.tensor([[2, 5, 10], [6, 8, 3]])
boundaries = torch.tensor([1, 5, 7, 8, 10])
self.run_test(BucketModel(), (input, boundaries))
@skipIfUnsupportedMinOpsetVersion(9)
def test_one_hot(self):
class OneHot(torch.nn.Module):
def __init__(self, num_classes):
super().__init__()
self.num_classes = num_classes
def forward(self, x):
return torch.nn.functional.one_hot(x, self.num_classes)
x = torch.arange(10)
self.run_test(OneHot(15), (x))
class OneHot(torch.nn.Module):
def forward(self, x, num_classes):
num_classes = num_classes.to(torch.int32)
return torch.nn.functional.one_hot(x, num_classes[0])
x = torch.arange(10)
num_classes = 15 * torch.ones(1)
self.run_test(OneHot(), (x, num_classes))
@skipIfUnsupportedMinOpsetVersion(9)
def test_gather(self):
class GatherModel(torch.nn.Module):
def forward(self, input, indices):
return input.gather(1, indices)
input = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]])
indices = torch.tensor([[1, 0], [0, 1], [0, 1]], dtype=torch.int64)
self.run_test(GatherModel(), input_args=(input, indices))
@skipScriptTest() # Scripting error: Cannot instantiate nn module
def test_gather_constant_fold(self):
class GatherModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.weight = torch.nn.Buffer(torch.ones(5))
# torch.nn.Embedding is converted to ONNX::Gather.
# Constant folding will be triggered for constant inputs.
# This pattern is common for constant mask inputs in transformer models.
self.embed = torch.nn.Embedding(8, 3)
def forward(self, x):
# shape is of rank 0
shape = self.weight.shape[0]
m = 5 - shape
y = torch.ones(1, 4, dtype=torch.long)
return x.clamp(min=m), self.embed(y)
x = torch.randn(1)
self.run_test(GatherModule(), (x,))
class GatherModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.weight = torch.nn.Buffer(torch.ones(2))
def forward(self, x):
# shape is of rank 0
shape = self.weight.shape[0]
pad = [1, shape, shape, shape]
zero_pad = torch.nn.ZeroPad2d(pad)
return zero_pad(x)
x = torch.randn(1, 3, 2)
self.run_test(GatherModule(), (x,))
class GatherModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.rb = torch.nn.Buffer(torch.randn(1, 1, 3, 1, 1))
def forward(self, x):
x += self.rb[0]
return x
x = torch.randn(1, 3, 224, 224)
self.run_test(
GatherModule(),
(x,),
dynamic_axes={
"input": {0: "batch", 2: "height", 3: "width"},
"output": {0: "batch", 1: "class", 2: "height", 3: "width"},
},
input_names=["input"],
output_names=["output"],
)
@skipIfUnsupportedOpsetVersion([13])
@skipIfUnsupportedMinOpsetVersion(9)
def test_expand(self):
class ExpandModel(torch.nn.Module):
def forward(self, input):
return input.expand(2, 3, -1)
input = torch.randn(2, 1, 4)
self.run_test(ExpandModel(), input_args=(input))
class ExpandInferDimModel(torch.nn.Module):
def forward(self, input):
return input.expand(-1, input.size(0))
input = torch.randn(3, 1)
self.run_test(ExpandInferDimModel(), input_args=(input))
class ExpandTensorSizeModel(torch.nn.Module):
def forward(self, input, size):
return input.expand(size)
input = torch.randn(
3,
)
size = torch.tensor(-1)
self.run_test(ExpandTensorSizeModel(), input_args=(input, size))
@skipIfUnsupportedMinOpsetVersion(11) # index_put is supported in opsets >= 11
def test_dynamic_expand_as(self):
class Model(torch.nn.Module):
def forward(self, x):
x[:, x.size(0) :] = 0
return x
x = torch.ones(2, 5)
x2 = torch.randn(3, 4)
self.run_test(
Model(),
(x,),
input_names=["x"],
dynamic_axes={"x": [0, 1]},
additional_test_inputs=[x2],
)
class Model(torch.nn.Module):
def forward(self, x):
x[:, x.size(0) :] = torch.tensor([1, 2, 3])
return x
x = torch.ones(2, 5, 3)
x2 = torch.randn(3, 4, 3)
self.run_test(
Model(),
(x,),
input_names=["x"],
dynamic_axes={"x": [0, 1, 2]},
additional_test_inputs=[x2],
)
class Model(torch.nn.Module):
def forward(self, x):
aa = torch.tensor([[0], [1], [2]])
return aa.expand_as(x)
x = torch.ones(3, 2)
x2 = torch.randn(3, 5)
self.run_test(
Model(),
(x,),
input_names=["x"],
dynamic_axes={"x": [0, 1]},
additional_test_inputs=[x2],
)
def test_multinomial(self):
class Multinomial(torch.nn.Module):
def forward(self, weight):
return torch.multinomial(weight, 3, replacement=True)
class MultinomialNoReplacement(torch.nn.Module):
def forward(self, weight):
return torch.multinomial(weight, 1)
weight = torch.tensor([[0, 10, 0, 0], [0, 0, 100, 0]], dtype=torch.float)
self.run_test(Multinomial(), (weight,))
self.run_test(MultinomialNoReplacement(), (weight,))
def _test_reduced_ops(self, op):
class ReducedOpModule(torch.nn.Module):
def forward(self, input):
return op(input, dim=-1)
if op != torch.mean: # torch.mean only supports float types
x = torch.randint(10, (4, 4), dtype=torch.uint8)
self.run_test(ReducedOpModule(), x)
x = torch.randint(10, (4, 4), dtype=torch.int8)
self.run_test(ReducedOpModule(), x)
x = torch.randint(10, (4, 4), dtype=torch.int16)
self.run_test(ReducedOpModule(), x)
x = torch.randint(10, (4, 4), dtype=torch.int32)
self.run_test(ReducedOpModule(), x)
x = torch.randint(10, (4, 4), dtype=torch.int64)
self.run_test(ReducedOpModule(), x)
# torch.mean only supports float types
# ORT does not support double ReduceProd for double
if op != torch.prod and op != torch.mean:
x = torch.randn(4, 5, dtype=torch.double)
self.run_test(ReducedOpModule(), x)
if op != torch.prod: # torch.prod not implemented for Half
x = torch.randn(4, 4, dtype=torch.half)
self.run_test(ReducedOpModule(), x)
x = torch.randn(4, 5, dtype=torch.float)
self.run_test(ReducedOpModule(), x)
def test_reduced_sum(self):
return self._test_reduced_ops(op=torch.sum)
def test_reduced_mean(self):
return self._test_reduced_ops(op=torch.mean)
def test_reduced_prod(self):
return self._test_reduced_ops(op=torch.prod)
def test_reduced_sum_dtypes(self):
class NoDimModel(torch.nn.Module):
def forward(self, input):
return input.sum(dtype=torch.float)
class DimModel(torch.nn.Module):
def forward(self, input):
return input.sum(dim=-1, dtype=torch.float)
input = torch.randn((4, 4), dtype=torch.half)
self.run_test(NoDimModel(), input)
self.run_test(DimModel(), input)
def test_reduced_min_max(self):
class ReducedMinMaxModule(torch.nn.Module):
def forward(self, input):
return torch.min(input, dim=-1)[0], torch.max(input, dim=0)[0]
x = torch.randint(10, (4, 4), dtype=torch.int32)
self.run_test(ReducedMinMaxModule(), x)
x = torch.randint(10, (4, 4), dtype=torch.int64)
self.run_test(ReducedMinMaxModule(), x)
x = torch.randn(4, 5, dtype=torch.float)
self.run_test(ReducedMinMaxModule(), x)
def test_reduce_log_sum_exp(self):
class ReduceLogSumExpModel(torch.nn.Module):
def forward(self, input):
a = torch.logsumexp(input, dim=0)
b = torch.logsumexp(input, dim=(0, 1))
return a + b
x = torch.randn(4, 4, requires_grad=True)
self.run_test(ReduceLogSumExpModel(), x)
def test_softmax(self):
for i in range(-4, 3):
model = torch.nn.Softmax(dim=i)
input = torch.randn(3, 4, 5, 6)
self.run_test(model, input)
class SoftmaxUnknownRank(torch.nn.Module):
def __init__(self, i):
super().__init__()
self.softmax = torch.nn.Softmax(dim=i)
def forward(self, x):
return self.softmax(x.reshape(3, 4, 5, 6))
model = torch.jit.script(SoftmaxUnknownRank(i))
self.run_test(model, input)
def test_softmax_large_values(self):
input = torch.tensor(
[[-1e12, -1e12, -1e12], [1e12, 0.0, -5.0], [3.0, 4.0, 5.0]]
)
for i in range(-2, 1):
model = torch.nn.Softmax(dim=i)
self.run_test(model, input)
class SoftmaxUnknownRank(torch.nn.Module):
def __init__(self, i):
super().__init__()
self.softmax = torch.nn.Softmax(dim=i)
def forward(self, x):
return self.softmax(x.reshape(3, 3))
model = torch.jit.script(SoftmaxUnknownRank(i))
self.run_test(model, input)
def test_logsoftmax(self):
for i in range(7)[2:]:
model = torch.nn.LogSoftmax(dim=i - 1)
dims = [2] * (i - 2) + [3, 4]
input = torch.ones(*dims, requires_grad=True)
self.run_test(model, input)
def test_logsoftmax_dim(self):
for i in range(-4, 3):
model = torch.nn.LogSoftmax(dim=i)
input = torch.randn(3, 4, 5, 6)
self.run_test(model, input)
def test_logsoftmax_dtype(self):
class Model(torch.nn.Module):
def forward(self, x):
return torch.nn.functional.log_softmax(x, dim=1, dtype=torch.float64)
x = torch.randn(3, 4, 5, requires_grad=True)
self.run_test(Model(), x)
def test_softplus(self):
class BetaOneModel(torch.nn.Module):
def forward(self, x):
return torch.nn.functional.softplus(x)
x = torch.randn(3, 4, 5, requires_grad=True)
self.run_test(BetaOneModel(), x)
class BetaModel(torch.nn.Module):
def forward(self, x):
return torch.nn.functional.softplus(x, beta=2)
x = torch.randn(3, 4, 5, requires_grad=True)
self.run_test(BetaModel(), x)
class BetaFloatModel(torch.nn.Module):
def forward(self, x):
return torch.nn.functional.softplus(x, beta=1.7)
x = torch.randn(3, 4, 5, requires_grad=True)
self.run_test(BetaFloatModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_lstm_no_hidden(self):
class LSTMModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.rnn = torch.nn.LSTM(input_size=16, hidden_size=16)
def forward(self, x):
return self.rnn(x)
input = torch.randn((10, 16, 16))
self.run_test(LSTMModel(), (input,))
@skipIfUnsupportedMinOpsetVersion(9)
def test_lstm_proj_no_hidden(self):
class LSTMModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.rnn = torch.nn.LSTM(input_size=16, hidden_size=16, proj_size=8)
def forward(self, x):
return self.rnn(x)
input = torch.randn((10, 16, 16))
with self.assertRaises(RuntimeError):
self.run_test(LSTMModel(), (input,))
@skipIfUnsupportedMinOpsetVersion(9)
def test_lstm(self):
class LSTMModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.rnn = torch.nn.LSTM(
RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, 1, bidirectional=False
)
def forward(self, x, h0, c0):
return self.rnn(x, (h0, c0))
input = torch.randn(RNN_SEQUENCE_LENGTH, BATCH_SIZE, RNN_INPUT_SIZE)
h0 = torch.randn(1, BATCH_SIZE, RNN_HIDDEN_SIZE)
c0 = torch.randn(1, BATCH_SIZE, RNN_HIDDEN_SIZE)
self.run_test(LSTMModel(), (input, h0, c0))
@skipIfUnsupportedMinOpsetVersion(9)
def test_lstm_cell(self):
class LSTMCellModel(torch.nn.Module):
def __init__(self, bias):
super().__init__()
self.lstm_cell = torch.nn.LSTMCell(
RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, bias=bias
)
def forward(self, x, h0, c0):
return self.lstm_cell(x, (h0, c0))
input = torch.randn(BATCH_SIZE, RNN_INPUT_SIZE)
h0 = torch.randn(BATCH_SIZE, RNN_HIDDEN_SIZE)
c0 = torch.randn(BATCH_SIZE, RNN_HIDDEN_SIZE)
for bias in [True, False]:
self.run_test(LSTMCellModel(bias), (input, h0, c0))
@skipIfUnsupportedMinOpsetVersion(9)
def test_lstm_default_init_state(self):
class LSTMModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.rnn = torch.nn.LSTM(
RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, 1, bidirectional=False
)
def forward(self, x):
return self.rnn(x)
input = torch.randn(RNN_SEQUENCE_LENGTH, BATCH_SIZE, RNN_INPUT_SIZE)
self.run_test(LSTMModel(), input)
@skipIfUnsupportedMinOpsetVersion(9)
def test_lstm_fixed_batch_size(self):
class LSTMModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.lstm = torch.nn.LSTM(
RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, 1, bidirectional=False
)
self.RNN_HIDDEN_SIZE = RNN_HIDDEN_SIZE
def forward(self, input):
batch_size = input.size()[1]
h0 = torch.ones([1, batch_size, self.RNN_HIDDEN_SIZE])
c0 = torch.ones([1, batch_size, self.RNN_HIDDEN_SIZE])
return self.lstm(input, (h0, c0))
input = torch.randn(RNN_SEQUENCE_LENGTH, BATCH_SIZE, RNN_INPUT_SIZE)
# verify with different input of same batch size
input2 = torch.randn(RNN_SEQUENCE_LENGTH, BATCH_SIZE, RNN_INPUT_SIZE)
self.run_test(
LSTMModel(), input, fixed_batch_size=True, additional_test_inputs=[input2]
)
@skipIfUnsupportedMinOpsetVersion(9)
def test_lstm_post_fix_init_state(self):
class LSTMModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.lstm = torch.nn.LSTM(
RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, 1, bidirectional=False
)
self.RNN_HIDDEN_SIZE = RNN_HIDDEN_SIZE
def forward(self, input):
batch_size = input.size()[1]
h0 = torch.ones([1, batch_size, self.RNN_HIDDEN_SIZE])
c0 = torch.ones([1, batch_size, self.RNN_HIDDEN_SIZE])
return self.lstm(input, (h0, c0))
model = LSTMModel()
input = torch.randn(RNN_SEQUENCE_LENGTH, 1, RNN_INPUT_SIZE)
# verify with different input of different batch size
input2 = torch.randn(RNN_SEQUENCE_LENGTH, BATCH_SIZE, RNN_INPUT_SIZE)
self.run_test(
model,
input,
input_names=["input.1"],
dynamic_axes={"input.1": {0: "seq", 1: "batch"}},
additional_test_inputs=[input2],
)
def test_lstm_constant_folding(self):
class LstmNet(torch.nn.Module):
def __init__(self, input_size, hidden_size, num_layers, bidirectional):
super().__init__()
self.lstm = torch.nn.LSTM(
input_size, hidden_size, num_layers, bidirectional=bidirectional
)
def forward(self, input, initial_state: tuple[Tensor, Tensor]):
return self.lstm(input, initial_state)
def get_LstmNet_model_and_inputs(
input_size, hidden_size, num_layers, batch_size, seq_len, bidirectional
):
num_directions = 2 if bidirectional else 1
model = LstmNet(input_size, hidden_size, num_layers, bidirectional)
input = torch.randn(seq_len, batch_size, input_size)
h0 = torch.randn(num_layers * num_directions, batch_size, hidden_size)
c0 = torch.randn(num_layers * num_directions, batch_size, hidden_size)
return model, (input, (h0, c0))
batch_size1 = 3
model1, input1 = get_LstmNet_model_and_inputs(7, 3, 2, batch_size1, 5, True)
self.run_test(model1, input1, do_constant_folding=True)
batch_size2 = 4
model2, input2 = get_LstmNet_model_and_inputs(5, 4, 3, batch_size2, 7, False)
self.run_test(model2, input2, do_constant_folding=True)
@skipIfUnsupportedMinOpsetVersion(9)
def test_lstm_no_bias(self):
class LstmNet(torch.nn.Module):
def __init__(self, num_layers, bidirectional):
super().__init__()
self.lstm = torch.nn.LSTM(
RNN_INPUT_SIZE,
RNN_HIDDEN_SIZE,
num_layers,
bias=False,
bidirectional=bidirectional,
)
def forward(self, input, initial_state: tuple[Tensor, Tensor]):
return self.lstm(input, initial_state)
def get_LstmNet_model_and_inputs(num_layers, bidirectional):
input = torch.randn(RNN_SEQUENCE_LENGTH, BATCH_SIZE, RNN_INPUT_SIZE)
num_directions = 2 if bidirectional else 1
model = LstmNet(num_layers, bidirectional)
h0 = torch.randn(num_layers * num_directions, BATCH_SIZE, RNN_HIDDEN_SIZE)
c0 = torch.randn(num_layers * num_directions, BATCH_SIZE, RNN_HIDDEN_SIZE)
return model, (input, (h0, c0))
num_layers = [1, 1, 2, 3]
bidirectional = [True, False, True, False]
models_and_inputs = [
get_LstmNet_model_and_inputs(n, b)
for n, b in zip(num_layers, bidirectional)
]
for model, input in models_and_inputs:
self.run_test(model, input)
@skipIfUnsupportedMinOpsetVersion(9)
def test_lstm_sequence(self):
class LstmNet(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.rnn1 = torch.nn.LSTM(8, 8, bidirectional=True, batch_first=True)
self.linear1 = torch.nn.Linear(8 * 2, 8)
self.rnn2 = torch.nn.LSTM(8, 8, bidirectional=True, batch_first=True)
self.linear2 = torch.nn.Linear(8 * 2, 8)
def forward(self, input):
rnn_output1, _ = self.rnn1(input)
linear_output1 = self.linear1(rnn_output1)
rnn_output2, _ = self.rnn2(linear_output1)
linear_output2 = self.linear2(rnn_output2)
return linear_output2
input = torch.zeros((1, 100, 8), dtype=torch.float32)
self.run_test(
LstmNet(),
input,
input_names=["input"],
output_names=["output"],
dynamic_axes={
"input": {0: "batch_size", 1: "w", 2: "h"},
"output": {0: "batch_size", 1: "w", 2: "h"},
},
)
@skipScriptTest()
def test_rnn_no_bias(self):
def make_model(layers, packed_sequence):
batch_first = packed_sequence == 2
model = torch.nn.RNN(
RNN_INPUT_SIZE,
RNN_HIDDEN_SIZE,
layers,
bidirectional=False,
batch_first=batch_first,
bias=False,
)
if packed_sequence == 1:
model = rnn_model_with_packed_sequence.RnnModelWithPackedSequence(
model, False
)
if packed_sequence == 2:
model = rnn_model_with_packed_sequence.RnnModelWithPackedSequence(
model, True
)
return model
def make_input(batch_size, layers, packed_sequence):
batch_first = packed_sequence == 2
seq_lengths = np.random.randint(1, RNN_SEQUENCE_LENGTH + 1, size=batch_size)
seq_lengths = sorted(map(int, seq_lengths), reverse=True)
inputs = [torch.randn(l, RNN_INPUT_SIZE) for l in seq_lengths]
inputs = rnn_utils.pad_sequence(inputs, batch_first=batch_first)
inputs = [inputs]
h0 = torch.randn(layers, batch_size, RNN_HIDDEN_SIZE)
inputs.append(h0)
if packed_sequence != 0:
inputs.append(torch.IntTensor(seq_lengths))
if len(inputs) == 1:
input = inputs[0]
else:
input = tuple(inputs)
return input
layers = [1, 3, 1, 3, 1, 3]
packed_sequence = [0, 0, 1, 1, 2, 2]
models = [make_model(l, p) for l, p in zip(layers, packed_sequence)]
inputs = [
make_input(RNN_BATCH_SIZE, l, p) for l, p in zip(layers, packed_sequence)
]
for model, input in zip(models, inputs):
self.run_test(model, input)
def test_gru_no_bias(self):
class GruNet(torch.nn.Module):
def __init__(self, input_size, hidden_size, num_layers, bidirectional):
super().__init__()
self.mygru = torch.nn.GRU(
input_size,
hidden_size,
num_layers,
bidirectional=bidirectional,
bias=False,
)
def forward(self, input, initial_state):
out = self.mygru(input, initial_state)
return out
def get_GruNet_model_and_inputs(
input_size, hidden_size, num_layers, batch_size, seq_len, bidirectional
):
num_directions = 2 if bidirectional else 1
model = GruNet(input_size, hidden_size, num_layers, bidirectional)
input = torch.randn(seq_len, batch_size, input_size)
h0 = torch.randn(num_layers * num_directions, batch_size, hidden_size)
return model, (input, h0)
input_size = [7, 5]
hidden_size = [3, 4]
num_layers = [2, 3]
batch_size = [3, 4]
seq_len = [5, 7]
bidirectional = [True, False]
models_and_inputs = [
get_GruNet_model_and_inputs(i, h, n, b, s, bi)
for i, h, n, b, s, bi in zip(
input_size, hidden_size, num_layers, batch_size, seq_len, bidirectional
)
]
for model, input in models_and_inputs:
self.run_test(model, input, do_constant_folding=True)
def test_gru_constant_folding(self):
class GruNet(torch.nn.Module):
def __init__(self, input_size, hidden_size, num_layers, bidirectional):
super().__init__()
self.mygru = torch.nn.GRU(
input_size, hidden_size, num_layers, bidirectional=bidirectional
)
def forward(self, input, initial_state):
out = self.mygru(input, initial_state)
return out
def get_GruNet_model_and_inputs(
input_size, hidden_size, num_layers, batch_size, seq_len, bidirectional
):
num_directions = 2 if bidirectional else 1
model = GruNet(input_size, hidden_size, num_layers, bidirectional)
input = torch.randn(seq_len, batch_size, input_size)
h0 = torch.randn(num_layers * num_directions, batch_size, hidden_size)
return model, (input, h0)
batch_size1 = 3
model1, input1 = get_GruNet_model_and_inputs(7, 3, 2, batch_size1, 5, True)
self.run_test(model1, input1, do_constant_folding=True)
batch_size2 = 4
model2, input2 = get_GruNet_model_and_inputs(5, 4, 3, batch_size2, 7, False)
self.run_test(model2, input2, do_constant_folding=True)
@skipIfUnsupportedMinOpsetVersion(8)
def test_max_tensors(self):
class MaxModel(torch.nn.Module):
def forward(self, input, other):
return torch.max(input, other)
model = MaxModel()
x = torch.randn(4, 4, requires_grad=True)
y = torch.randn(4, 1, requires_grad=True)
self.run_test(model, (x, y))
def test_amax_amin(self):
class Model(torch.nn.Module):
def forward(self, x):
return torch.amax(x, dim=0, keepdim=True), torch.amin(
x, dim=[0, 1], keepdim=False
)
model = Model()
x = torch.randn(4, 4)
self.run_test(model, x)
def test_aminmax(self):
class Model(torch.nn.Module):
def forward(self, x):
return torch.aminmax(x, dim=1, keepdim=True), torch.aminmax(
x, keepdim=False
)
model = Model()
x = torch.randn(3, 4)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_arange_end(self):
class ArangeScript(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, a):
return torch.arange(a.size(0), dtype=torch.float).view(-1, 1) + a
x = torch.randn(3, 4, requires_grad=True)
outputs = ArangeScript()(x)
self.run_test(ArangeScript(), x)
class ArangeModel(torch.nn.Module):
def forward(self, a):
return torch.arange(a.size(0), dtype=torch.float).view(-1, 1) + a
self.run_test(ArangeModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_arange_end_notype(self):
class ArangeScript(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, a):
return torch.arange(a.size(0))
x = torch.randn(3, 4, requires_grad=True)
outputs = ArangeScript()(x)
self.run_test(ArangeScript(), x, input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(ArangeScript(), x, remained_onnx_input_idx=[])
class ArangeModel(torch.nn.Module):
def forward(self, a):
return torch.arange(a.size(0))
self.run_test(ArangeModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(ArangeModel(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_arange_start_end(self):
class ArangeScript(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, a):
return torch.arange(2, a.size(0) + 2, dtype=torch.float).view(-1, 1) + a
x = torch.randn(3, 4, requires_grad=True)
self.run_test(ArangeScript(), x)
class ArangeModel(torch.nn.Module):
def forward(self, a):
return torch.arange(2, a.size(0) + 2, dtype=torch.float).view(-1, 1) + a
self.run_test(ArangeModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_arange_start_end_notype(self):
class ArangeScript(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, a):
return torch.arange(2.7, a.size(0) + 2).view(-1, 1) + a
x = torch.randn(3, 4, requires_grad=True)
self.run_test(ArangeScript(), x)
class ArangeModel(torch.nn.Module):
def forward(self, a):
return torch.arange(2.7, a.size(0) + 2).view(-1, 1) + a
self.run_test(ArangeModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_arange_start_end_step(self):
class ArangeScript(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, a):
return (
torch.arange(
2, a.size(0) * a.size(1) + 2, a.size(1), dtype=torch.float
).view(-1, 1)
+ a
)
x = torch.randn(3, 4, requires_grad=True)
self.run_test(ArangeScript(), x)
class ArangeModel(torch.nn.Module):
def forward(self, a):
return (
torch.arange(
2, a.size(0) * a.size(1) + 2, a.size(1), dtype=torch.float
).view(-1, 1)
+ a
)
self.run_test(ArangeModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_arange_start_end_step_notype(self):
class ArangeScript(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, a):
return (
torch.arange(2.7, a.size(0) * a.size(1) + 2, a.size(1)).view(-1, 1)
+ a
)
x = torch.randn(3, 4, requires_grad=True)
self.run_test(ArangeScript(), x)
class ArangeModel(torch.nn.Module):
def forward(self, a):
return (
torch.arange(2.7, a.size(0) * a.size(1) + 2, a.size(1)).view(-1, 1)
+ a
)
self.run_test(ArangeModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test__dim_arange(self):
class DimArange(torch.nn.Module):
def forward(self, input):
return torch._dim_arange(input, 1)
x = torch.ones(5, 6)
self.run_test(DimArange(), x, input_names=["x"], dynamic_axes={"x": [0, 1]})
remained_onnx_input_idx = None if self.opset_version < 11 else []
self.run_test(DimArange(), x, remained_onnx_input_idx=remained_onnx_input_idx)
def _test_compare_ops(self, model, num_inputs):
x_float = torch.randn(1, 2, 3, 4, requires_grad=True)
x_int = torch.randint(10, (3, 4), dtype=torch.int32)
if num_inputs > 1:
y_float = torch.randn(1, 2, 3, 4, requires_grad=True)
y_int = torch.randint(10, (3, 4), dtype=torch.int32)
self.run_test(model, (x_float, y_float))
self.run_test(model, (x_float, y_int))
self.run_test(model, (x_int, y_float))
self.run_test(model, (x_int, y_int))
else:
self.run_test(model, x_float)
self.run_test(model, x_int)
@skipIfUnsupportedMinOpsetVersion(9)
def test_and_or_xor(self):
class MyModel(torch.nn.Module):
def forward(self, x, y):
return x ^ y, x | y, x & y, ~x
x = torch.randint(0, 2, (5, 5), dtype=torch.bool)
y = torch.randint(0, 2, (5, 5), dtype=torch.bool)
self.run_test(MyModel(), input_args=(x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_logical_and(self):
class AndModel(torch.nn.Module):
def forward(self, x, y):
return torch.logical_and(x, y)
x = torch.randint(0, 2, (5, 5), dtype=torch.bool)
y = torch.randint(0, 2, (5, 5), dtype=torch.bool)
self.run_test(AndModel(), input_args=(x, y))
x = torch.randint(10, (5, 5), dtype=torch.int32)
y = torch.randint(10, (5, 5), dtype=torch.int32)
self.run_test(AndModel(), input_args=(x, y))
x = torch.randint(10, (5, 5), dtype=torch.double)
y = torch.randint(10, (5, 5), dtype=torch.double)
self.run_test(AndModel(), input_args=(x, y))
x = torch.randint(10, (2, 3, 5), dtype=torch.float32)
y = torch.randint(10, (2, 3, 5), dtype=torch.long)
self.run_test(AndModel(), input_args=(x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_logical_or(self):
class OrModel(torch.nn.Module):
def forward(self, x, y):
return torch.logical_or(x, y)
x = torch.randint(0, 2, (5, 5), dtype=torch.bool)
y = torch.randint(0, 2, (5, 5), dtype=torch.bool)
self.run_test(OrModel(), input_args=(x, y))
x = torch.randint(10, (5, 5), dtype=torch.int32)
y = torch.randint(10, (5, 5), dtype=torch.int32)
self.run_test(OrModel(), input_args=(x, y))
x = torch.randint(10, (5, 5), dtype=torch.double)
y = torch.randint(10, (5, 5), dtype=torch.double)
self.run_test(OrModel(), input_args=(x, y))
x = torch.randint(10, (2, 3, 5), dtype=torch.float32)
y = torch.randint(10, (2, 3, 5), dtype=torch.long)
self.run_test(OrModel(), input_args=(x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_logical_xor(self):
class XorModel(torch.nn.Module):
def forward(self, x, y):
return torch.logical_xor(x, y)
x = torch.randint(0, 2, (5, 5), dtype=torch.bool)
y = torch.randint(0, 2, (5, 5), dtype=torch.bool)
self.run_test(XorModel(), input_args=(x, y))
x = torch.randint(10, (5, 5), dtype=torch.int32)
y = torch.randint(10, (5, 5), dtype=torch.int32)
self.run_test(XorModel(), input_args=(x, y))
x = torch.randint(10, (5, 5), dtype=torch.double)
y = torch.randint(10, (5, 5), dtype=torch.double)
self.run_test(XorModel(), input_args=(x, y))
x = torch.randint(10, (2, 3, 5), dtype=torch.float32)
y = torch.randint(10, (2, 3, 5), dtype=torch.long)
self.run_test(XorModel(), input_args=(x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_logical_not(self):
class NotModel(torch.nn.Module):
def forward(self, x):
return torch.logical_not(x)
x = torch.randint(0, 2, (5, 5), dtype=torch.bool)
self.run_test(NotModel(), input_args=(x,))
x = torch.randint(10, (5, 5), dtype=torch.int32)
self.run_test(NotModel(), input_args=(x,))
x = torch.randint(10, (5, 5), dtype=torch.double)
self.run_test(NotModel(), input_args=(x,))
x = torch.randint(10, (2, 3, 5), dtype=torch.float32)
self.run_test(NotModel(), input_args=(x,))
@skipIfUnsupportedMinOpsetVersion(11) # float equal added after opset 11
def test_eq(self):
class EqualModel(torch.nn.Module):
def forward(self, input, other):
return input == other
self._test_compare_ops(EqualModel(), 2)
def test_gt(self):
class GreaterModel(torch.nn.Module):
def forward(self, input, other):
return input > other
self._test_compare_ops(GreaterModel(), 2)
@skipIfUnsupportedMinOpsetVersion(9)
def test_ge(self):
class GreaterOrEqualModel(torch.nn.Module):
def forward(self, input, other):
return input >= other
self._test_compare_ops(GreaterOrEqualModel(), 2)
def test_gt_scalar(self):
class GreaterModel(torch.nn.Module):
def forward(self, input):
return input > 1
self._test_compare_ops(GreaterModel(), 1)
def test_gt_primitive(self):
class GreaterModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.y: int = 2
def forward(self, x: int):
return self.y > x
x = 3
self.run_test(GreaterModel(), (x,))
@skipIfUnsupportedMinOpsetVersion(9)
def test_ge_scalar(self):
class GreaterOrEqualModel(torch.nn.Module):
def forward(self, input):
return input >= 1
self._test_compare_ops(GreaterOrEqualModel(), 1)
def test_lt(self):
class LessModel(torch.nn.Module):
def forward(self, input, other):
return input > other
self._test_compare_ops(LessModel(), 2)
@skipIfUnsupportedMinOpsetVersion(9)
def test_le(self):
class LessOrEqualModel(torch.nn.Module):
def forward(self, input, other):
return input <= other
self._test_compare_ops(LessOrEqualModel(), 2)
def test_lt_scalar(self):
class LessModel(torch.nn.Module):
def forward(self, input):
return input < 1
self._test_compare_ops(LessModel(), 1)
@skipIfUnsupportedMinOpsetVersion(9)
def test_le_scalar(self):
class LessOrEqualModel(torch.nn.Module):
def forward(self, input):
return input <= 1
self._test_compare_ops(LessOrEqualModel(), 1)
def test_matmul(self):
class MatmulModel(torch.nn.Module):
def forward(self, input, other):
return torch.matmul(input, other)
x = torch.randn(3, 4, requires_grad=True)
y = torch.randn(4, 5, requires_grad=True)
self.run_test(MatmulModel(), (x, y))
x = torch.randint(10, (3, 4))
y = torch.randint(10, (4, 5))
self.run_test(MatmulModel(), (x, y))
def test_matmul_batch(self):
class MatmulModel(torch.nn.Module):
def forward(self, input, other):
return torch.matmul(input, other)
x = torch.randn(2, 3, 4, requires_grad=True)
y = torch.randn(2, 4, 5, requires_grad=True)
self.run_test(MatmulModel(), (x, y))
x = torch.randint(10, (2, 3, 4))
y = torch.randint(10, (2, 4, 5))
self.run_test(MatmulModel(), (x, y))
def _argmin_argmax_model(self, input):
class ArgminArgmaxModel(torch.nn.Module):
def forward(self, input):
return (
torch.argmin(input),
torch.argmax(input),
torch.argmin(input, keepdim=True),
torch.argmax(input, keepdim=True),
torch.argmin(input, dim=0, keepdim=True),
torch.argmax(input, dim=1, keepdim=True),
)
self.run_test(ArgminArgmaxModel(), input)
@skipIfUnsupportedMinOpsetVersion(9)
def test_argmin_argmax(self):
input = torch.randn(7, 3, 5)
self._argmin_argmax_model(input)
# Argmin and Argmax with "select_last_index" is not supported before opset 12
# "select_last_index" was added in opset 12 to deal with corner case where the
# same value appears multiple times in the tensor
@skipIfUnsupportedMinOpsetVersion(12)
def test_argmin_argmax_select_last_index(self):
input = torch.tensor([[1.0, 2.0, 3.0], [1.0, 1.0, 2.0]])
self._argmin_argmax_model(input)
input = torch.ones(7, 3, 5)
self._argmin_argmax_model(input)
def test_repeat(self):
class RepeatModel(torch.nn.Module):
def forward(self, x, y):
x2 = x.repeat(y.shape[0], 1)
y1 = y.view(-1, 1)
return x2 + y1
x = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5, 8, 9])
self.run_test(RepeatModel(), (x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_repeat_interleave(self):
class FlattenModel(torch.nn.Module):
def forward(self, x):
return x.repeat_interleave(2)
for shape in ([3], [3, 4], [2, 3, 4]):
x = torch.randn(shape)
self.run_test(FlattenModel(), (x,))
class DimsModel(torch.nn.Module):
def forward(self, x):
return x.repeat_interleave(4, dim=1)
x = torch.tensor([[1, 2], [3, 4]])
self.run_test(DimsModel(), (x,))
class DimsModel2(torch.nn.Module):
def forward(self, x):
repeats = torch.tensor([4])
return torch.repeat_interleave(x, repeats, dim=1)
x = torch.tensor([[1, 2], [3, 4]])
self.run_test(DimsModel2(), (x,))
class RepeatsDimsModel(torch.nn.Module):
def forward(self, x):
repeats = torch.tensor([1, 2])
return torch.repeat_interleave(x, repeats, dim=0)
x = torch.tensor([[1, 2], [3, 4]])
self.run_test(RepeatsDimsModel(), (x,))
class RepeatsDimsModel2(torch.nn.Module):
def forward(self, x):
repeats = torch.tensor([1, 2])
return torch.repeat_interleave(x, repeats, dim=1)
x = torch.tensor([[1, 2], [3, 4]])
self.run_test(RepeatsDimsModel2(), (x,))
@skipIfUnsupportedMinOpsetVersion(9)
def test_repeat_interleave_noop(self):
class Model(torch.nn.Module):
def forward(self, x):
return x.repeat_interleave(1, dim=1)
x = torch.randn(4, 1, 8)
self.run_test(Model(), (x,))
@skipIfUnsupportedMinOpsetVersion(13)
def test_dynamic_repeat_interleave(self):
class SingleDynamicModel(torch.nn.Module):
def forward(self, x):
repeats = torch.tensor(4)
return torch.repeat_interleave(x, repeats, dim=1)
x = torch.tensor([[1, 2, 4], [3, 4, 7]])
another_x = torch.tensor([[7, 8], [5, 6]])
self.run_test(
SingleDynamicModel(),
x,
additional_test_inputs=[another_x],
input_names=["input_1"],
dynamic_axes={"input_1": {1: "w"}},
)
class NegDynamicModel(torch.nn.Module):
def forward(self, x):
repeats = torch.tensor(4)
return torch.repeat_interleave(x, repeats, dim=-1)
x = torch.tensor([[1, 2, 4], [3, 4, 7]])
another_x = torch.tensor([[7, 8], [5, 6]])
self.run_test(
NegDynamicModel(),
x,
additional_test_inputs=[another_x],
input_names=["input_1"],
dynamic_axes={"input_1": {1: "w"}},
)
class SingleDynamicModelFloat(torch.nn.Module):
def forward(self, x):
repeats = torch.tensor([4])
return torch.repeat_interleave(x, repeats, dim=0)
x = torch.tensor([[1.1, 2.1], [3.1, 4.1]])
another_x = torch.tensor([[7.1, 8.1], [5.1, 6.1]])
self.run_test(
SingleDynamicModelFloat(),
x,
additional_test_inputs=[another_x],
input_names=["input_1"],
dynamic_axes={"input_1": {0: "h"}},
)
class DynamicRepeatsModel(torch.nn.Module):
def forward(self, x, repeats):
return torch.repeat_interleave(x, repeats, dim=1)
x = torch.tensor([[1, 2, 4], [3, 4, 7]])
another_x = torch.tensor([[7, 8], [5, 6]])
repeats = torch.tensor([2])
another_repeats = torch.tensor([4])
self.run_test(
DynamicRepeatsModel(),
(x, repeats),
additional_test_inputs=[(another_x, another_repeats)],
input_names=["input_1", "repeats_1"],
dynamic_axes={"input_1": {1: "w"}, "repeats_1": {0: "r"}},
)
class DynamicRepeatsModel2(torch.nn.Module):
def forward(self, x, repeats):
return torch.repeat_interleave(x, repeats, dim=1)
x = torch.tensor([[1, 2, 4], [3, 4, 7]])
repeats = torch.tensor([2])
another_repeats = torch.tensor([4])
self.run_test(
DynamicRepeatsModel2(),
(x, repeats),
additional_test_inputs=[(x, another_repeats)],
input_names=["input_1", "repeats_1"],
dynamic_axes={"repeats_1": {0: "r"}},
)
class DynamicFlattenModel(torch.nn.Module):
def forward(self, x):
return x.repeat_interleave(2)
x = torch.tensor([1, 2, 3])
self.run_test(
DynamicFlattenModel(),
x,
input_names=["input_1"],
dynamic_axes={"input_1": {0: "w"}},
)
@skipIfUnsupportedMinOpsetVersion(13)
def test_multiple_dynamic_repeat_interleave(self):
class DynamicRepeatsModel(torch.nn.Module):
def forward(self, x, repeats):
return torch.repeat_interleave(x, repeats, dim=1)
x = torch.tensor([[1, 2, 4], [3, 4, 7]])
repeats = torch.tensor([2, 3, 4])
another_repeats = torch.tensor([4, 3, 2])
self.run_test(
DynamicRepeatsModel(),
(x, repeats),
additional_test_inputs=[(x, another_repeats)],
input_names=["input_1", "repeats_1"],
dynamic_axes={"repeats_1": {0: "r"}},
)
class DynamicRepeatsModel2(torch.nn.Module):
def forward(self, x, repeats):
return torch.repeat_interleave(x, repeats, dim=0)
x = torch.tensor([[1, 2, 4], [3, 4, 7]])
repeats = torch.tensor([2, 3])
another_repeats = torch.tensor([4, 3])
self.run_test(
DynamicRepeatsModel2(),
(x, repeats),
additional_test_inputs=[(x, another_repeats)],
input_names=["input_1", "repeats_1"],
dynamic_axes={"repeats_1": {0: "r"}},
)
def test_view(self):
class ViewModel(torch.nn.Module):
def forward(self, input):
return input.view(4, 24)
x = torch.randint(10, (4, 2, 3, 4), dtype=torch.int32)
self.run_test(ViewModel(), x)
def test_view_dynamic(self):
class ViewModel(torch.nn.Module):
def forward(self, input, other):
return input.view(other.shape)
x = torch.randn(2, 3, 4)
shape = torch.randn(6, 4)
self.run_test(
ViewModel(),
(x, shape),
input_names=["x", "shape"],
dynamic_axes={"x": [0, 1, 2], "shape": [0, 1]},
)
self.run_test(ViewModel(), (x, shape), remained_onnx_input_idx=[0])
def test_view_dynamic_zero_dim(self):
class ViewModel(torch.nn.Module):
def forward(self, input):
input = input.view(-1, 2)
return input.view(1, -1)
x = torch.ones(2)
another_x = torch.empty((0,))
self.run_test(
ViewModel(),
x,
additional_test_inputs=[another_x],
input_names=["input_1"],
dynamic_axes={
"input_1": [
0,
]
},
)
def test_view_as(self):
class ViewModel(torch.nn.Module):
def forward(self, input, other):
return input.view_as(other)
x = torch.randn(2, 3, 4)
y = torch.randn(6, 4)
self.run_test(ViewModel(), (x, y))
def test_linear(self):
class LinearModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.fc = torch.nn.Linear(16, 16)
def forward(self, x):
out = self.fc(x)
out = self.fc(out)
return out
x = torch.randn(3, 16)
self.run_test(LinearModel(), (x,))
class LinearModel(torch.nn.Module):
def forward(self, input, weight, bias):
return torch.nn.functional.linear(input, weight, bias)
# input of rank 2
x = torch.randn(2, 2)
y = torch.randn(2, 2)
z = torch.randn(1)
self.run_test(LinearModel(), (x, y, z))
# input of rank 3
x = torch.randn(3, 3, 3)
y = torch.randn(3, 3)
z = torch.randn(1)
self.run_test(LinearModel(), (x, y, z))
@skipScriptTest()
def test_weight_norm(self):
# addmm for 3-d inputs converts to onnx::MatMul
model = torch.nn.utils.weight_norm(torch.nn.Linear(5, 10), dim=1)
x = torch.randn(3, 4, 5, requires_grad=True)
self.run_test(model, x)
# addmm for 2-d inputs converts to onnx::Gemm
model = torch.nn.utils.weight_norm(torch.nn.Linear(5, 10), dim=1)
x = torch.randn(4, 5, requires_grad=True)
self.run_test(model, x)
model = torch.nn.utils.weight_norm(torch.nn.Conv1d(1, 1, 3))
x = torch.randn(1, 1, 5, requires_grad=True)
self.run_test(model, x)
model = torch.nn.utils.weight_norm(torch.nn.Conv1d(1, 1, 3), dim=-2)
x = torch.randn(1, 1, 5, requires_grad=True)
self.run_test(model, x)
model = torch.nn.utils.weight_norm(torch.nn.Conv1d(3, 6, 3), name="weight")
x = torch.randn(3, 3, 5, requires_grad=True)
self.run_test(model, x)
@skipScriptTest()
def test_weight_norm_nodim(self):
# addmm for 3-d inputs converts to onnx::MatMul
model = torch.nn.utils.weight_norm(torch.nn.Linear(5, 10), dim=None)
x = torch.randn(3, 4, 5, requires_grad=True)
self.run_test(model, x)
# addmm for 2-d inputs converts to onnx::Gemm
model = torch.nn.utils.weight_norm(torch.nn.Linear(5, 10), dim=None)
x = torch.randn(4, 5, requires_grad=True)
self.run_test(model, x)
def test_flatten(self):
class FlattenModel(torch.nn.Module):
def forward(self, input):
return torch.flatten(input)
model = FlattenModel()
# flatten with 4d input
x = torch.randint(10, (1, 2, 3, 4))
self.run_test(model, x)
# flatten with 0d input
x = torch.randn([])
self.run_test(model, x)
# flatten with 1d input
x = torch.randn(4)
self.run_test(model, x)
def test_flatten2d(self):
class FlattenModel(torch.nn.Module):
def forward(self, input):
return torch.flatten(input, 1)
x = torch.randint(10, (1, 2, 3, 4))
self.run_test(FlattenModel(), x)
def test_flatten2d_neg(self):
class FlattenModel(torch.nn.Module):
def forward(self, x):
return (
torch.flatten(x, 1, -1),
torch.flatten(x, 0, -2),
torch.flatten(x, 1, -2),
)
x = torch.randint(10, (1, 2, 3, 4))
self.run_test(FlattenModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_flatten_dynamic_axes(self):
class MyModule(torch.nn.Module):
def forward(self, x):
return torch.flatten(x, start_dim=2, end_dim=3)
batch_size = 3
x = torch.randn(batch_size, 5, 4, 5)
y = torch.randn(5, 5, 4, 5)
model = MyModule()
self.run_test(
model,
x,
additional_test_inputs=[y],
input_names=["input"],
output_names=["output"],
dynamic_axes={"input": {0: "batch_size"}, "output": {0: "batch_size"}},
)
@skipIfUnsupportedMinOpsetVersion(11)
def test_getitem(self):
class GetItemModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x, y, z, ind):
# this will create prim::ListConstruct(x, y, z) + aten::__getitem__
arr = [x, y, z]
return arr[ind]
x = torch.randn(3, 4, 5)
y = torch.randn(1, 4, 5)
z = torch.randn(2, 4, 5)
ind = torch.tensor(1, dtype=torch.long)
self.run_test(GetItemModel(), (x, y, z, ind))
ind = torch.tensor(-2, dtype=torch.long)
self.run_test(GetItemModel(), (x, y, z, ind))
@skipDtypeChecking
def test_item(self):
class M(torch.nn.Module):
def forward(self, x, y, i: int):
return int(x[y[i]].item())
x = torch.arange(6, dtype=torch.float)
y = torch.tensor([0, 1, 2, 3, 4], dtype=torch.long)
i = 3
self.run_test(torch.jit.script(M()), (x, y, i))
@skipScriptTest() # torch.nonzero(x, as_tuple=True) is not scriptable.
@skipIfUnsupportedMinOpsetVersion(9)
def test_nonzero(self):
class NonzeroModel(torch.nn.Module):
def forward(self, x):
return x.nonzero(), x.nonzero(as_tuple=True)
x = torch.randn(60).index_fill_(0, torch.randint(0, 60, (20,)), 0).view(3, 4, 5)
self.run_test(NonzeroModel(), (x,))
def test_unbind(self):
class UnbindModel(torch.nn.Module):
def forward(self, input):
_, out, _ = input.unbind()
return out
x = torch.randn(3, 4, 5)
self.run_test(UnbindModel(), x)
class UnbindModel2(torch.nn.Module):
def forward(self, input):
_, out, _, _ = input.unbind(1)
return out
x = torch.randn(3, 4, 5)
self.run_test(UnbindModel2(), x)
class UnbindModel3(torch.nn.Module):
def forward(self, input):
_, out, _, _ = input.unbind(-2)
return out
x = torch.randn(3, 4, 5)
self.run_test(UnbindModel3(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_len(self):
class LenModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return len(input.unbind()) + input
x = torch.randn(4, 5)
self.run_test(
LenModel(),
x,
input_names=["input"],
dynamic_axes={"input": {0: "seq"}},
additional_test_inputs=(torch.randn(5, 5),),
)
@skipIfUnsupportedMinOpsetVersion(9)
def test_len_list(self):
class LenListModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return torch.ones(len(input.shape))
x = torch.randn(4, 5)
self.run_test(LenListModel(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(11)
def test_unbind_dynamic(self):
class UnbindModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return input.unbind()[1]
x = torch.randn(3, 4, 5)
self.run_test(UnbindModel(), x)
class UnbindModel2(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return input.unbind(-1)[1]
x = torch.randn(3, 4, 5)
self.run_test(UnbindModel2(), x)
@skipScriptTest() # scripting tests run for opsets > 11. See: test_split_script
def test_split(self):
class SplitModel(torch.nn.Module):
def forward(self, input):
return input.split([2, 1, 2]), input.split([3, 2])[0]
x = torch.randn(5, 4, 3)
self.run_test(SplitModel(), x)
class SplitModel2(torch.nn.Module):
def forward(self, input):
return input.split([2, 1, 1], -2), input.split([2, 2], -2)[-1]
x = torch.randn(5, 4, 3)
self.run_test(SplitModel2(), x)
class SplitModel3(torch.nn.Module):
def forward(self, input):
return input.split([2, 1, 2])
x = torch.randn(5, 4, 3)
self.run_test(SplitModel3(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_split_script(self):
class SplitModel(torch.nn.Module):
def forward(self, input):
return input.split([2, 1, 2]), input.split([3, 2])[0]
x = torch.randn(5, 4, 3)
self.run_test(SplitModel(), x)
class SplitModel2(torch.nn.Module):
def forward(self, input):
return input.split([2, 1, 1], -2), input.split([2, 2], -2)[-1]
x = torch.randn(5, 4, 3)
self.run_test(SplitModel2(), x)
class SplitModel3(torch.nn.Module):
def forward(self, input):
return input.split([2, 1, 2])
x = torch.randn(5, 4, 3)
self.run_test(SplitModel3(), x)
@skipIfUnsupportedMinOpsetVersion(11)
@skipScriptTest()
def test_split_size_as_list(self):
class SplitModel(torch.nn.Module):
def forward(self, input, split_sizes: list[int]):
out = []
split_list: list[Tensor] = input.split(split_sizes)
for ob in split_list:
out.append(ob) # noqa: PERF402
return torch.cat(out, dim=0)
x = torch.randn(6, 4, 3)
split_sizes = [torch.tensor(2), torch.tensor(4)]
self.run_test(SplitModel(), (x, split_sizes))
@skipIfUnsupportedMinOpsetVersion(11)
def test_split_size_with_slice(self):
class SplitModule(torch.nn.Module):
def forward(self, x, y, t):
splits = (x.size(1), y.size(1))
out, out2 = torch.split(t, splits, dim=1)
return out, out2
x = torch.randn(2, 3)
y = torch.randn(2, 4)
t = torch.randn(2, 7)
self.run_test(
SplitModule(),
(x, y, t),
input_names=["x", "y", "t"],
dynamic_axes={"x": [0, 1], "y": [0, 1], "t": [0, 1]},
)
self.run_test(SplitModule(), (x, y, t), remained_onnx_input_idx=[2])
@skipIfUnsupportedMinOpsetVersion(11)
def test_split_dynamic(self):
class SplitModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return input.split(2)[1]
x = torch.randn(5, 4, 3)
self.run_test(SplitModel(), x)
class SplitModel2(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
return input.split(2, -3)[1]
x = torch.randn(5, 4, 3)
self.run_test(SplitModel2(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_split_dynamic_axes(self):
class Split(torch.nn.Module):
def forward(self, x):
return x.split(1, dim=-1)
x = torch.randn(4, 384, 2)
input_names = ["logits"]
self.run_test(
Split(),
x,
input_names=input_names,
dynamic_axes={input_names[0]: {0: "batch"}},
)
@skipIfUnsupportedMinOpsetVersion(11)
def test_chunk(self):
class ChunkModel(torch.nn.Module):
def __init__(self, dim=1):
super().__init__()
self.dim = dim
def forward(self, x):
return torch.chunk(x, 3, dim=self.dim)
model = ChunkModel()
model.eval()
model_neg_dim = ChunkModel(-1)
model_neg_dim.eval()
x = torch.randn(1, 18)
for dim_size_ in range(13, 16):
y = torch.randn(1, dim_size_)
self.run_test(
model,
x,
additional_test_inputs=[y],
input_names=["x"],
dynamic_axes={"x": {0: "batch_size", 1: "dims"}},
)
self.run_test(
model_neg_dim,
x,
additional_test_inputs=[y],
input_names=["x"],
dynamic_axes={"x": {0: "batch_size", 1: "dims"}},
)
@skipIfUnsupportedMinOpsetVersion(11)
def test_dynamic_chunk(self):
class ChunkModel(torch.nn.Module):
def __init__(self, dim=1):
super().__init__()
self.dim = dim
def forward(self, x):
return torch.chunk(x, x.size(0), dim=self.dim)
model = ChunkModel()
model.eval()
model_neg_dim = ChunkModel(-1)
model_neg_dim.eval()
x = torch.randn(3, 18)
for dim_size_ in range(13, 16):
y = torch.randn(3, dim_size_)
self.run_test(
model,
x,
additional_test_inputs=[y],
input_names=["x"],
dynamic_axes={"x": {0: "batch_size", 1: "dims"}},
)
self.run_test(
model_neg_dim,
x,
additional_test_inputs=[y],
input_names=["x"],
dynamic_axes={"x": {0: "batch_size", 1: "dims"}},
)
def test_concat(self):
class ConcatModel(torch.nn.Module):
def forward(self, x, y, z):
return torch.cat((x, y, z))
x = torch.randn(3, 4, 5)
y = torch.randn(1, 4, 5)
z = torch.randn(2, 4, 5)
self.run_test(ConcatModel(), (x, y, z))
@skipIfUnsupportedMinOpsetVersion(11)
def test_concat_dynamic(self):
class ConcatDynamicModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.cat(x.unbind())
x = torch.randn(4, 5, 6)
self.run_test(ConcatDynamicModel(), x)
def test_stack(self):
class StackModel(torch.nn.Module):
def forward(self, x, y, z):
return torch.stack((x, y, z), 1)
x = torch.randn(3, 4, 5)
y = torch.randn(3, 4, 5)
z = torch.randn(3, 4, 5)
self.run_test(StackModel(), (x, y, z))
@skipIfUnsupportedMinOpsetVersion(11)
def test_stack_dynamic(self):
class StackDynamicModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.stack(x.unbind(), 1)
x = torch.randn(4, 5, 6)
self.run_test(StackDynamicModel(), x)
def test_loop_dynamic(self):
class LoopModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
for i in range(x.size(2)):
x = x + i
return x
model = LoopModel()
inputs = torch.zeros(1, 2, 3, dtype=torch.long)
self.run_test(model, inputs)
@skipIfUnsupportedMinOpsetVersion(9)
def test_loop_nested(self):
class NestedLoopsModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
for _ in range(5):
a = 0
while a < 4:
a += 1
x = x + a
return x
model = NestedLoopsModel()
inputs = torch.zeros(1, 2, 3, dtype=torch.long)
self.run_test(model, inputs)
@skipIfUnsupportedMinOpsetVersion(11)
def test_loop_with_list(self):
class ListLoopModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
res = []
res1 = []
arr = x.split([3, 4, 1, 1, 2, 3, 2], 0)
res2 = torch.zeros(3, 4, dtype=torch.long)
res3 = []
res4 = []
for i in range(len(arr)):
res.append(arr[i].sum(0, False))
res1.append(arr[-1 - i].sum(0, False))
res2 += 1
res3 = res3 + [arr[i].sum(0, False)]
res4 += [arr[-1 - i].sum(0, False)]
return res, res1, res2, torch.stack(res3), torch.stack(res4)
model = ListLoopModel()
inputs = torch.randn(16)
self.run_test(model, inputs)
@skipIfUnsupportedMinOpsetVersion(11)
def test_loop_transpose(self):
class LoopModel(torch.nn.Module):
def forward(self, x):
res = torch.zeros_like(x[0])
for _ in range(x.size(0)):
res += x[0].transpose(0, 1)
return res
model = torch.jit.script(LoopModel())
x = torch.randn(5, 3, 3)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_loop_multi_dim(self):
class LoopMultiDimModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x, y):
for x_ in torch.flip(x.narrow(0, 0, 7), [0]):
y = x_[0][y]
return y
model = LoopMultiDimModel()
x = torch.randint(0, 5, (8, 1, 17), dtype=torch.long)
y = torch.ones(1, dtype=torch.long)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(11)
def test_list(self):
class ListModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
tensors = x.unbind()
res = []
res.append(tensors[0])
res.append(tensors[1])
res.pop(1)
res.insert(0, tensors[1])
res.append(tensors[2])
res += [tensors[3], tensors[4]]
res = res + [tensors[5]]
return torch.ones(len(res))
model = ListModel()
inputs = torch.randn(16, 1)
self.run_test(model, inputs)
@skipIfUnsupportedMinOpsetVersion(11)
def test_list_append(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
res += [torch.matmul(x[i], y)]
return res
model = torch.jit.script(ListModel())
x = torch.randn(16, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(13)
def test_list_append_nested(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
for j in range(x.size(1)):
res += [torch.matmul(x[i][j], y)]
return res
model = torch.jit.script(ListModel())
x = torch.randn(4, 4, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(14) # Need onnx::Identity of sequence in opset 14
def test_list_append_nested_2(self):
class ListModel(torch.nn.Module):
def forward(self, x):
res = []
res_replicate = []
for i in range(x.size(0)):
if len(res) > 2:
for j in range(x.size(1)):
res.append(x[i][j])
res_replicate.append(res[-1])
res.append(res_replicate[-1])
return res, res_replicate
model = torch.jit.script(ListModel())
x = torch.randn(4, 4, 3, 4)
self.run_test(model, (x,))
@skipIfUnsupportedMinOpsetVersion(13)
def test_list_append_nested_mixed_dtype(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
for j in range(x.size(1)):
if i == j:
res.append(x == y)
else:
res.append(x != y)
return res
model = torch.jit.script(ListModel())
x = torch.randn(4, 4, 3, 4)
y = torch.randn(3, 4)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(11)
def test_list_pop(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
res += [torch.matmul(x[i], y)]
res.pop()
return res
model = torch.jit.script(ListModel())
x = torch.randn(16, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(13)
def test_list_pop_nested(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
for j in range(x.size(1)):
res += [torch.matmul(x[i][j], y)]
res.pop()
res += [torch.matmul(x[i][0], y)]
return res
model = torch.jit.script(ListModel())
x = torch.randn(4, 4, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(11)
def test_list_del(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
res += [torch.matmul(x[i], y)]
del res[2]
return res
model = torch.jit.script(ListModel())
x = torch.randn(16, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(13)
def test_list_del_nested(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
for j in range(x.size(1)):
res += [torch.matmul(x[i][j], y)]
del res[i]
res += [torch.matmul(x[i][0], y)]
return res
model = torch.jit.script(ListModel())
x = torch.randn(4, 4, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(11)
def test_list_set(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
res.append(x[i])
res[y] = x[y]
return res
model = torch.jit.script(ListModel())
x = torch.randn(12, 4)
y = torch.tensor(2, dtype=torch.long)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(13)
def test_list_idx_sum(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
indices = torch.arange(x.size(0))
res = []
for i in range(x.size(0)):
res.append(x[i])
return res[torch.sum(indices[:y])]
model = torch.jit.script(ListModel())
x = torch.randn(12, 4)
y = torch.tensor(2, dtype=torch.long)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_tensor_factories(self):
class TensorFactory(torch.nn.Module):
def forward(self, x):
return torch.zeros(x.size()) + torch.ones(x.size())
x = torch.randn(2, 3, 4)
self.run_test(
TensorFactory(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]}
)
self.run_test(TensorFactory(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_tensor_factories_script(self):
class TensorFactory(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
return torch.zeros(x.shape, dtype=torch.float) + torch.ones(
x.shape, dtype=torch.float
)
x = torch.randn(2, 3, 4)
self.run_test(
TensorFactory(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]}
)
self.run_test(TensorFactory(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_tensor_like_factories_script(self):
class TensorFactory(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
zeros = torch.zeros_like(
x,
dtype=torch.float,
layout=torch.strided,
device=torch.device("cpu"),
)
ones = torch.ones_like(
x,
dtype=torch.float,
layout=torch.strided,
device=torch.device("cpu"),
)
return zeros + ones
x = torch.randn(2, 3, 4)
self.run_test(
TensorFactory(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]}
)
self.run_test(TensorFactory(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(13)
def test_tensor_split(self):
class TensorSplitModel(torch.nn.Module):
def forward(self, input):
return (
input.tensor_split([1, 3]),
# test with output indexing.
input.tensor_split([2, 4])[0],
# test split on specific dim.
input.tensor_split([1, 3, 4], dim=-2),
# test split on specific dim and output indexing.
input.tensor_split([0, 2], dim=-2)[-1],
# test with out of bound end index (5).
input.tensor_split([2, 3, 5]),
)
self.run_test(TensorSplitModel(), torch.randn(5, 4, 3))
@skipIfUnsupportedMinOpsetVersion(13)
def test_tensor_split_scalar(self):
class TensorSplitModel(torch.nn.Module):
def forward(self, x):
return torch.tensor_split(x, x.size(1))
self.run_test(TensorSplitModel(), torch.randn(1, 2, 3))
@skipIfUnsupportedMinOpsetVersion(13)
def test_tensor_split_dynamic_axes(self):
class TensorSplitModel(torch.nn.Module):
def forward(self, x):
return x.tensor_split(1, dim=-1)
x = torch.randn(4, 384, 2)
input_names = ["logits"]
self.run_test(
TensorSplitModel(),
x,
input_names=input_names,
dynamic_axes={input_names[0]: {0: "batch"}},
)
@skipIfUnsupportedMinOpsetVersion(9)
def test_eye(self):
class TensorFactory(torch.nn.Module):
def forward(self, x):
return (
torch.eye(x.size()[1], 3),
torch.eye(4, 4, dtype=torch.long),
torch.eye(x.size()[1], 2, dtype=torch.long),
torch.eye(x.shape[0]),
torch.eye(x.shape[0], dtype=torch.float64),
)
x = torch.randn(2, 3, 4)
another_x = torch.randn(5, 6, 7)
self.run_test(
TensorFactory(),
x,
additional_test_inputs=[another_x],
input_names=["input_1"],
dynamic_axes={"input_1": [0, 1, 2]},
)
@skipIfUnsupportedMinOpsetVersion(13)
def test_diagonal(self):
class DiagonalModel(torch.nn.Module):
def forward(self, x):
return torch.diagonal(x)
x = torch.randn(2, 4, 5, 2)
# Other test inputs to test dynamic behavior
another_x = torch.randn(5, 6, 7, 8)
self.run_test(
DiagonalModel(),
x,
additional_test_inputs=[another_x],
input_names=["input_1"],
dynamic_axes={"input_1": [0, 1, 2, 3]},
)
class DiagonalModelNegOffset(torch.nn.Module):
def forward(self, x):
return torch.diagonal(x, offset=-1)
x = torch.randn(2, 4, 5, 2)
# Other test inputs to test dynamic behavior
another_x = torch.randn(5, 6, 7, 8)
self.run_test(
DiagonalModelNegOffset(),
x,
additional_test_inputs=[another_x],
input_names=["input_1"],
dynamic_axes={"input_1": [0, 1, 2, 3]},
)
class DiagonalModelPosOffset(torch.nn.Module):
def forward(self, x):
return torch.diagonal(x, offset=1)
x = torch.randn(2, 4, 5, 2)
# Other test inputs to test dynamic behavior
another_x = torch.randn(5, 6, 7, 8)
self.run_test(
DiagonalModelPosOffset(),
x,
additional_test_inputs=[another_x],
input_names=["input_1"],
dynamic_axes={"input_1": [0, 1, 2, 3]},
)
class DiagonalModelWithDims(torch.nn.Module):
def forward(self, x):
return torch.diagonal(x, offset=-1, dim1=1, dim2=2)
x = torch.randn(2, 4, 5, 2)
# Other test inputs to test dynamic behavior
another_x = torch.randn(5, 6, 7, 8)
self.run_test(
DiagonalModelWithDims(),
x,
additional_test_inputs=[another_x],
input_names=["input_1"],
dynamic_axes={"input_1": [0, 1, 2, 3]},
)
class DiagonalModelWithNegativeDims(torch.nn.Module):
def forward(self, x):
return torch.diagonal(x, offset=0, dim1=-2, dim2=-1)
x = torch.randn(2, 4, 5, 2)
# Other test inputs to test dynamic behavior
another_x = torch.randn(5, 6, 7, 8)
self.run_test(
DiagonalModelWithNegativeDims(),
x,
additional_test_inputs=[another_x],
input_names=["input_1"],
dynamic_axes={"input_1": [0, 1, 2, 3]},
)
class DiagonalModelOffsetOverrun(torch.nn.Module):
def forward(self, x):
return torch.diagonal(x, offset=-2), torch.diagonal(x, offset=5)
x = torch.randn(2, 4, 5, 2)
# Other test inputs to test dynamic behavior
another_x = torch.randn(5, 6, 7, 8)
self.run_test(
DiagonalModelOffsetOverrun(),
x,
additional_test_inputs=[another_x],
input_names=["input_1"],
dynamic_axes={"input_1": [0, 1, 2, 3]},
)
@skipIfUnsupportedMinOpsetVersion(9)
def test_inplace_zero(self):
class Zero_(torch.nn.Module):
def forward(self, x):
return x.zero_(), x
x = torch.randn(2, 3, 4)
self.run_test(Zero_(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(Zero_(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(11)
def test_inplace_zero_qkv(self):
class Zero_(torch.nn.Module):
def forward(self, x):
return x[2:4].zero_()
x = torch.randn(24, 3, 4)
self.run_test(Zero_(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
@skipIfUnsupportedMinOpsetVersion(9)
def test_new_zeros(self):
class Zero_(torch.nn.Module):
def forward(self, x):
return x.new_zeros(x.shape[1:2]), x.new_zeros(
x.shape[2:], dtype=torch.long
)
x = torch.randn(2, 3, 4)
self.run_test(Zero_(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(Zero_(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_new_zeros_with_dtype(self):
class MyModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.emb = torch.nn.Embedding(50, 64)
def forward(self, x):
inp = x.new_zeros(x.shape)
return self.emb(inp)
model = MyModel()
x = torch.Tensor([[2, 5, 6], [3, 2, 5]]).to(torch.int64)
self.run_test(model, x, input_names=["x"], dynamic_axes={"x": [0, 1]})
@skipIfUnsupportedMinOpsetVersion(9)
def test_new_ones(self):
class OnesModel(torch.nn.Module):
def forward(self, x):
return x.new_ones(x.shape[1:2]), x.new_ones(
x.shape[2:], dtype=torch.long
)
x = torch.randn(2, 3, 4)
self.run_test(OnesModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(OnesModel(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
@skipScriptTest() # torch.zeros/torch.ones with size tensor of dim != 0 not scriptable.
def test_zeros_ones_with_tensor_input(self):
class ZeroAndOnes(torch.nn.Module):
def forward(self, x):
return torch.zeros(x, 1), torch.ones(x, 1)
x = torch.tensor([2])
self.run_test(ZeroAndOnes(), (x,))
@skipIfUnsupportedMinOpsetVersion(9)
@skipShapeChecking
def test_tolist(self):
class List(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
res: list[int] = input.tolist()
return res
self.run_test(List(), (torch.randint(100, (1,)),))
@skipIfUnsupportedMinOpsetVersion(9)
def test_list_pass(self):
class Slice(torch.nn.Module):
def forward(self, x, y):
return x.new_zeros(x.shape[2:] + y.shape[1:])
x = torch.randn(2, 3, 4, 5)
y = torch.randn(1, 2, 3, 4)
self.run_test(
Slice(),
(x, y),
input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2, 3], "y": [0, 1, 2, 3]},
)
self.run_test(Slice(), (x, y), remained_onnx_input_idx=[])
class Size(torch.nn.Module):
def forward(self, x, y):
return x.new_zeros(x.shape + y.shape)
x = torch.randn(2, 3, 4)
y = torch.randn(1, 2, 3)
self.run_test(
Size(),
(x, y),
input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2], "y": [0, 1, 2]},
)
self.run_test(Size(), (x, y), remained_onnx_input_idx=[])
class Array(torch.nn.Module):
def forward(self, x, y):
arr1 = [x.shape[0], x.shape[1], 2]
arr2 = [y.shape[0], y.shape[1]]
return x.new_zeros(arr1 + arr2)
x = torch.randn(2, 3, 4)
y = torch.randn(1, 2, 3)
self.run_test(
Array(),
(x, y),
input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2], "y": [0, 1, 2]},
)
self.run_test(Array(), (x, y), remained_onnx_input_idx=[])
class List(torch.nn.Module):
def forward(self, x, y):
l1 = list(x.shape)
l2 = list(y.shape)
return x.new_zeros(l1 + l2)
x = torch.randn(2, 3, 4)
y = torch.randn(1, 2, 3)
self.run_test(
List(),
(x, y),
input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2], "y": [0, 1, 2]},
)
self.run_test(List(), (x, y), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_new_empty(self):
class Empty(torch.nn.Module):
def forward(self, x):
return (
x.new_empty(x.shape[0]).fill_(0),
x.new_empty(x.shape[0], dtype=torch.long) * 0,
)
x = torch.randn(2, 3, 4)
self.run_test(Empty(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(Empty(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_new_full(self):
class Full(torch.nn.Module):
def forward(self, x):
return x.new_full(x.shape[1:2], 5), x.new_full(
x.shape[0:1], 1.3, dtype=torch.long
)
x = torch.randn(2, 3, 4)
self.run_test(Full(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(Full(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_inplace_list(self):
class Arithmetic(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x, y):
return torch.cat([x.add_(3), y.fill_(0)])
x = torch.randn(2, 3)
y = torch.randn(2, 3)
self.run_test(
Arithmetic(),
(x, y),
input_names=["x", "y"],
dynamic_axes={"x": [0, 1], "y": [0, 1]},
)
self.run_test(Arithmetic(), (x, y), remained_onnx_input_idx=[0])
@skipIfUnsupportedMinOpsetVersion(9)
def test_inplace_fill(self):
class Fill_(torch.nn.Module):
def forward(self, x):
return x.fill_(3), x
x = torch.randn(2, 3, 4)
self.run_test(Fill_(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]})
self.run_test(Fill_(), x, remained_onnx_input_idx=[])
def test_inplace_arithmetic(self):
class Arithmetic(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x, y):
x.add_(3)
y.mul_(x)
return x, y
x = torch.randn(2, 3, 4)
y = torch.randn(2, 3, 4)
self.run_test(Arithmetic(), (x, y))
def test_inplace_arithmetic_half(self):
class InplaceAddModel(torch.nn.Module):
def forward(self, x, y):
return x.add_(y)
class InplaceMulModel(torch.nn.Module):
def forward(self, x, y):
return x.mul_(y)
x = torch.randn(2, 2, dtype=torch.half)
y = torch.randn(2, 2, dtype=torch.float)
self.run_test(InplaceAddModel(), (x, y), rtol=1e-2, atol=1e-2)
self.run_test(InplaceMulModel(), (x, y), rtol=1e-2, atol=1e-2)
@skipIfUnsupportedMinOpsetVersion(9)
def test_inplace_with_loop(self):
class M(torch.nn.Module):
def forward(self, x):
a = torch.ones(
12,
)
for _ in range(10):
a.add_(
torch.ones(
12,
)
)
return a + x
m = M()
x = torch.randn(
12,
)
self.run_test(torch.jit.script(M()), (x))
@skipIfUnsupportedMinOpsetVersion(9)
def test_inplace_with_loop_2(self):
class M(torch.nn.Module):
def forward(self, x):
_bias = torch.ones(
12,
)
a = torch.ones(
12,
) # used in loop, altered.
a_ref = a # not used in loop, should be altered.
b = x.clone() # used in loop, not be altered.
b_ref = b # not used in loop, should not be altered.
for i in range(10):
if i == 3:
for _ in range(5):
a += _bias
_bias.add_(
torch.ones(
12,
)
)
b = b + torch.ones(
12,
)
_bias.add_(
torch.ones(
12,
)
)
a += _bias
# TODO: value for a_ref is incorrect.
# a_ref += torch.ones(12,)
b_ref += torch.ones(
12,
)
return _bias + x, a, b, b_ref
m = M()
x = torch.zeros(
12,
)
self.run_test(torch.jit.script(M()), (x))
@skipIfUnsupportedMinOpsetVersion(11)
def test_inplace_attr_with_loop(self):
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self._bias = torch.arange(
12,
)
def forward(self, x):
self._bias = torch.arange(
12,
)
for i in range(10):
if i == 3:
for _ in range(5):
self._bias += torch.arange(
12,
)
return self._bias + x
m = M()
x = torch.zeros(
12,
)
self.run_test(torch.jit.script(M()), (x))
@skipIfUnsupportedMinOpsetVersion(11)
def test_inplace_attr_copy_with_loop(self):
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self._bias = torch.arange(
12,
)
def forward(self, x):
self._bias = torch.arange(
12,
)
for i in range(10):
if i == 3:
for _ in range(5):
self._bias.copy_(
torch.arange(
12,
)
)
self._bias.copy_(
self._bias
+ torch.arange(
12,
)
)
self._bias.copy_(
self._bias
+ torch.arange(
12,
)
)
return self._bias + x
m = M()
x = torch.zeros(
12,
)
self.run_test(torch.jit.script(M()), (x))
@skipIfUnsupportedMinOpsetVersion(14) # Need onnx::Identity of sequence in opset 14
def test_inplace_sequence_with_loop(self):
class M(torch.nn.Module):
def process(self, beam_hyps: list[Tensor], done: Tensor, x):
batch_size = x.shape[0]
for i in range(batch_size):
if done[i]:
continue
beam_idx = 0
for _, token in enumerate(x[i]):
beam_hyps.append(token)
beam_idx += 1 # noqa: SIM113
if beam_idx == 6:
break
done[i] = len(beam_hyps) > 4
return beam_hyps, done
def forward(self, x):
beam_hyps: list[Tensor] = []
batch_size = x.shape[0]
cur_len = 0
max_len = x.shape[1]
done = torch.zeros(batch_size, dtype=torch.bool)
while cur_len < max_len:
beam_hyps, done = self.process(beam_hyps, done, x[:, 0, :])
cur_len = cur_len + 1
return beam_hyps
m = torch.jit.script(M())
x = torch.randn(8, 4, 3)
self.run_test(torch.jit.script(M()), (x))
@skipScriptTest() # Sort with dynamic dim not supported in ONNX
def test_sort(self):
class SortModel(torch.nn.Module):
def forward(self, x):
out = []
for i in range(-2, 2):
out.append(torch.sort(x, dim=i, descending=True))
return out
x = torch.randn(3, 4)
self.run_test(SortModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
@skipScriptTest() # Sort with dynamic dim not supported in ONNX
def test_sort_ascending(self):
class SortModel(torch.nn.Module):
def forward(self, x):
out = []
for i in range(-2, 2):
out.append(torch.sort(x, dim=i, descending=False))
return out
x = torch.randn(3, 4)
self.run_test(SortModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_argsort(self):
class ArgSortModel(torch.nn.Module):
def forward(self, x):
return torch.argsort(x, dim=1, descending=False)
x = torch.randn(3, 4)
self.run_test(ArgSortModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_masked_fill(self):
class MaskedFillModel(torch.nn.Module):
def forward(self, x):
mask = torch.tensor([[0, 0, 1], [1, 1, 0]], dtype=torch.bool)
return x.masked_fill(mask, 2)
x = torch.zeros(4, 2, 3, requires_grad=True)
self.run_test(MaskedFillModel(), x)
class MaskedFillModel2(torch.nn.Module):
def forward(self, x):
return x.masked_fill(x > 3, -1)
x = torch.arange(16).view(2, 2, 4).to(torch.float32)
self.run_test(MaskedFillModel2(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_masked_fill_inplace(self):
class MaskedFillModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
mask = torch.tensor([[0, 0, 1], [1, 1, 0]], dtype=torch.bool)
x.masked_fill_(mask, 2)
return x
x = torch.zeros(4, 2, 3, requires_grad=True)
self.run_test(MaskedFillModel(), x)
class MaskedFillModel2(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, x):
x.masked_fill_(x > 3, -1)
return x
x = torch.arange(16).view(2, 2, 4).to(torch.float32)
self.run_test(MaskedFillModel2(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_masked_scatter(self):
class MaskedScatterModel(torch.nn.Module):
def forward(self, x):
return torch.masked_scatter(x, x.ge(0.5), torch.ones(100, 100) * 5)
x = torch.randn(3, 4, 5, requires_grad=True)
self.run_test(MaskedScatterModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_masked_select(self):
class MaskedSelectModel(torch.nn.Module):
def forward(self, x):
return torch.masked_select(x, x.ge(0.5))
x = torch.randn(3, 4, 5, requires_grad=True)
self.run_test(MaskedSelectModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_to_masked_fill(self):
class MaskedFillModel(torch.nn.Module):
def forward(self, input_mask, some_const):
mask = input_mask.clone()
mask[mask != some_const] = 1
mask[mask == some_const] = 0
return mask
mask = torch.randn(2, 2, 2, requires_grad=True)
constant = torch.tensor(5, dtype=torch.float)
self.run_test(MaskedFillModel(), (mask, constant))
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_to_masked_scatter(self):
class MaskedScatterModel(torch.nn.Module):
def forward(self, input_mask, some_const):
mask = input_mask.clone()
mask[mask != some_const] = torch.ones(8)
return mask
mask = torch.randn(2, 2, 2, requires_grad=True)
constant = torch.tensor(5, dtype=torch.float)
self.run_test(MaskedScatterModel(), (mask, constant))
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_with_1d_mask_to_masked_scatter(self):
class MaskedScatterModel(torch.nn.Module):
def forward(self, tensor, mask, some_const):
tensor[mask] = some_const
return tensor
mask = torch.tensor([0, 1, 0, 1, 0, 1, 0, 1], dtype=torch.bool)
tensor = torch.randn(8, 4, 5, requires_grad=True)
some_const = torch.randn(4, 4, 5, dtype=torch.float)
self.run_test(MaskedScatterModel(), (tensor, mask, some_const))
@skipIfUnsupportedMinOpsetVersion(9)
def test_pixel_shuffle(self):
class PixelShuffle(torch.nn.Module):
def forward(self, x):
return torch.pixel_shuffle(x, upscale_factor=2)
x = torch.randn(2, 16, 4, 3, requires_grad=True)
y = torch.randn(4, 32, 8, 4, requires_grad=True)
self.run_test(PixelShuffle(), x)
self.run_test(
PixelShuffle(),
x,
input_names=["x"],
dynamic_axes={"x": [0, 1, 2, 3]},
additional_test_inputs=[y],
)
@skipIfUnsupportedMinOpsetVersion(9)
def test_pixel_unshuffle(self):
class PixelUnshuffle(torch.nn.Module):
def forward(self, x):
return torch.pixel_unshuffle(x, downscale_factor=2)
x = torch.randn(2, 16, 4, 6, requires_grad=True)
y = torch.randn(4, 32, 8, 4, requires_grad=True)
self.run_test(PixelUnshuffle(), x)
self.run_test(
PixelUnshuffle(),
x,
input_names=["x"],
dynamic_axes={"x": [0, 1, 2, 3]},
additional_test_inputs=[y],
)
@skipIfUnsupportedMinOpsetVersion(9)
def test_reciprocal(self):
class ReciprocalModel(torch.nn.Module):
def forward(self, x):
return torch.reciprocal(x)
model = ReciprocalModel()
x = torch.tensor([2, 4])
self.run_test(model, x.to(torch.long))
self.run_test(model, x.to(torch.float))
self.run_test(model, x.to(torch.double))
@skipIfUnsupportedMinOpsetVersion(9)
def test_scalar_type(self):
class ArithmeticModel(torch.nn.Module):
def forward(self, x):
return x.size(0) * 2 * x, 2 - x
x = torch.ones(2, 3, dtype=torch.float32)
self.run_test(ArithmeticModel(), x)
class ComparisonModel(torch.nn.Module):
def forward(self, x, y):
a = torch.tensor([12.0])
return x.lt(1.5) & y.le(2) & x.le(1), x.gt(y), x.lt(y), a.ge(x.size(0))
x = torch.ones(2, 3, dtype=torch.int32)
y = torch.ones(2, 3, dtype=torch.float32)
self.run_test(ComparisonModel(), (x, y))
class MatMulModel(torch.nn.Module):
def forward(self, x):
return torch.mm(x, x) + x + torch.mm(x, x) + x
x = torch.ones(3, 3)
self.run_test(MatMulModel(), x)
class AddMMModel(torch.nn.Module):
def forward(self, x):
return torch.mm(x, x) + x
x = torch.ones(3, 3)
self.run_test(AddMMModel(), x)
class FullModel(torch.nn.Module):
# add is used for exporting full
def forward(self, x):
return torch.full((3, 4), x)
x = torch.tensor(12.0)
self.run_test(FullModel(), x)
class CatModel(torch.nn.Module):
def forward(self, fp16, fp32):
return torch.cat([fp16, fp32])
fp16 = Tensor([0.5])
fp16 = fp16.half()
fp32 = Tensor([1.5])
self.run_test(CatModel(), (fp16, fp32))
@skipIfUnsupportedMinOpsetVersion(9)
def test_scalar_type_does_not_trigger_upcast_type_promotion(self):
class DoNotUpcastModel(torch.nn.Module):
def forward(self, x):
scale = x.size()[-1] ** -0.5
# 'scale' is exported as onnx float32 rank 0 tensor.
# The following 'Mul' should NOT be promoted to float32.
return x * scale
x = torch.ones(2, 3, dtype=torch.float16)
self.run_test(DoNotUpcastModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_scalar_type_promotion_onnx_where_two_prim_const(self):
class TwoPrimConstCastWhereModel(torch.nn.Module):
def forward(self, c):
return torch.where(c, 0, 1.0)
c = torch.ones(8, dtype=torch.bool)
self.run_test(TwoPrimConstCastWhereModel(), (c))
@skipIfUnsupportedMinOpsetVersion(9)
def test_scalar_type_promotion_onnx_where_one_prim_const(self):
class OnePrimConstCastWhereModel(torch.nn.Module):
def forward(self, c, x):
return torch.where(c, x, 1.0)
c = torch.ones(8, dtype=torch.bool)
x = torch.ones(8, dtype=torch.float16)
self.run_test(OnePrimConstCastWhereModel(), (c, x))
@skipIfUnsupportedMinOpsetVersion(9)
def test_scalar_type_promotion_onnx_where_one_tensor_const(self):
class OneTensorConstCastWhereModel(torch.nn.Module):
def forward(self, c, x):
return torch.where(c, x, torch.ones(size=(), dtype=torch.float64))
c = torch.ones(8, dtype=torch.bool)
x = torch.ones(8, dtype=torch.float16)
self.run_test(OneTensorConstCastWhereModel(), (c, x))
@skipIfUnsupportedMinOpsetVersion(9)
def test_scalar_type_upcast_type_promotion_onnx_where_no_const(self):
class OnnxWhereUpcastModel(torch.nn.Module):
def forward(self, c, x, y):
return torch.where(c, x, y)
c = torch.ones(8, dtype=torch.bool)
x = torch.ones(8, dtype=torch.float16)
y = torch.ones(8, dtype=torch.float32)
self.run_test(OnnxWhereUpcastModel(), (c, x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_full_like(self):
class FullLikeModel(torch.nn.Module):
def forward(self, x):
return torch.full_like(x, 1.3, dtype=torch.int)
x = torch.tensor(12)
self.run_test(FullLikeModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
@skipDtypeChecking
def test_full_like_value(self):
class FullLikeModel(torch.nn.Module):
def forward(self, x, y):
out = y + 2
return torch.full_like(x, out)
x = torch.tensor(12)
y = torch.tensor(2)
self.run_test(FullLikeModel(), (x, y))
def test_l1_norm(self):
class NormModel(torch.nn.Module):
def forward(self, x):
return torch.norm(x, p=1, dim=-1, keepdim=False)
x = torch.randn(4, 2, 3, requires_grad=True)
self.run_test(NormModel(), x)
def test_l2_norm(self):
class NormModel(torch.nn.Module):
def forward(self, x):
return torch.norm(x, p=2, dim=-2, keepdim=False)
x = torch.randn(4, 2, 3, requires_grad=True)
self.run_test(NormModel(), x)
def test_frobenius_norm(self):
class NormModel(torch.nn.Module):
def forward(self, x):
return torch.norm(x, p="fro", dim=0, keepdim=False)
x = torch.randn(4, 2, 3, requires_grad=True)
self.run_test(NormModel(), x)
def test_frobenius_norm_keepdim(self):
class NormModel(torch.nn.Module):
def forward(self, x):
return torch.norm(x, p="fro", dim=(0, 1), keepdim=True)
x = torch.randn(4, 2, 3, requires_grad=True)
self.run_test(NormModel(), x)
def test_unfold(self):
class UnfoldModel(torch.nn.Module):
def forward(self, x):
return x.unfold(dimension=2, size=2, step=2)
x = torch.randn(4, 2, 3, requires_grad=True)
y = torch.randn(2, 1, 3, requires_grad=True)
self.run_test(
UnfoldModel(),
x,
dynamic_axes={"x": [0, 1]},
input_names=["x"],
additional_test_inputs=[y],
)
def test_unfold_infer_shape(self):
class UnfoldModule(torch.jit.ScriptModule):
def __init__(self) -> None:
super().__init__()
self.conv = torch.nn.Conv1d(3, 1, 3, stride=2)
@torch.jit.script_method
def forward(self, x):
x = self.conv(x)
return x.unfold(dimension=2, size=2, step=2)
x = torch.randn(32, 3, 64)
self.run_test(UnfoldModule(), x)
@skipIfUnsupportedMinOpsetVersion(12)
def test_unfold_dynamic_inputs(self):
class UnfoldModel(torch.nn.Module):
def forward(self, x):
return x.unfold(dimension=2, size=x.shape[1], step=x.shape[1] - 1)
x = torch.randn(4, 2, 4, requires_grad=True)
self.run_test(UnfoldModel(), x)
class UnfoldModel(torch.nn.Module):
def forward(self, x):
return x.unfold(dimension=2, size=x.shape[1], step=1)
x = torch.randn(4, 2, 4, requires_grad=True)
self.run_test(UnfoldModel(), x)
@skipIfUnsupportedMinOpsetVersion(9) # MatMul long inputs is added in ONNX opset 9.
def test_mv(self):
class MatmulModel(torch.nn.Module):
def forward(self, input, other):
return torch.mv(input, other)
x = torch.randn(4, 5, requires_grad=True)
y = torch.randn(5, requires_grad=True)
self.run_test(MatmulModel(), (x, y))
x = torch.randint(10, (4, 5))
y = torch.randint(10, (5,))
self.run_test(MatmulModel(), (x, y))
@skipIfUnsupportedMinOpsetVersion(9) # MatMul long inputs is added in ONNX opset 9.
def test_dot(self):
class MatmulModel(torch.nn.Module):
def forward(self, input, other):
return torch.dot(input, other)
x = torch.randn(5, requires_grad=True)
y = torch.randn(5, requires_grad=True)
self.run_test(MatmulModel(), (x, y))
x = torch.randint(10, (5,))
y = torch.randint(10, (5,))
self.run_test(MatmulModel(), (x, y))
@skipScriptTest() # SpectralNorm not TorchScript compatible.
def test_spectral_norm(self):
m = torch.nn.utils.spectral_norm(torch.nn.Linear(2, 4))
x = torch.randn(6, 2)
self.run_test(m, (x,))
def test_prelu(self):
class PReluModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.prelu = torch.nn.PReLU()
def forward(self, x):
return self.prelu(x)
x = torch.randn(2, 3, 4)
y = torch.randn(2, 4, 5)
self.run_test(
PReluModel(),
x,
input_names=["x"],
dynamic_axes={"x": [1, 2]},
additional_test_inputs=[y],
)
def test_prelu_scalar(self):
x = torch.scalar_tensor(1.0)
self.run_test(torch.nn.PReLU(), x, input_names=["x"])
def test_relu6(self):
class Relu6Model(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.relu6 = torch.nn.ReLU6()
def forward(self, x):
return self.relu6(x)
x = torch.randn(2, 3, 4) * 100.0
y = torch.randn(2, 4, 5) * 100.0
self.run_test(
Relu6Model(),
x,
input_names=["x"],
dynamic_axes={"x": [1, 2]},
additional_test_inputs=[y],
)
def test_silu(self):
class SiLUModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.silu = torch.nn.SiLU()
def forward(self, x):
return self.silu(x)
x = torch.randn(2, 3, 4)
self.run_test(SiLUModel(), (x))
@skipIfUnsupportedMinOpsetVersion(14)
def test_tril(self):
class trilModel(torch.nn.Module):
def forward(self, x):
return torch.tril(x)
x = torch.randn(2, 3, 4)
self.run_test(trilModel(), (x))
class trilModelwithDiagonal(torch.nn.Module):
def forward(self, x):
return torch.tril(x, diagonal=1)
x = torch.randn(2, 3, 4)
self.run_test(trilModelwithDiagonal(), (x))
class trilModelwithNegDiagonal(torch.nn.Module):
def forward(self, x):
return torch.tril(x, diagonal=-1)
x = torch.randn(2, 3, 4)
self.run_test(trilModelwithNegDiagonal(), (x))
class trilModelWithDiagonalInput(torch.nn.Module):
def forward(self, x, diagnonal: int):
return torch.tril(x, diagonal=diagnonal)
x = torch.randn(2, 3, 4)
self.run_test(trilModelWithDiagonalInput(), (x, 5))
@skipIfUnsupportedMinOpsetVersion(14)
def test_triu(self):
class triuModel(torch.nn.Module):
def forward(self, x):
return torch.triu(x)
x = torch.randn(2, 3, 4)
self.run_test(triuModel(), (x))
class triuModelwithDiagonal(torch.nn.Module):
def forward(self, x):
return torch.triu(x, diagonal=1)
x = torch.randn(2, 3, 4)
self.run_test(triuModelwithDiagonal(), (x))
class triuModelwithNegDiagonal(torch.nn.Module):
def forward(self, x):
return torch.triu(x, diagonal=-1)
x = torch.randn(2, 3, 4)
self.run_test(triuModelwithNegDiagonal(), (x))
class triuModelWithDiagonalInput(torch.nn.Module):
def forward(self, x, diagnonal: int):
return torch.triu(x, diagonal=diagnonal)
x = torch.randn(2, 3, 4)
self.run_test(triuModelWithDiagonalInput(), (x, 5))
def test_mish(self):
class MishModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.mish = torch.nn.Mish()
def forward(self, x):
return self.mish(x)
x = torch.randn(2, 3, 4)
self.run_test(MishModel(), (x))
def test_remainder(self):
class RemainderModel(torch.nn.Module):
def forward(self, input, other):
return torch.remainder(input, other)
x = torch.randn(4, 2, 3)
y = torch.randn(1, 2, 1)
self.run_test(RemainderModel(), (x, y))
x = torch.tensor([7, 6, -7, -6], dtype=torch.long)
y = torch.tensor([2], dtype=torch.long)
self.run_test(RemainderModel(), (x, y))
x = x.to(torch.float)
self.run_test(RemainderModel(), (x, y))
y = y.to(torch.float)
self.run_test(RemainderModel(), (x, y))
x = x.to(torch.int32)
self.run_test(RemainderModel(), (x, y))
def test_remainder_scalar(self):
class RemainderModel(torch.nn.Module):
def __init__(self, scalar=2.55):
super().__init__()
self.scalar = scalar
def forward(self, input):
return torch.remainder(input, self.scalar)
x = torch.randint(10, (2, 3))
self.run_test(RemainderModel(), x)
x = torch.tensor([7, 6, -7, -6], dtype=torch.long)
self.run_test(RemainderModel(2), x)
@skipIfUnsupportedMinOpsetVersion(10)
def test_fmod(self):
class FModModel(torch.nn.Module):
def forward(self, input, other):
return torch.fmod(input, other)
x = torch.randn(4, 2, 3)
y = torch.randn(1, 2, 1)
self.run_test(FModModel(), (x, y))
@skipIfUnsupportedMinOpsetVersion(10)
def test_fmod_scalar(self):
class FModModel(torch.nn.Module):
def forward(self, input):
return torch.fmod(input, 2.55)
x = torch.randint(10, (2, 3))
self.run_test(FModModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_glu(self):
class GluModel(torch.nn.Module):
def forward(self, x):
return torch.nn.functional.glu(x)
x = torch.randn(2, 4, 5, 6, requires_grad=True)
self.run_test(GluModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_gelu(self):
class GeluModel(torch.nn.Module):
def forward(self, x):
return torch.nn.functional.gelu(x, approximate="none")
x = torch.randn(2, 4, 5, 6, requires_grad=True)
self.run_test(GeluModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_tanh_gelu(self):
class GeluModel(torch.nn.Module):
def forward(self, x):
return torch.nn.functional.gelu(x, approximate="tanh")
x = torch.randn(2, 4, 5, 6, requires_grad=True)
self.run_test(GeluModel(), x)
def test_add_inplace(self):
class InplaceAddModel(torch.nn.Module):
def forward(self, x):
x += 12
return x
x = torch.randn(4, 2, 3, requires_grad=True)
self.run_test(InplaceAddModel(), x)
def test_addcmul(self):
class AddcmulModel(torch.nn.Module):
def forward(self, x, t1, t2):
return torch.addcmul(x, t1, t2), torch.addcmul(x, t1, t2, value=2.2)
x = torch.randn(1, 3)
t1 = torch.randn(3, 1)
t2 = torch.randn(1, 3)
self.run_test(AddcmulModel(), (x, t1, t2))
def test_rsqrt(self):
class RsqrtModel(torch.nn.Module):
def forward(self, x):
return x.rsqrt()
x = torch.randn(4, 2, 3, requires_grad=True, dtype=torch.float64)
self.run_test(RsqrtModel(), x)
def test_rsqrt_zeros(self):
class RsqrtModel(torch.nn.Module):
def forward(self, x):
return x.rsqrt()
x = torch.zeros(4, 2, 3, requires_grad=True, dtype=torch.float64)
self.run_test(RsqrtModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_unique(self):
class UniqueModel(torch.nn.Module):
def forward(self, x):
return torch.unique(
x, sorted=True, return_inverse=False, return_counts=True
)
x = torch.tensor([1, 3, 2, 3], dtype=torch.long)
self.run_test(UniqueModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_unique_along_dim(self):
class UniqueModel(torch.nn.Module):
def forward(self, x):
return torch.unique(
x, dim=0, sorted=True, return_inverse=True, return_counts=False
)
x = torch.tensor([1, 3, 2, 3], dtype=torch.long)
self.run_test(UniqueModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_cumsum(self):
class CumSum(torch.nn.Module):
def forward(self, input):
return torch.cumsum(input, dim=0)
x = torch.randn(2, 3, 4)
model = CumSum()
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_cumsum_with_cast(self):
class CumSum(torch.nn.Module):
def forward(self, input):
return torch.cumsum(input, dim=0, dtype=torch.float32)
model = CumSum()
x = torch.tensor([2, 3, 4], dtype=torch.int32)
self.run_test(model, x)
x = torch.tensor([False, True, True])
self.run_test(model, x)
@skipScriptTest() # error in propagate as assign input shape
@skipIfUnsupportedMinOpsetVersion(10)
def test_embedding_bag(self):
model = torch.nn.EmbeddingBag(10, 5, mode="sum", scale_grad_by_freq=True)
input = torch.randint(10, (7,))
offset = torch.tensor([0, 2, 5, 6])
self.run_test(model, (input, offset))
model = torch.nn.EmbeddingBag(10, 5, mode="sum", include_last_offset=True)
input = torch.randint(10, (7,))
offset = torch.tensor([0, 2, 5, 6])
self.run_test(model, (input, offset))
model = torch.nn.EmbeddingBag(10, 5, mode="max")
input = torch.randint(10, (7, 5))
self.run_test(model, (input))
@skipIfUnsupportedMinOpsetVersion(11)
def test_embedding_bag_1d_per_sample_weights(self):
class EmbeddingModel(torch.nn.Module):
def forward(self, embedding_matrix, input, offset, weights):
return torch.nn.functional.embedding_bag(
input,
embedding_matrix,
offsets=offset,
mode="sum",
per_sample_weights=weights,
)
model = EmbeddingModel()
x = torch.randint(7, (6,))
w = torch.randn(
6,
)
offset = torch.tensor([0, 2, 5])
embedding_matrix = torch.rand(10, 15)
self.run_test(model, (embedding_matrix, x, offset, w))
@skipIfUnsupportedMinOpsetVersion(11)
@unittest.skip(
"This test is broken with ONNXRuntime(17): "
"when running with onnxruntime 1.17.0 this test fails with the following error:"
"FAIL : Non-zero status code returned while running If node. "
"Name:'/If' Status Message: if.cc:253 Compute "
"If nodes condition input must have exactly one element"
"https://github.com/pytorch/pytorch/issues/119442"
)
def test_embedding_bag_2d_per_sample_weights(self):
class EmbeddingModel(torch.nn.Module):
def forward(self, embedding_matrix, input, weights):
return torch.nn.functional.embedding_bag(
input, embedding_matrix, mode="sum", per_sample_weights=weights
)
embedding_matrix = torch.rand(10, 15)
model = EmbeddingModel()
x = torch.randint(7, (2, 3))
w = torch.randn(2, 3)
x2 = torch.randint(7, (4, 3))
w2 = torch.randn(4, 3)
self.run_test(
model,
(embedding_matrix, x, w),
input_names=["embed", "x", "w"],
dynamic_axes={"x": [0], "w": [0]},
additional_test_inputs=[(embedding_matrix, x2, w2)],
)
@skipScriptTest() # scripting prim::Uninitialized, prim::dtype, prim::unchecked_cast
@skipIfUnsupportedMinOpsetVersion(11)
@unittest.skip(
"Due to ONNX Loop shape inference issue. "
"https://msdata.visualstudio.com/Vienna/_workitems/edit/1352001"
)
def test_embedding_bag_dynamic_input(self):
class EmbeddingModel1D(torch.nn.Module):
def forward(self, embedding_matrix, input, weights, offsets):
return torch.nn.functional.embedding_bag(
input,
embedding_matrix,
offsets=offsets,
mode="sum",
per_sample_weights=weights,
)
model = EmbeddingModel1D()
x = torch.randint(7, (6,))
w = torch.randn(
6,
)
offsets = torch.tensor([0, 2, 5], dtype=torch.long)
embedding_matrix = torch.rand(10, 15)
x2 = torch.randint(7, (2,))
w2 = torch.randn(
2,
)
embedding_matrix2 = torch.rand(12, 25)
offsets2 = torch.tensor(
[
0,
],
dtype=torch.long,
)
self.run_test(
model,
(embedding_matrix, x, w, offsets),
additional_test_inputs=[(embedding_matrix2, x2, w2, offsets2)],
input_names=["embedding_matrix", "x", "offsets", "w"],
dynamic_axes={
"embedding_matrix": [0, 1],
"x": [0],
"offsets": [0],
"w": [0],
},
)
class EmbeddingModel2D(torch.nn.Module):
def forward(self, embedding_matrix, input, weights):
return torch.nn.functional.embedding_bag(
input, embedding_matrix, mode="sum", per_sample_weights=weights
)
model = EmbeddingModel2D()
x = torch.randint(7, (2, 3))
w = torch.randn(2, 3)
embedding_matrix = torch.rand(10, 15)
x2 = torch.randint(7, (3, 5))
w2 = torch.randn(3, 5)
embedding_matrix2 = torch.rand(12, 25)
self.run_test(
model,
(embedding_matrix, x, w),
additional_test_inputs=[(embedding_matrix2, x2, w2)],
input_names=["embedding_matrix", "x", "w"],
dynamic_axes={"embedding_matrix": [0, 1], "x": [0, 1], "w": [0, 1]},
)
@skipIfUnsupportedMinOpsetVersion(8)
def test_meshgrid(self):
class Meshgrid(torch.nn.Module):
def forward(self, x, y, z):
output1, output2, output3 = torch.meshgrid(x, y, z)
return output1, output2, output3
x = torch.randn(3, requires_grad=True)
y = torch.zeros(4, requires_grad=True)
z = torch.randn(5, requires_grad=True)
self.run_test(Meshgrid(), (x, y, z))
@skipIfUnsupportedMinOpsetVersion(8)
def test_meshgrid_indexing(self):
class Meshgrid(torch.nn.Module):
def __init__(self, indexing):
super().__init__()
self.indexing = indexing
def forward(self, x, y, z):
output1, output2, output3 = torch.meshgrid(
x, y, z, indexing=self.indexing
)
return output1, output2, output3
x = torch.randn(5, requires_grad=True)
y = torch.zeros(6, requires_grad=True)
z = torch.randn(7, requires_grad=True)
for indexing in ("xy", "ij"):
self.run_test(Meshgrid(indexing), (x, y, z))
@skipIfUnsupportedMinOpsetVersion(8)
def test_meshgrid_scalar(self):
class Meshgrid(torch.nn.Module):
def forward(self, x, y, z):
output1, output2, output3 = torch.meshgrid(x, y, z)
return output1, output2, output3
x = torch.ones(3, requires_grad=True)
y = torch.zeros(4, requires_grad=True)
z = torch.tensor(2.0)
self.run_test(Meshgrid(), (x, y, z))
def test_baddbmm(self):
class MyModule(torch.nn.Module):
def forward(self, input, batch1, batch2):
return torch.baddbmm(
input, batch1, batch2, alpha=torch.tensor(5), beta=3.5
)
x = torch.randn(10, 3, 5)
batch1 = torch.randn(10, 3, 4)
batch2 = torch.randn(10, 4, 5)
model = MyModule()
self.run_test(model, (x, batch1, batch2))
def test_baddbmm_dynamic(self):
class MyModule(torch.nn.Module):
def forward(self, input, batch1, batch2, alpha, beta):
return torch.baddbmm(input, batch1, batch2, alpha=alpha, beta=beta)
x = torch.randn(10, 3, 5)
batch1 = torch.randn(10, 3, 4)
batch2 = torch.randn(10, 4, 5)
alpha = torch.tensor(5)
beta = torch.tensor(3.5)
model = MyModule()
self.run_test(model, (x, batch1, batch2, alpha, beta))
def test_numel(self):
class MyModule(torch.nn.Module):
def forward(self, input):
return input.numel() * input
x = torch.randn(2, 3, 5)
x2 = torch.randn(4, 5, 6)
model = MyModule()
self.run_test(
model,
(x,),
input_names=["x"],
dynamic_axes={"x": [0, 1, 2]},
additional_test_inputs=[(x2,)],
)
def test_numel_empty(self):
class MyModule(torch.nn.Module):
def forward(self, input):
return input.numel() * input
x = torch.randn(0)
x2 = torch.randn(4)
model = MyModule()
self.run_test(
model,
(x,),
input_names=["x"],
dynamic_axes={"x": [0]},
additional_test_inputs=[(x2,)],
)
def test_dtype(self):
class MyModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input, other):
return input.to(dtype=other.dtype) + other
x = torch.randn(2, 3)
y = torch.randn(2, 3)
self.run_test(MyModel(), (x, y))
def test_dtype_eq(self):
class MyModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input, other):
if input.dtype == other.dtype:
return input + other
return input
x = torch.randn(2, 3)
y = torch.randn(2, 3)
self.run_test(MyModel(), (x, y))
def test_cast_to(self):
class MyModule(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input, other):
return input.to(other) + other
x = torch.randn(2, 3, 4)
y = torch.tensor([1], dtype=torch.int64)
model = MyModule()
self.run_test(model, (x, y))
def test_cast_to_bool(self):
class MyModule(torch.nn.Module):
def forward(self, input, other):
return torch.cat((input.to(other), other), 0)
x = torch.randn(2, 3, 4)
y = torch.zeros([2, 3, 4], dtype=torch.bool)
model = MyModule()
self.run_test(model, (x, y))
# ONNX supports bfloat16 for opsets >= 13
@skipIfUnsupportedMinOpsetVersion(13)
def test_cast_type_as_with_bfloat16(self):
class MyModule(torch.nn.Module):
def forward(self, x):
y = torch.ones((3, 4), dtype=torch.bfloat16)
x = x.type_as(y)
return x.to(dtype=torch.float16)
x = torch.ones(3, 4, dtype=torch.float16)
model = MyModule()
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_type_as(self):
class MyModule(torch.nn.Module):
def forward(self, x):
y = torch.tensor([1.0])
return x.type_as(y)
a = torch.tensor([True, False], dtype=torch.bool)
b = torch.randn(3, 4, dtype=torch.double)
c = torch.ones((2, 2), dtype=torch.int64)
model = MyModule()
self.run_test(model, a)
self.run_test(model, b)
self.run_test(model, c)
@skipIfUnsupportedMinOpsetVersion(9)
def test_ones_bool(self):
class MyModule(torch.nn.Module):
def forward(self, input):
true = torch.ones(input.shape, dtype=torch.bool)
return input.to(true) & true
x = torch.randn(2, 3, 4)
model = MyModule()
self.run_test(model, x)
def test_log(self):
class Log(torch.nn.Module):
def forward(self, input):
return torch.log(input)
x = torch.rand(2, 3, 4)
model = Log()
self.run_test(model, x)
def test_log1p(self):
class Log1p(torch.nn.Module):
def forward(self, input):
return torch.log1p(input)
x = torch.rand(2, 3, 4)
model = Log1p()
self.run_test(model, x)
def test_log10(self):
class Log10(torch.nn.Module):
def forward(self, input):
return torch.log10(input)
x = torch.rand(2, 3, 4)
model = Log10()
self.run_test(model, x)
def test_log2(self):
class Log2(torch.nn.Module):
def forward(self, input):
return torch.log2(input)
x = torch.tensor(1.0)
model = Log2()
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_round(self):
class Round(torch.nn.Module):
def forward(self, x):
return torch.round(x)
x = torch.tensor([0.9920, -1.0362, -1.5000, 3.5000], requires_grad=True)
self.run_test(Round(), x)
int_x = torch.tensor([9920, 1036, -1500, 35], dtype=torch.int32)
self.run_test(Round(), int_x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_round_with_decimals(self):
class Round(torch.nn.Module):
def __init__(self, decimals):
super().__init__()
self.decimals = decimals
def forward(self, x):
return torch.round(x, decimals=self.decimals)
x = torch.tensor([0.9920, -1234.0362, -1.58960, 3.5000])
for decimals in (0, -2, 3):
self.run_test(Round(decimals), x)
@skipIfUnsupportedMinOpsetVersion(17)
def test_stft_default(self):
class STFT(torch.nn.Module):
def forward(self, x):
n_fft = 16
return torch.stft(x, n_fft=n_fft, center=False, return_complex=False)
x = torch.randn((1, 32), requires_grad=True)
self.run_test(STFT(), x, atol=1e-6)
@skipIfUnsupportedMinOpsetVersion(17)
def test_stft_hop_length(self):
class STFT(torch.nn.Module):
def forward(self, x):
n_fft = 16
hop_length = 4
return torch.stft(
x,
n_fft=n_fft,
center=False,
hop_length=hop_length,
return_complex=False,
)
x = torch.randn((1, 32), requires_grad=True)
self.run_test(STFT(), x, atol=1e-6)
@skipIfUnsupportedMinOpsetVersion(17)
def test_stft_non_divisible_hop_length(self):
class STFT(torch.nn.Module):
def forward(self, x):
n_fft = 16
hop_length = 5
return torch.stft(
x,
n_fft=n_fft,
center=False,
hop_length=hop_length,
return_complex=False,
)
x = torch.randn((1, 32), requires_grad=True)
self.run_test(STFT(), x, atol=1e-6)
@skipIfUnsupportedMinOpsetVersion(17)
def test_stft_window_int_same_size(self):
class STFT(torch.nn.Module):
def forward(self, x):
n_fft = 16
win_length = 16
return torch.stft(
x,
n_fft=n_fft,
center=False,
win_length=win_length,
return_complex=False,
)
x = torch.randn((1, 32), requires_grad=True)
self.run_test(STFT(), x, atol=1e-6)
@skipIfUnsupportedMinOpsetVersion(17)
def test_stft_window_int_different_size(self):
class STFT(torch.nn.Module):
def forward(self, x):
n_fft = 16
win_length = 9
return torch.stft(
x,
n_fft=n_fft,
center=False,
win_length=win_length,
return_complex=False,
)
x = torch.randn((1, 32), requires_grad=True)
self.run_test(STFT(), x, atol=1e-6)
@skipIfUnsupportedMinOpsetVersion(17)
def test_stft_window_custom(self):
class STFT(torch.nn.Module):
def forward(self, x):
n_fft = 16
window = torch.hann_window(16)
return torch.stft(
x,
n_fft=n_fft,
center=False,
window=window,
return_complex=False,
)
x = torch.randn((1, 32), requires_grad=True)
self.run_test(STFT(), x, atol=1e-6)
@skipIfUnsupportedMinOpsetVersion(17)
def test_stft_wrong_custom_window_size(self):
class STFT(torch.nn.Module):
def forward(self, x):
n_fft = 16
window = torch.hann_window(10)
return torch.stft(
x, n_fft=n_fft, window=window, center=False, return_complex=False
)
x = torch.randn((1, 32), requires_grad=True)
with self.assertRaises((AssertionError, RuntimeError)):
self.run_test(STFT(), x)
@skipIfUnsupportedMinOpsetVersion(17)
def test_stft_wrong_window_length(self):
class STFT(torch.nn.Module):
def forward(self, x):
n_fft = 16
win_len = 17
return torch.stft(
x,
n_fft=n_fft,
win_length=win_len,
center=False,
return_complex=False,
)
x = torch.randn((1, 32), requires_grad=True)
with self.assertRaises(RuntimeError):
self.run_test(STFT(), x)
@skipIfUnsupportedMinOpsetVersion(17)
def test_stft_window_size_with_win_len(self):
class STFT(torch.nn.Module):
def forward(self, x):
n_fft = 16
window = torch.hann_window(10)
win_len = 10
return torch.stft(
x,
n_fft=n_fft,
window=window,
win_length=win_len,
center=False,
return_complex=False,
)
x = torch.randn((1, 32), requires_grad=True)
self.run_test(STFT(), x, atol=1e-6)
@skipIfUnsupportedMinOpsetVersion(17)
def test_stft_one_dimension(self):
class STFT(torch.nn.Module):
def forward(self, x):
n_fft = 16
return torch.stft(
x,
n_fft=n_fft,
center=False,
return_complex=False,
)
x = torch.randn((32), requires_grad=True)
self.run_test(STFT(), x, atol=1e-6)
@skipIfUnsupportedMinOpsetVersion(17)
def test_stft_wrong_input_size(self):
class STFT(torch.nn.Module):
def forward(self, x):
n_fft = 16
return torch.stft(x, n_fft=n_fft, center=False, return_complex=False)
x = torch.randn((1, 1, 32), requires_grad=True)
with self.assertRaises(RuntimeError):
self.run_test(STFT(), x)
@skipIfUnsupportedMinOpsetVersion(17)
def test_stft_wrong_return_complex(self):
class STFT(torch.nn.Module):
def forward(self, x):
n_fft = 16
return torch.stft(x, n_fft=n_fft, center=False, return_complex=True)
x = torch.randn((1, 32), requires_grad=True)
with self.assertRaises(errors.SymbolicValueError):
self.run_test(STFT(), x)
@skipIfUnsupportedMinOpsetVersion(17)
def test_stft_normalize(self):
class STFT(torch.nn.Module):
def forward(self, x):
n_fft = 16
return torch.stft(
x,
n_fft=n_fft,
center=False,
normalized=True,
return_complex=False,
)
x = torch.randn((32), requires_grad=True)
self.run_test(STFT(), x, atol=1e-6)
@skipIfUnsupportedMinOpsetVersion(17)
def test_stft_not_onesided(self):
class STFT(torch.nn.Module):
def forward(self, x):
n_fft = 16
return torch.stft(
x,
n_fft=n_fft,
center=False,
onesided=False,
return_complex=False,
)
x = torch.randn((32), requires_grad=True)
self.run_test(STFT(), x, atol=1e-6)
def test_constant_pad(self):
model = torch.nn.ConstantPad1d(2, 3.5)
x = torch.randn(2, 4, 4)
self.run_test(model, x)
model = torch.nn.ConstantPad2d((3, 0, 2, 1), 3.5)
x = torch.randn(2, 2, 4, 4)
self.run_test(model, x)
@common_utils.parametrize(
"pad",
[
common_utils.subtest([2, 4], name="scalar_list"),
common_utils.subtest(
[
torch.tensor(2, dtype=torch.int64),
torch.tensor(4, dtype=torch.int64),
],
name="scalar_tensor_list",
),
],
)
@skipIfUnsupportedMinOpsetVersion(11) # Dynamic padding is added in opset 11
def test_pad_types(self, pad):
# Test for different pad integer types
class Pad(torch.nn.Module):
def forward(self, x, pad: list[int]):
return torch.nn.functional.pad(x, pad)
x = torch.randn(2, 2, 4, 4)
self.run_test(Pad(), (x, pad))
@skipIfUnsupportedMinOpsetVersion(11)
def test_pad_circular(self):
class PadModel(torch.nn.Module):
def forward(self, x):
out = torch.nn.functional.pad(x, (1, 2, 1, 2), mode="circular")
return out
x = torch.randn(2, 3, 3, 4)
self.run_test(PadModel(), (x))
@skipIfUnsupportedMinOpsetVersion(11)
def test_pad_circular_negative(self):
# Test for different pad integer types
class PadModel(torch.nn.Module):
def forward(self, x):
out = torch.nn.functional.pad(x, (-1, -2), mode="circular")
return out
x = torch.randn(2, 3, 6)
self.run_test(PadModel(), (x))
@skipIfUnsupportedMinOpsetVersion(11)
def test_pad_circular_dynamic_axes(self):
class PadModel(torch.nn.Module):
def forward(self, x):
out = torch.nn.functional.pad(x, (2, 1, 2, 1), mode="circular")
return out
x = torch.randn(4, 3, 5, 6)
self.run_test(
PadModel(),
x,
input_names=["input_1"],
dynamic_axes={"input_1": [0, 1, 2, 3]},
)
@skipIfUnsupportedMaxOpsetVersion(10)
@skipScriptTest() # TODO: the logic in symbolic_opset9 doesn't handle script
def test_unsupported_pad(self):
class Pad(torch.nn.Module):
def forward(self, x, pad: list[int]):
return torch.nn.functional.pad(x, pad)
x = torch.randn(2, 2, 4, 4)
y = [2, 4]
with self.assertRaisesRegex(
RuntimeError,
(
"Unsupported: ONNX export of Pad.*"
+ "The sizes of the padding must be constant"
),
):
self.run_test(Pad(), (x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_if_fold(self):
class IfFoldModel(torch.nn.Module):
def forward(self, y):
if y.dim() == 2:
y = y + 4
y = y + 2
else:
y = y - 1
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), x)
class IfFoldModel(torch.nn.Module):
def forward(self, y):
if y.numel() > 1:
y = y + 4
else:
y = y + 2
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), x)
class IfFoldModel(torch.nn.Module):
def forward(self, y):
if y.dim() != 3:
y = y + 4
y = y + 2
else:
return y
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), x)
class IfFoldModel(torch.nn.Module):
def forward(self, y):
if y.dim() >= 1:
y = y + 4
else:
y = y - 1
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), x)
class IfFoldModel(torch.nn.Module):
def forward(self, y):
if y.dim() <= 1:
y = y + 4
else:
y = y + 2
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), x)
class IfFoldModel(torch.nn.Module):
def forward(self, y):
if y.dim() < 3 and y.dtype == torch.int:
y = y + 4
y = y + 2
else:
return y
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), x)
class IfFoldModel(torch.nn.Module):
def forward(self, y):
if y.dim() == 3 and y.dtype == torch.int:
y = y + 4
y = y + 2
else:
y = y + 1
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), x)
class IfFoldModel(torch.nn.Module):
def forward(self, y):
if y.numel() != 0 and y.dim() == 2:
y = y + 4
y = y + 2
else:
return y
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), x)
class IfFoldModel(torch.nn.Module):
def forward(self, x, y):
if x.numel() == y.numel():
y = x + y
else:
y = y - x
return y
x = torch.ones((3, 4), dtype=torch.int)
y = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), (x, y))
class IfFoldModel(torch.nn.Module):
def forward(self, x, y):
if x.numel() != y.numel():
y = x + y
else:
y = y - x
return y
x = torch.ones((3, 4), dtype=torch.int)
y = torch.ones((3, 4), dtype=torch.int)
self.run_test(IfFoldModel(), (x, y))
@skipIfUnsupportedMinOpsetVersion(11)
def test_uninitialized(self):
class UninitializedModel(torch.nn.Module):
def forward(self, y):
if y.shape[1] < 5:
if y.size(0) == 1:
y = y + 4
else:
return y
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(UninitializedModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_uninitialized_dynamic(self):
class UninitializedModel(torch.nn.Module):
def forward(self, y):
if y.shape[1] < 5:
if y.size(0) == 1:
y = y + 4
else:
return y
return y
x = torch.ones((3, 4), dtype=torch.int)
y = torch.ones((6, 7), dtype=torch.int)
self.run_test(
UninitializedModel(),
x,
additional_test_inputs=[y],
input_names=["input_1"],
dynamic_axes={"input_1": [0, 1]},
)
# onnx::Identity of sequence supported for ONNX opset >= 14
@skipIfUnsupportedMinOpsetVersion(14)
def test_uninitialized_tensorList(self):
class UninitializedTensorListModel(torch.nn.Module):
def forward(self, x):
if x[0].shape[0] < 5:
if x.size(0) == 1:
x = x + 4
else:
return [x]
return [x]
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(torch.jit.script(UninitializedTensorListModel()), x)
# onnx::Identity of sequence supported for ONNX opset >= 14
@skipIfUnsupportedMinOpsetVersion(14)
def test_uninitialized_tensorList_dynamic(self):
class UninitializedTensorListModel(torch.nn.Module):
def forward(self, x):
if x[0].shape[0] < 5:
if x.size(0) == 1:
x += x
else:
return list(x)
return list(x)
x = torch.ones((3, 4), dtype=torch.double)
self.run_test(
torch.jit.script(UninitializedTensorListModel()),
x,
input_names=["input_1"],
dynamic_axes={"input_1": [0, 1]},
)
# onnx::Identity of sequence supported for ONNX opset >= 14
@skipIfUnsupportedMinOpsetVersion(14)
def test_uninitialized_intList(self):
class UninitializedListModel(torch.nn.Module):
def forward(self, x):
y = list(range(x.size(0)))
if y[0] < 5:
# if x.size(0) != 3, ORT will throw type error.
if x.size(0) == 3:
y.append(10)
else:
return y
return y
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(
torch.jit.script(UninitializedListModel()),
x,
input_names=["input_1"],
dynamic_axes={"input_1": [0, 1]},
)
# onnx::Identity of sequence supported for ONNX opset >= 14
@skipIfUnsupportedMinOpsetVersion(14)
def test_uninitialized_tensorList_shape(self):
class UninitializedModel(torch.nn.Module):
def forward(self, x):
if x.shape[1] < 5:
if x.size(0) == 1:
x = x + 4
else:
x_list = list(x)
x_list.append(x)
return x_list
return [x, x]
x = torch.ones((3, 4), dtype=torch.int)
y = torch.ones((4, 6), dtype=torch.int)
self.run_test(
torch.jit.script(UninitializedModel()),
x,
additional_test_inputs=[y],
input_names=["input_1"],
dynamic_axes={"input_1": [0, 1]},
)
# Sequence type as loop-carried dependencies only supported for ONNX opset >= 13
@skipIfUnsupportedMinOpsetVersion(13)
def test_sequance_loopcarried(self):
class SequanceLoopModel(torch.nn.Module):
def forward(self, x):
outputs = []
for _ in range(3):
outputs += [x]
return torch.stack(outputs).transpose(0, 1)
x = torch.ones((3, 4), dtype=torch.int)
self.run_test(torch.jit.script(SequanceLoopModel()), x)
def test_reflection_pad(self):
model = torch.nn.ReflectionPad1d(2)
x = torch.randn(2, 4, 4)
self.run_test(model, x)
model = torch.nn.ReflectionPad2d((3, 0, 2, 1))
x = torch.randn(2, 2, 4, 4)
self.run_test(model, x)
def test_replication_pad(self):
model = torch.nn.ReplicationPad1d(2)
x = torch.randn(2, 4, 4)
self.run_test(model, x)
model = torch.nn.ReplicationPad2d((3, 0, 2, 1))
x = torch.randn(2, 2, 4, 4)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_im2col(self):
class Unfold(torch.nn.Module):
def forward(self, input):
return (
torch.nn.functional.unfold(
input, kernel_size=(10, 15), dilation=2, padding=5, stride=3
),
torch.nn.functional.unfold(
input, kernel_size=(2, 2), dilation=1, padding=0, stride=3
),
torch.nn.functional.unfold(
input, kernel_size=(1, 1), dilation=5, padding=2, stride=3
),
)
x = torch.rand(1, 1, 200, 100)
self.run_test(Unfold(), x)
@skipIfNoLapack
@skipIfUnsupportedMinOpsetVersion(11)
def test_det(self):
class Det(torch.nn.Module):
def forward(self, x):
return torch.linalg.det(x)
x = torch.randn(2, 3, 5, 5)
self.run_test(Det(), x)
def test_linalg_norm(self):
class LinalgSingleDimModel(torch.nn.Module):
def __init__(self, ord_val):
super().__init__()
self.ord = ord_val
def forward(self, x):
return torch.linalg.norm(x, ord=self.ord, dim=1)
x = torch.randn(2, 3, 5, 5)
self.run_test(LinalgSingleDimModel(None), x)
self.run_test(LinalgSingleDimModel(2), x)
self.run_test(LinalgSingleDimModel(float("inf")), x)
self.run_test(LinalgSingleDimModel(-float("inf")), x)
self.run_test(LinalgSingleDimModel(-4), x)
self.run_test(LinalgSingleDimModel(1.5), x)
class LinalgMultiDimModel(torch.nn.Module):
def __init__(self, ord_val):
super().__init__()
self.ord = ord_val
def forward(self, x):
return torch.linalg.norm(x, ord=self.ord, dim=(0, 2))
x = torch.randn(2, 3, 5, 5)
self.run_test(LinalgMultiDimModel("fro"), x)
self.run_test(LinalgMultiDimModel(float("inf")), x)
self.run_test(LinalgMultiDimModel(-float("inf")), x)
self.run_test(LinalgMultiDimModel(1), x)
self.run_test(LinalgMultiDimModel(-1), x)
class LinalgNoDimNoOrdModel(torch.nn.Module):
def forward(self, x):
return torch.linalg.norm(x)
x = torch.randn(2, 3, 5, 5)
self.run_test(LinalgNoDimNoOrdModel(), x)
y = torch.randn(2, 3)
self.run_test(LinalgNoDimNoOrdModel(), y)
z = torch.randn(2)
self.run_test(LinalgNoDimNoOrdModel(), z)
class LinalgNoDim1DModel(torch.nn.Module):
def __init__(self, ord_val):
super().__init__()
self.ord = ord_val
def forward(self, x):
return torch.linalg.norm(x, ord=self.ord)
x = torch.randn(2)
self.run_test(LinalgNoDim1DModel(None), x)
self.run_test(LinalgNoDim1DModel(2), x)
self.run_test(LinalgNoDim1DModel(float("inf")), x)
self.run_test(LinalgNoDim1DModel(-float("inf")), x)
self.run_test(LinalgNoDim1DModel(-4), x)
self.run_test(LinalgNoDim1DModel(1.5), x)
class LinalgNoDim2DModel(torch.nn.Module):
def __init__(self, ord_val):
super().__init__()
self.ord = ord_val
def forward(self, x):
return torch.linalg.norm(x, ord=self.ord)
x = torch.randn(2, 3)
self.run_test(LinalgNoDim2DModel("fro"), x)
self.run_test(LinalgNoDim2DModel(float("inf")), x)
self.run_test(LinalgNoDim2DModel(-float("inf")), x)
self.run_test(LinalgNoDim2DModel(1), x)
self.run_test(LinalgNoDim2DModel(-1), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_linalg_vector_norm_zero(self):
class LinalgVectorNormModel(torch.nn.Module):
def __init__(self, ord_val):
super().__init__()
self.ord = ord_val
def forward(self, x):
return torch.linalg.vector_norm(x, ord=self.ord)
x = torch.randn(2, 3, 5, 5)
self.run_test(LinalgVectorNormModel(0), x)
def test_linalg_vector_norm(self):
class LinalgVectorNormModel(torch.nn.Module):
def __init__(self, ord_val, dim_info):
super().__init__()
self.ord = ord_val
self.dim, self.keepdim = dim_info
def forward(self, x):
return torch.linalg.vector_norm(
x, ord=self.ord, dim=self.dim, keepdim=self.keepdim
)
x = torch.randn(2, 3, 5, 5)
ord_options = [2, float("inf"), -float("inf"), -4, 1.5]
dim_options = [(None, False), (1, False), ((1, 2), False), ((1, 2), True)]
for ord_val in ord_options:
for dim_info in dim_options:
self.run_test(LinalgVectorNormModel(ord_val, dim_info), x)
def test_linalg_matrix_norm(self):
class LinalgMatrixNormModel(torch.nn.Module):
def __init__(self, ord_val, dim_val=(-2, -1), keepdim_val=False):
super().__init__()
self.ord = ord_val
self.dim = dim_val
self.keepdim = keepdim_val
def forward(self, x):
return torch.linalg.matrix_norm(
x, ord=self.ord, dim=self.dim, keepdim=self.keepdim
)
x = torch.randn(2, 3, 5, 5)
ord_options = ["fro", float("inf"), -float("inf"), 1, -1]
for ord_val in ord_options:
self.run_test(LinalgMatrixNormModel(ord_val), x)
self.run_test(LinalgMatrixNormModel(ord_val, (0, 2)), x)
self.run_test(LinalgMatrixNormModel(ord_val, (0, 2), True), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_linalg_cross(self):
class Cross(torch.nn.Module):
def forward(self, x, y):
return torch.linalg.cross(x, y, dim=1), torch.linalg.cross(x, y)
x = torch.randn(5, 3, 2, 3)
y = torch.randn(1, 3, 1, 3)
self.run_test(Cross(), input_args=(x, y))
# This test checks output scalar type in the ONNX graph should not be null
# https://github.com/pytorch/pytorch/issues/28607
@skipIfUnsupportedMinOpsetVersion(10)
def test_trace_script(self):
@torch.jit.script
def center_slice_helper(input, h_offset):
return input[:, h_offset:]
class CenterCrop(torch.nn.Module):
def forward(self, input):
return center_slice_helper(input, torch.tensor(input.shape[1] - 1))
x = torch.randn(3, 4)
self.run_test(CenterCrop(), x)
@skipIfNoLapack
@skipIfUnsupportedMinOpsetVersion(11)
def test_logdet(self):
class LogDet(torch.nn.Module):
def forward(self, x):
return torch.logdet(x)
x = torch.randn(2, 3, 5, 5)
self.run_test(LogDet(), x)
def test_dim(self):
class DimModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
out = input * 2
out *= out.dim()
return out
empty_input = torch.randn(0, requires_grad=True)
multi_dim_input = torch.randn(1, 2, 3, requires_grad=True)
self.run_test(DimModel(), empty_input)
self.run_test(DimModel(), multi_dim_input)
@skipIfUnsupportedMinOpsetVersion(11)
def test_dim_1(self):
class M(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, poses):
boxes = torch.zeros([poses.shape[0], 2, 4])
batch_boxes = []
for kp_boxes in boxes:
kp_boxes = torchvision.ops.clip_boxes_to_image(kp_boxes, (2, 3))
batch_boxes.append(kp_boxes)
return batch_boxes
dummy_inputs = torch.rand(2, 2, 3)
self.run_test(M(), (dummy_inputs,), input_names=["x"], dynamic_axes={"x": [0]})
@skipIfUnsupportedMinOpsetVersion(12)
@skipDtypeChecking
def test_outer(self):
class Outer(torch.nn.Module):
def forward(self, x, y):
return torch.outer(x, y)
x = torch.arange(1, 5)
y = torch.arange(1, 4)
self.run_test(Outer(), input_args=(x, y))
x = torch.arange(1, 6).to(dtype=torch.float32)
y = torch.arange(1, 4).to(dtype=torch.long)
self.run_test(Outer(), input_args=(x, y))
x = torch.arange(2, 5).to(dtype=torch.float32)
y = torch.arange(2, 4).to(dtype=torch.float64)
self.run_test(Outer(), input_args=(x, y))
x = torch.arange(3, 6).to(dtype=torch.int32)
y = torch.arange(4, 7).to(dtype=torch.long)
self.run_test(Outer(), input_args=(x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_movedim(self):
class MovedimModel(torch.nn.Module):
def forward(self, x):
return (
x.movedim(1, 3),
x.movedim(2, 0),
x.movedim(1, 1),
x.movedim((1, 2, 3), (3, 0, 1)),
x.movedim((0, 1, 2), (1, 2, 3)),
x.movedim((1, 3, 2), (1, 3, 2)),
)
x = torch.randn(5, 3, 4, 2)
self.run_test(MovedimModel(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_moveaxis(self):
# moveaxis is an alias of movedim; thus, mostly copied from `test_movedim`.
class MoveaxisModel(torch.nn.Module):
def forward(self, x):
return (
x.moveaxis(1, 3),
x.moveaxis(2, 0),
x.moveaxis(1, 1),
x.moveaxis((1, 2, 3), (3, 0, 1)),
x.moveaxis((0, 1, 2), (1, 2, 3)),
x.moveaxis((1, 3, 2), (1, 3, 2)),
)
x = torch.randn(5, 3, 4, 2)
self.run_test(MoveaxisModel(), x)
@skipIfUnsupportedMinOpsetVersion(12)
def test_einsum(self):
class EinsumModelBatchDiagonal(torch.nn.Module):
def forward(self, x):
eqn = "...ii ->...i"
return torch.einsum(eqn, x)
for x in [torch.randn(3, 5, 5), torch.randn(3, 5, 5).to(dtype=torch.bool)]:
self.run_test(EinsumModelBatchDiagonal(), input_args=(x,))
class EinsumModelBatchMatmul(torch.nn.Module):
def forward(self, x, y):
eqn = "bij, bjk -> bik"
return torch.einsum(eqn, x, y)
x = torch.randn(5, 2, 3)
y = torch.randn(5, 3, 4)
self.run_test(EinsumModelBatchMatmul(), input_args=(x, y))
class EinsumModelInnerProd(torch.nn.Module):
def forward(self, x, y):
eqn = "i,i"
return torch.einsum(eqn, x, y)
x = torch.randn(5)
y = torch.randn(5)
self.run_test(EinsumModelInnerProd(), input_args=(x, y))
class EinsumModelTranspose(torch.nn.Module):
def forward(self, x):
eqn = "ij->ji"
return torch.einsum(eqn, x)
for x in [torch.randn(3, 4), torch.randn(3, 4).to(dtype=torch.bool)]:
self.run_test(EinsumModelTranspose(), input_args=(x,))
@skipIfUnsupportedMinOpsetVersion(9)
def test_cosine_similarity(self):
x = torch.randn(5, 3, 2)
y = torch.randn(5, 3, 2)
self.run_test(torch.nn.CosineSimilarity(dim=2), input_args=(x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_pairwise_distance(self):
x = torch.randn(5, 3, 2)
y = torch.randn(5, 3, 2)
self.run_test(torch.nn.PairwiseDistance(p=2.0), input_args=(x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_cross(self):
class Cross(torch.nn.Module):
def forward(self, x, y):
return torch.cross(x, y, dim=3), torch.cross(x, y)
x = torch.randn(5, 3, 2, 3)
y = torch.randn(5, 3, 2, 3)
self.run_test(Cross(), input_args=(x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_cdist(self):
class Cdist(torch.nn.Module):
def forward(self, x, y):
return torch.cdist(x, y)
x = torch.randn(5, 3, 3)
y = torch.randn(5, 2, 3)
self.run_test(Cdist(), input_args=(x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_cdist_euclid_dist(self):
class Cdist(torch.nn.Module):
def forward(self, x, y):
return torch.cdist(x, y, p=2.0, compute_mode="use_mm_for_euclid_dist")
x = torch.randn(2, 64, 4)
y = torch.randn(1, 32, 4)
self.run_test(Cdist(), input_args=(x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_cdist_euclid_dist_if_necessary(self):
class Cdist(torch.nn.Module):
def forward(self, x, y):
return torch.cdist(
x, y, p=2.0, compute_mode="use_mm_for_euclid_dist_if_necessary"
)
x = torch.randn(2, 64, 4)
y = torch.randn(1, 32, 4)
self.run_test(Cdist(), input_args=(x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_cdist_no_euclid_dist(self):
class Cdist(torch.nn.Module):
def forward(self, x, y):
return torch.cdist(
x, y, p=2.0, compute_mode="donot_use_mm_for_euclid_dist"
)
x = torch.randn(2, 64, 4)
y = torch.randn(1, 32, 4)
self.run_test(Cdist(), input_args=(x, y))
@skipIfUnsupportedMinOpsetVersion(12)
def test_crossentropyloss(self):
for ignore_index in [-100, 1]:
x = torch.randn(3, 5)
y = torch.empty(3, dtype=torch.long).random_(5)
y[y == 1] = ignore_index
self._crossentropyloss(x, y, ignore_index)
x = torch.randn(3, 5, 2)
y = torch.empty(3, 2, dtype=torch.long).random_(5)
y[y == 1] = ignore_index
self._crossentropyloss(x, y, ignore_index)
x = torch.randn(3, 5, 2, 7)
y = torch.empty(3, 2, 7, dtype=torch.long).random_(5)
y[y == 1] = ignore_index
self._crossentropyloss(x, y, ignore_index)
def _crossentropyloss(self, x, y, ignore_index):
class CrossEntropyLossNone(torch.nn.Module):
def __init__(self, ignore_index):
super().__init__()
if ignore_index == -100:
self.loss = torch.nn.CrossEntropyLoss(reduction="none")
else:
self.loss = torch.nn.CrossEntropyLoss(
reduction="none", ignore_index=ignore_index
)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(CrossEntropyLossNone(ignore_index), input_args=(x, y))
class CrossEntropyLossNoneWeight(torch.nn.Module):
def __init__(self, ignore_index):
super().__init__()
if ignore_index == -100:
self.loss = torch.nn.CrossEntropyLoss(
reduction="none", weight=torch.randn(5)
)
else:
self.loss = torch.nn.CrossEntropyLoss(
reduction="none",
weight=torch.randn(5),
ignore_index=ignore_index,
)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(CrossEntropyLossNoneWeight(ignore_index), input_args=(x, y))
class CrossEntropyLossSum(torch.nn.Module):
def __init__(self, ignore_index):
super().__init__()
if ignore_index == -100:
self.loss = torch.nn.CrossEntropyLoss(reduction="sum")
else:
self.loss = torch.nn.CrossEntropyLoss(
reduction="sum", ignore_index=ignore_index
)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(CrossEntropyLossSum(ignore_index), input_args=(x, y))
class CrossEntropyLossSumWeight(torch.nn.Module):
def __init__(self, ignore_index):
super().__init__()
if ignore_index == -100:
self.loss = torch.nn.CrossEntropyLoss(
reduction="sum", weight=torch.randn(5)
)
else:
self.loss = torch.nn.CrossEntropyLoss(
reduction="sum",
weight=torch.randn(5),
ignore_index=ignore_index,
)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(CrossEntropyLossSumWeight(ignore_index), input_args=(x, y))
class CrossEntropyLossMean(torch.nn.Module):
def __init__(self, ignore_index):
super().__init__()
if ignore_index == -100:
self.loss = torch.nn.CrossEntropyLoss()
else:
self.loss = torch.nn.CrossEntropyLoss(ignore_index=ignore_index)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(CrossEntropyLossMean(ignore_index), input_args=(x, y))
class CrossEntropyLossMeanWeight(torch.nn.Module):
def __init__(self, ignore_index):
super().__init__()
if ignore_index == -100:
self.loss = torch.nn.CrossEntropyLoss(weight=torch.randn(5))
else:
self.loss = torch.nn.CrossEntropyLoss(
weight=torch.randn(5), ignore_index=ignore_index
)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(CrossEntropyLossMeanWeight(ignore_index), input_args=(x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_MSELoss(self):
class MSELoss(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.loss1 = torch.nn.MSELoss(reduction="none")
self.loss2 = torch.nn.MSELoss(reduction="sum")
self.loss3 = torch.nn.MSELoss(reduction="mean")
def forward(self, input, target):
return (
self.loss1(input, target),
self.loss2(input, target),
self.loss3(input, target),
)
x = torch.randn(2, 3, 5)
y = torch.randn(2, 3, 5)
self.run_test(MSELoss(), input_args=(x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_kldiv_loss(self):
x = torch.rand(5).log()
y = torch.rand(5)
self._kldiv_loss(x, y)
x = torch.rand(2, 3, 5).log()
y = torch.rand(2, 3, 5)
self._kldiv_loss(x, y)
x = torch.rand(2, 3, 5, 7).log()
y = torch.rand(2, 3, 5, 7)
self._kldiv_loss(x, y)
def _kldiv_loss(self, x, y):
class KLDivLossNone(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.loss = torch.nn.KLDivLoss(reduction="none", log_target=True)
def forward(self, input, target):
return self.loss(input, target.log())
self.run_test(KLDivLossNone(), input_args=(x, y))
class KLDivLossMean(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.loss = torch.nn.KLDivLoss(reduction="mean", log_target=False)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(KLDivLossMean(), input_args=(x, y))
class KLDivLossSum(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.loss = torch.nn.KLDivLoss(reduction="sum", log_target=True)
def forward(self, input, target):
return self.loss(input, target.log())
self.run_test(KLDivLossSum(), input_args=(x, y))
class KLDivLossBatchMean(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.loss = torch.nn.KLDivLoss(reduction="batchmean", log_target=False)
def forward(self, input, target):
return self.loss(input, target)
self.run_test(KLDivLossBatchMean(), input_args=(x, y))
class KLDivLossMiniBatchMean(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.loss = torch.nn.KLDivLoss(
reduction="batchmean", size_average=False, log_target=True
)
def forward(self, input, target):
return self.loss(input, target.log())
self.run_test(KLDivLossMiniBatchMean(), input_args=(x, y))
@skipIfUnsupportedMinOpsetVersion(12)
def test_nllloss(self):
class NLLModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.loss = torch.nn.NLLLoss(reduction="none")
self.m = torch.nn.LogSoftmax(dim=1)
def forward(self, input, target):
output = self.loss(self.m(2 * input), target)
return output
N, C = 5, 4
input = torch.randn(N, 16)
target = torch.empty(N, dtype=torch.long).random_(0, C)
# using test data containing default ignore_index=-100
target[target == 1] = -100
self.run_test(NLLModel(), (input, target))
@skipIfUnsupportedMinOpsetVersion(12)
def test_nllloss_2d_none(self):
class NLLModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.loss = torch.nn.NLLLoss(reduction="none")
self.conv = torch.nn.Conv2d(16, C, (3, 3))
self.m = torch.nn.LogSoftmax(dim=1)
def forward(self, input, target):
output = self.loss(self.m(self.conv(input)), target)
return output
N, C = 5, 4
input = torch.randn(N, 16, 10, 10)
target = torch.empty(N, 8, 8, dtype=torch.long).random_(0, C)
# using test data containing default ignore_index=-100
target[target == 1] = -100
self.run_test(NLLModel(), (input, target))
@skipIfUnsupportedMinOpsetVersion(12)
def test_nllloss_2d_mean(self):
class NLLModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.loss = torch.nn.NLLLoss(reduction="mean")
self.conv = torch.nn.Conv2d(16, C, (3, 3))
self.m = torch.nn.LogSoftmax(dim=1)
def forward(self, input, target):
output = self.loss(self.m(self.conv(input)), target)
return output
N, C = 5, 4
input = torch.randn(N, 16, 10, 10)
target = torch.empty(N, 8, 8, dtype=torch.long).random_(0, C)
# using test data containing default ignore_index=-100
target[target == 1] = -100
self.run_test(NLLModel(), (input, target))
@skipIfUnsupportedMinOpsetVersion(12)
def test_nllloss_2d_sum(self):
class NLLModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.loss = torch.nn.NLLLoss(reduction="sum")
self.conv = torch.nn.Conv2d(16, C, (3, 3))
self.m = torch.nn.LogSoftmax(dim=1)
def forward(self, input, target):
output = self.loss(self.m(self.conv(input)), target)
return output
N, C = 5, 4
input = torch.randn(N, 16, 10, 10)
target = torch.empty(N, 8, 8, dtype=torch.long).random_(0, C)
# using test data containing default ignore_index=-100
target[target == 1] = -100
self.run_test(NLLModel(), (input, target))
@skipIfUnsupportedMinOpsetVersion(12)
def test_nllloss_2d_mean_weights(self):
class NLLModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.loss = torch.nn.NLLLoss(reduction="mean", weight=torch.randn(C))
self.conv = torch.nn.Conv2d(16, C, (3, 3))
self.m = torch.nn.LogSoftmax(dim=1)
def forward(self, input, target):
output = self.loss(self.m(self.conv(input)), target)
return output
N, C = 5, 4
input = torch.randn(N, 16, 10, 10)
target = torch.empty(N, 8, 8, dtype=torch.long).random_(0, C)
# using test data containing default ignore_index=-100
target[target == 1] = -100
self.run_test(NLLModel(), (input, target))
@skipIfUnsupportedMinOpsetVersion(12)
def test_nllloss_2d_mean_ignore_index(self):
class NLLModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.loss = torch.nn.NLLLoss(reduction="mean", ignore_index=1)
self.conv = torch.nn.Conv2d(16, C, (3, 3))
self.m = torch.nn.LogSoftmax(dim=1)
def forward(self, input, target):
output = self.loss(self.m(self.conv(input)), target)
return output
N, C = 5, 4
input = torch.randn(N, 16, 10, 10)
target = torch.empty(N, 8, 8, dtype=torch.long).random_(0, C)
self.run_test(NLLModel(), (input, target))
@skipIfUnsupportedMinOpsetVersion(12)
def test_nllloss_dynamic_ignore_index(self):
import torch.nn.functional as F
def linear_combination(x, y, epsilon):
return epsilon * x + (1 - epsilon) * y
def reduce_loss(loss, reduction="mean"):
return (
loss.mean()
if reduction == "mean"
else loss.sum()
if reduction == "sum"
else loss
)
class LabelSmoothingCrossEntropy(torch.nn.Module):
def __init__(self, epsilon: float = 0.1, reduction="mean"):
super().__init__()
self.epsilon = epsilon
self.reduction = reduction
def forward(self, preds, target, start_position):
n = preds.size()[-1]
log_preds = F.log_softmax(preds, dim=-1)
ignore_index = start_position.size(1)
nll = F.nll_loss(
log_preds,
target,
reduction=self.reduction,
ignore_index=ignore_index,
)
return nll + start_position.float()
N = 5
preds = torch.randn(N, 16)
target = torch.randint(5, (N,))
start_position = torch.randint(10, (N, N))
self.run_test(LabelSmoothingCrossEntropy(), (preds, target, start_position))
@skipIfUnsupportedMinOpsetVersion(12)
def test_nllloss_2d_mean_ignore_index_weights(self):
class NLLModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.loss = torch.nn.NLLLoss(
reduction="mean", weight=torch.randn(C), ignore_index=1
)
self.conv = torch.nn.Conv2d(16, C, (3, 3))
self.m = torch.nn.LogSoftmax(dim=1)
def forward(self, input, target):
output = self.loss(self.m(self.conv(input)), target)
return output
N, C = 5, 4
input = torch.randn(N, 16, 10, 10)
target = torch.empty(N, 8, 8, dtype=torch.long).random_(0, C)
self.run_test(NLLModel(), (input, target))
@skipIfUnsupportedMinOpsetVersion(12)
def test_binary_cross_entropy_with_logits(self):
x = torch.randn(5)
y = torch.empty(5).random_(2)
self._bce_logits(x, y)
x = torch.randn(3, 4)
y = torch.empty(3, 4).random_(2)
weight = torch.tensor([3])
self._bce_logits_wegiht(x, y, weight)
x = torch.randn(3, 2, 4)
y = torch.empty(3, 2, 4).random_(2)
pos_weight = torch.empty([2, 4]).random_(2)
self._bce_logits_posweight(x, y, pos_weight)
x = torch.randn(3, 3, 4)
y = torch.empty(3, 3, 4).random_(2)
weight = torch.tensor([3])
pos_weight = torch.empty([3, 4]).random_(2)
self._bce_logits_loss_weight_posweight(x, y, weight, pos_weight)
def _bce_logits(self, x, y):
class BCEWithLogitsLossNone(torch.nn.Module):
def forward(self, input, target):
return torch.nn.functional.binary_cross_entropy_with_logits(
input, target, reduction="none"
)
self.run_test(BCEWithLogitsLossNone(), input_args=(x, y))
class BCEWithLogitsLossMean(torch.nn.Module):
def forward(self, input, target):
return torch.nn.functional.binary_cross_entropy_with_logits(
input, target, reduction="mean"
)
self.run_test(BCEWithLogitsLossMean(), input_args=(x, y))
class BCEWithLogitsLossSum(torch.nn.Module):
def forward(self, input, target):
return torch.nn.functional.binary_cross_entropy_with_logits(
input, target, reduction="sum"
)
self.run_test(BCEWithLogitsLossSum(), input_args=(x, y))
def _bce_logits_wegiht(self, x, y, weight):
class BCEWithLogitsLossWegihtNone(torch.nn.Module):
def forward(self, input, target, weight):
return torch.nn.functional.binary_cross_entropy_with_logits(
input, target, weight=weight, reduction="none"
)
self.run_test(BCEWithLogitsLossWegihtNone(), input_args=(x, y, weight))
class BCEWithLogitsLossWegihtMean(torch.nn.Module):
def forward(self, input, target, weight):
return torch.nn.functional.binary_cross_entropy_with_logits(
input, target, weight=weight, reduction="mean"
)
self.run_test(BCEWithLogitsLossWegihtMean(), input_args=(x, y, weight))
class BCEWithLogitsLossWegihtSum(torch.nn.Module):
def forward(self, input, target, weight):
return torch.nn.functional.binary_cross_entropy_with_logits(
input, target, weight=weight, reduction="sum"
)
self.run_test(BCEWithLogitsLossWegihtSum(), input_args=(x, y, weight))
def _bce_logits_posweight(self, x, y, pos_weight):
class BCEWithLogitsLossPosWegihtNone(torch.nn.Module):
def forward(self, input, target, pos_weight):
return torch.nn.functional.binary_cross_entropy_with_logits(
input, target, pos_weight=pos_weight, reduction="none"
)
self.run_test(BCEWithLogitsLossPosWegihtNone(), input_args=(x, y, pos_weight))
class BCEWithLogitsLossPosWegihtMean(torch.nn.Module):
def forward(self, input, target, pos_weight):
return torch.nn.functional.binary_cross_entropy_with_logits(
input, target, pos_weight=pos_weight, reduction="mean"
)
self.run_test(BCEWithLogitsLossPosWegihtMean(), input_args=(x, y, pos_weight))
class BCEWithLogitsLossPosWegihtSum(torch.nn.Module):
def forward(self, input, target, pos_weight):
return torch.nn.functional.binary_cross_entropy_with_logits(
input, target, pos_weight=pos_weight, reduction="sum"
)
self.run_test(BCEWithLogitsLossPosWegihtSum(), input_args=(x, y, pos_weight))
def _bce_logits_loss_weight_posweight(self, x, y, weight, pos_weight):
class BCEWithLogitsLossWeightPosweightNone(torch.nn.Module):
def forward(self, input, target, weight, pos_weight):
return torch.nn.functional.binary_cross_entropy_with_logits(
input,
target,
weight=weight,
pos_weight=pos_weight,
reduction="none",
)
self.run_test(
BCEWithLogitsLossWeightPosweightNone(),
input_args=(x, y, weight, pos_weight),
)
class BCEWithLogitsLossWeightPosweightMean(torch.nn.Module):
def forward(self, input, target, weight, pos_weight):
return torch.nn.functional.binary_cross_entropy_with_logits(
input,
target,
weight=weight,
pos_weight=pos_weight,
reduction="mean",
)
self.run_test(
BCEWithLogitsLossWeightPosweightMean(),
input_args=(x, y, weight, pos_weight),
)
class BCEWithLogitsLossWeightPosweightSum(torch.nn.Module):
def forward(self, input, target, weight, pos_weight):
return torch.nn.functional.binary_cross_entropy_with_logits(
input, target, weight=weight, pos_weight=pos_weight, reduction="sum"
)
self.run_test(
BCEWithLogitsLossWeightPosweightSum(), input_args=(x, y, weight, pos_weight)
)
def test_torch_mm(self):
class M(torch.nn.Module):
def forward(self, mat1, mat2):
mm = torch.mm(mat1, mat2)
return mm
mat1 = torch.randn(2, 3)
mat2 = torch.randn(3, 3)
self.run_test(M(), input_args=(mat1, mat2))
@skipIfUnsupportedMinOpsetVersion(
9
) # Because where op is not supported for opset < 9.
def test_where_with_bool_tensor(self):
class M(torch.nn.Module):
def forward(self, mat1, mat2):
out = torch.where(mat1 > 0, mat1, mat2)
return out
mat1 = torch.randn(2, 3)
mat2 = torch.ones(2, 3)
self.run_test(M(), input_args=(mat1, mat2))
@skipIfUnsupportedMinOpsetVersion(
9
) # Because where op is not supported for opset < 9.
def test_where_with_byte_tensor(self):
class M(torch.nn.Module):
def forward(self, cond, mat1, mat2):
out = torch.where(cond, mat1, mat2)
return out
cond = torch.ones(2, 3, dtype=torch.uint8)
cond[1, 2] = 0
mat1 = torch.randn(2, 3)
mat2 = torch.ones(2, 3)
self.run_test(M(), input_args=(cond, mat1, mat2))
@skipIfUnsupportedMinOpsetVersion(10) # ONNX IsInf op is added in opset 10.
def test_isinf(self):
class M(torch.nn.Module):
def forward(self, x):
return x.isinf()
x = torch.tensor([[1, 2, float("inf")], [2, float("nan"), float("inf")]])
self.run_test(M(), (x,))
@skipIfUnsupportedMinOpsetVersion(10)
def test_isfinite(self):
class M(torch.nn.Module):
def forward(self, x):
return x.isfinite()
x = torch.tensor([[1, 2, float("inf")], [2, float("nan"), -float("inf")]])
self.run_test(M(), (x,))
@skipIfUnsupportedMinOpsetVersion(9) # ONNX IsNaN op is added in opset 9.
def test_isnan(self):
class M(torch.nn.Module):
def forward(self, x):
return x.isnan()
x = torch.tensor([[1, 2, float("inf")], [2, float("nan"), float("inf")]])
self.run_test(M(), (x,))
@skipIfUnsupportedMinOpsetVersion(
10
) # ONNX IsNaN, IsInf op is added in opset 9, 10 respectively.
def test_nan_to_num(self):
class NoParams(torch.nn.Module):
def forward(self, x):
return x.nan_to_num()
x = torch.tensor([[1, 2, float("inf")], [2, float("nan"), -float("inf")]])
xint = torch.ones((2, 4), dtype=torch.int)
xhalf = torch.ones((2, 4), dtype=torch.half)
self.run_test(NoParams(), (x,))
self.run_test(NoParams(), (xint,))
self.run_test(NoParams(), (xhalf,))
class WithParams(torch.nn.Module):
def forward(self, x):
return x.nan_to_num(nan=2.3, posinf=4.5, neginf=6.7)
x = torch.tensor([[1, 2, float("inf")], [2, float("nan"), -float("inf")]])
self.run_test(WithParams(), (x,))
@skipIfUnsupportedMinOpsetVersion(9)
def test_maximum_minimum(self):
class ModelWithNan(torch.nn.Module):
def forward(self, x, y):
return torch.maximum(x, y), torch.minimum(x, y)
x = torch.tensor([-2, -2, float("nan")])
y = torch.rand(1, 3)
self.run_test(ModelWithNan(), (x, y))
@skipIfUnsupportedMinOpsetVersion(12)
def test_minimum_dtypes(self):
class MinimumModel(torch.nn.Module):
def forward(self, x, y):
return torch.minimum(x, y)
x = torch.randn((5, 5), dtype=torch.float16)
y = torch.randn((5, 5), dtype=torch.float)
self.run_test(MinimumModel(), (x, y))
x = torch.randn((5, 5), dtype=torch.float16)
y = torch.randint(10, (5, 5), dtype=torch.int16)
self.run_test(MinimumModel(), (x, y))
x = torch.randint(10, (5, 5), dtype=torch.int16)
y = torch.randint(10, (5, 5), dtype=torch.int32)
self.run_test(MinimumModel(), (x, y))
x = torch.randint(10, (5, 5), dtype=torch.int)
y = torch.full_like(x, True)
self.run_test(MinimumModel(), (x, y))
@skipIfUnsupportedMinOpsetVersion(12)
def test_maximum_dtypes(self):
class MaximumModel(torch.nn.Module):
def forward(self, x, y):
return torch.maximum(x, y)
x = torch.randn((5, 5), dtype=torch.float16)
y = torch.randn((5, 5), dtype=torch.float)
self.run_test(MaximumModel(), (x, y))
x = torch.randn((5, 5), dtype=torch.float16)
y = torch.randint(10, (5, 5), dtype=torch.int16)
self.run_test(MaximumModel(), (x, y))
x = torch.randint(10, (5, 5), dtype=torch.int16)
y = torch.randint(10, (5, 5), dtype=torch.int32)
self.run_test(MaximumModel(), (x, y))
x = torch.randint(10, (5, 5), dtype=torch.int)
y = torch.full_like(x, True)
self.run_test(MaximumModel(), (x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_any(self):
class M(torch.nn.Module):
def forward(self, x):
return x.any()
x = torch.tensor([[True, False], [False, False]])
self.run_test(M(), (x,))
class MDim(torch.nn.Module):
def forward(self, x):
return x.any(dim=1)
x = torch.rand(3, 4).bool()
self.run_test(MDim(), (x,))
class MKeepdim(torch.nn.Module):
def forward(self, x):
return x.any(dim=1, keepdim=True)
x = torch.rand(3, 4).bool()
self.run_test(MKeepdim(), (x,))
@skipIfUnsupportedMinOpsetVersion(9)
def test_all(self):
class M(torch.nn.Module):
def forward(self, x):
return x.all()
x = torch.tensor([[True, False], [False, False]])
self.run_test(M(), (x,))
class MDim(torch.nn.Module):
def forward(self, x):
return x.all(dim=1)
x = torch.rand(3, 4).bool()
self.run_test(MDim(), (x,))
class MKeepdim(torch.nn.Module):
def forward(self, x):
return x.all(dim=1, keepdim=True)
x = torch.rand(3, 4).bool()
self.run_test(MKeepdim(), (x,))
def test_dropout(self):
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.dropout = torch.nn.Dropout(0.3)
def forward(self, x):
dropout = self.dropout(x)
return dropout
x = torch.randn(10, 3, 53)
self.run_test(M(), (x))
def test_rrelu_eval(self):
x = torch.tensor([0.5, -0.5])
self.run_test(torch.nn.RReLU(0.1, 0.3).eval(), x)
def test_shape_constant_fold(self):
class ShapeModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.weight = torch.nn.Buffer(torch.ones(5))
def forward(self, x):
shape = self.weight.shape[0]
return x + shape
x = torch.randn(2, 5)
self.run_test(ShapeModule(), (x,), rtol=1e-3, atol=1e-5)
@skipIfUnsupportedMinOpsetVersion(12)
def test_celu(self):
class Celu(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.celu = torch.nn.CELU(alpha=1.0)
def forward(self, input):
return self.celu(input)
input = torch.randn(2)
self.run_test(Celu(), (input,))
@skipIfUnsupportedMinOpsetVersion(12)
def test_celu_default(self):
class Celu(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.celu = torch.nn.CELU()
def forward(self, input):
return self.celu(input)
input = torch.randn(2)
self.run_test(Celu(), (input,))
@skipIfUnsupportedMinOpsetVersion(12)
def test_celu_alpha(self):
class Celu(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.celu = torch.nn.CELU(alpha=2.0)
def forward(self, input):
return self.celu(input)
input = torch.randn(2)
self.run_test(Celu(), (input,))
@skipIfUnsupportedMinOpsetVersion(12)
def test_celu_cast(self):
class Celu(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.celu = torch.nn.CELU()
def forward(self, input):
return self.celu(input)
input = torch.randn(2, 5, 7, dtype=torch.float64)
self.run_test(Celu(), (input,))
def test_lower_tuple(self):
class TupleModule(torch.nn.Module):
def forward(self, input1: Tensor, input2: Tensor, input3: Tensor) -> Tensor:
a = (input1, input2)
b = a
c = (input1, input2, input3)
for _ in range(5):
d = a[0]
for _ in range(2):
e, f = a
a = (d, f)
f = c[2]
if f.size(0) != input1.size(-1):
g = b[1]
b = (g, f)
else:
k = c[1:]
b = (f, k[0])
m, n = b
c = (input1, n, m)
p, q, r = c
return p + q + r
input1 = torch.randn(2)
input2 = torch.randn(2)
input3 = torch.randn(2)
self.run_test(TupleModule(), (input1, input2, input3))
def test_lower_tuple_2(self):
class TupleModule(torch.nn.Module):
def forward(self, input1: Tensor, input2: Tensor) -> tuple[Tensor, Tensor]:
a = (input1, input2)
for _ in range(5):
c, d = a
a = (c, d)
return a
input1 = torch.randn(2)
input2 = torch.randn(2)
self.run_test(TupleModule(), (input1, input2))
def test_lower_tuple_3(self):
class TupleModule(torch.nn.Module):
def forward(
self,
input1: tuple[Tensor, Tensor],
input2: tuple[Tensor, Tensor],
) -> tuple[tuple[Tensor, Tensor], tuple[Tensor, Tensor]]:
a = input1
b = input2
for _ in range(5):
c, d = a
e, f = b
if c.shape[0] == e.shape[0]:
e = e + c
else:
f = f + d
a = (e, f)
b = (c, d)
return a, b
input1 = (torch.randn(2), torch.randn(2))
input2 = (torch.randn(2), torch.randn(2))
self.run_test(TupleModule(), (input1, input2))
@skipIfUnsupportedMinOpsetVersion(9)
def test_where(self):
class Model(torch.nn.Module):
def forward(self, cond, input, other):
return torch.where(cond, input, other)
x = torch.randint(0, 1, (2, 3, 4), dtype=torch.bool)
y = torch.randn(2, 1, 4)
z = torch.ones(2, 3, 1)
self.run_test(Model(), (x, y, z))
@skipIfUnsupportedMinOpsetVersion(9)
@skipScriptTest() # scripting tests run for opsets > 11. See: test_where_condition_script
def test_where_condition(self):
class Model1(torch.nn.Module):
def forward(self, input):
return torch.stack(torch.where(input > 0.5), dim=1)
x = torch.randint(0, 2, (2, 3, 4), dtype=bool)
self.run_test(Model1(), (x))
class Model2(torch.nn.Module):
def forward(self, input, other):
return torch.stack(torch.where(input > other), dim=1)
x = torch.randint(0, 1, (2, 3, 4), dtype=bool)
y = torch.randint(1, 2, (2, 3, 4), dtype=bool)
self.run_test(Model2(), (x, y))
@skipIfUnsupportedOpsetVersion([13])
@skipIfUnsupportedMinOpsetVersion(11)
def test_where_condition_script(self):
class Model1(torch.nn.Module):
def forward(self, input):
return torch.stack(torch.where(input > 0.5), dim=1)
x = torch.randint(0, 2, (2, 3, 4), dtype=bool)
self.run_test(Model1(), (x))
class Model2(torch.nn.Module):
def forward(self, input, other):
return torch.stack(torch.where(input > other), dim=1)
x = torch.randint(0, 1, (2, 3, 4), dtype=bool)
y = torch.randint(1, 2, (2, 3, 4), dtype=bool)
self.run_test(Model2(), (x, y))
def test_empty_branch(self):
class EmptyBranchModel(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
out = input + 1
if out.dim() > 2:
if out.dim() > 3:
out += 3
else:
pass
else:
pass
return out
x = torch.randn(1, 2, 3, requires_grad=True)
self.run_test(EmptyBranchModel(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_derive_index_scripting(self):
class MyModule(torch.nn.Module):
def forward(self, x: Tensor):
j = []
for idx in range(len(x) - 1, -len(x), -2):
y = x[idx]
j += [x * y]
return j
x = torch.randn(5, 13)
self.run_test(MyModule(), x)
class MyModule(torch.nn.Module):
def forward(self, x: Tensor):
j = []
for idx in range(-len(x), len(x) - 1, 2):
y = x[idx]
j += [x * y]
return j
x = torch.randn(5, 13)
self.run_test(MyModule(), x)
class MyModule(torch.nn.Module):
def forward(self, x: Tensor):
j = []
for idx in range(len(x) - 1, -len(x), -3):
y = x[idx]
j += [x * y]
return j
self.run_test(MyModule(), x)
class MyModule(torch.nn.Module):
def forward(self, x: Tensor):
j = []
for idx in range(-len(x), len(x) - 1, 3):
y = x[idx]
j += [x * y]
return j
self.run_test(MyModule(), x)
@skipScriptTest() # Scripting fails for add lists for opsets < 11. Check test_derive_index_scripting
def test_derive_index(self):
class MyModule(torch.nn.Module):
def forward(self, x: Tensor):
j = []
for idx in range(len(x) - 1, -len(x), -2):
y = x[idx]
j += [x * y]
return j
x = torch.randn(5, 13)
self.run_test(MyModule(), x)
class MyModule(torch.nn.Module):
def forward(self, x: Tensor):
j = []
for idx in range(-len(x), len(x) - 1, 2):
y = x[idx]
j += [x * y]
return j
x = torch.randn(5, 13)
self.run_test(MyModule(), x)
class MyModule(torch.nn.Module):
def forward(self, x: Tensor):
j = []
for idx in range(len(x) - 1, -len(x), -3):
y = x[idx]
j += [x * y]
return j
self.run_test(MyModule(), x)
class MyModule(torch.nn.Module):
def forward(self, x: Tensor):
j = []
for idx in range(-len(x), len(x) - 1, 3):
y = x[idx]
j += [x * y]
return j
self.run_test(MyModule(), x)
@skipIfUnsupportedMinOpsetVersion(11)
def test_if_transpose(self):
class IfModel(torch.nn.Module):
def forward(self, x):
x = x.transpose(0, 1)
if x.size(0) == 2:
return x.transpose(0, 1)
else:
return x
x = torch.randn(2, 3)
self.run_test(
torch.jit.script(IfModel()),
x,
output_names=["output_1"],
dynamic_axes={"output_1": [0, 1]},
)
@skipIfUnsupportedMinOpsetVersion(13)
def test_if_list(self):
class IfModel(torch.nn.Module):
def forward(self, x, y, cond):
res = []
if cond:
res = res + [x]
else:
res = res + [y]
return res
x = torch.randn(2, 3)
y = torch.randn(3, 3)
cond = torch.tensor(1, dtype=torch.bool)
self.run_test(torch.jit.script(IfModel()), (x, y, cond))
@skipIfUnsupportedMinOpsetVersion(13)
def test_if_view(self):
class IfModel(torch.nn.Module):
def forward(self, x, y, cond):
bs, seq = y.shape[:2]
if cond:
res = x.view(bs, seq, -1)
else:
res = y
return res.transpose(1, 2)
x = torch.randn(2, 16, 2, 2)
y = torch.randn(2, 16, 8)
cond = torch.tensor(1, dtype=torch.bool)
self.run_test(
torch.jit.script(IfModel()),
(x, y, cond),
output_names=["output_1"],
dynamic_axes={"output_1": [1]},
)
@skipScriptTest(
skip_before_opset_version=11, reason="dynamic split support added in 11"
)
def test_split_tensor_scalar(self):
class SplitModel(torch.nn.Module):
def forward(self, x):
return torch.split(x, x.size(1))
x = torch.randn(1, 2, 3, requires_grad=True)
self.run_test(SplitModel(), x)
def test_split_tensor_multi(self):
class SplitModel(torch.nn.Module):
def forward(self, x):
return torch.split(x, torch.ones(3))
x = torch.randn(1, 2, 3, requires_grad=True)
def run_model():
SplitModel(x)
self.assertRaises(TypeError, run_model)
@skipIfUnsupportedMinOpsetVersion(9)
def test_embedding(self):
class EmbedModel(torch.nn.Module):
def forward(self, input, emb):
return torch.nn.functional.embedding(input, emb, padding_idx=1)
model = EmbedModel()
x = torch.randint(4, (4,))
x[2] = x[0] = 1
embedding_matrix = torch.rand(10, 3)
self.run_test(model, (x, embedding_matrix))
x = torch.randint(4, (4, 3, 2))
x[2] = 1
x[0][1] = 1
self.run_test(model, (x, embedding_matrix))
self.run_test(
model, (x, embedding_matrix), training=torch.onnx.TrainingMode.TRAINING
)
class EmbedModelWithoutPaddingIdx(torch.nn.Module):
def forward(self, input, emb):
return torch.nn.functional.embedding(input, emb)
model = EmbedModelWithoutPaddingIdx()
x = torch.randint(4, (4, 3, 2))
self.run_test(model, (x, embedding_matrix))
@skipIfUnsupportedMinOpsetVersion(9)
def test_embedding_module(self):
class EmbedModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.emb = torch.nn.Embedding(4, 3, padding_idx=1)
self.emb2 = torch.nn.Embedding(4, 3, padding_idx=1)
with torch.no_grad():
self.emb2.weight[1] = torch.ones(3)
def forward(self, input):
return self.emb(input), self.emb2(input)
model = EmbedModel()
x = torch.randint(4, (4,))
x[2] = x[0] = 1
self.run_test(model, (x,))
x = torch.randint(4, (4, 3, 2))
x[2] = 1
x[0][1] = 1
self.run_test(model, (x,))
class EmbedModelWithoutPaddingIdx(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.emb = torch.nn.Embedding(4, 3)
def forward(self, input):
return self.emb(input)
model = EmbedModelWithoutPaddingIdx()
x = torch.randint(4, (4, 3, 2))
self.run_test(model, (x,))
@skipIfUnsupportedMinOpsetVersion(11)
def test_embedding_renorm(self):
n, d = 7, 5
embedding = torch.nn.Embedding(n, d, max_norm=0.2)
idx = torch.tensor([2, 1])
self.run_test(embedding, idx)
embedding = torch.nn.Embedding(n, d, max_norm=0.5, norm_type=1.0)
idx = torch.tensor([4, 3, 4, 2])
self.run_test(embedding, idx)
def _dispatch_rnn_test(self, name, *args, **kwargs):
if name == "elman":
self._elman_rnn_test(*args, **kwargs)
if name == "lstm":
self._lstm_test(*args, **kwargs)
if name == "gru":
self._gru_test(*args, **kwargs)
def _elman_rnn_test(
self,
layers,
nonlinearity,
bidirectional,
initial_state,
packed_sequence,
dropout,
**extra_kwargs,
):
class ElmanWithStateModel(torch.nn.Module):
def __init__(self, layers, nonlinearity, bidirect, dropout, batch_first):
super().__init__()
self.batch_first = batch_first
self.inner_model = torch.nn.RNN(
RNN_INPUT_SIZE,
RNN_HIDDEN_SIZE,
layers,
nonlinearity=nonlinearity,
bidirectional=bidirectional,
dropout=dropout,
batch_first=batch_first,
)
def forward(self, input: rnn_utils.PackedSequence, hx=None):
return self.inner_model(input, hx)
class ElmanWithoutStateModel(torch.nn.Module):
def __init__(self, layers, nonlinearity, bidirect, dropout, batch_first):
super().__init__()
self.batch_first = batch_first
self.inner_model = torch.nn.RNN(
RNN_INPUT_SIZE,
RNN_HIDDEN_SIZE,
layers,
nonlinearity=nonlinearity,
bidirectional=bidirectional,
dropout=dropout,
batch_first=batch_first,
)
def forward(self, input: rnn_utils.PackedSequence):
return self.inner_model(input)
batch_first = packed_sequence == 2
if initial_state:
model = ElmanWithStateModel(
layers=layers,
bidirect=bidirectional,
nonlinearity=nonlinearity,
dropout=dropout,
batch_first=batch_first,
)
if packed_sequence:
model = (
rnn_model_with_packed_sequence.RnnModelWithPackedSequenceWithState(
model, batch_first
)
)
else:
model = ElmanWithoutStateModel(
layers=layers,
bidirect=bidirectional,
nonlinearity=nonlinearity,
dropout=dropout,
batch_first=batch_first,
)
if packed_sequence:
model = rnn_model_with_packed_sequence.RnnModelWithPackedSequenceWithoutState(
model, batch_first
)
def make_input(batch_size):
seq_lengths = np.random.randint(1, RNN_SEQUENCE_LENGTH + 1, size=batch_size)
seq_lengths = sorted(map(int, seq_lengths), reverse=True)
inputs = [torch.randn(l, RNN_INPUT_SIZE) for l in seq_lengths]
inputs = rnn_utils.pad_sequence(inputs, batch_first=batch_first)
inputs = [inputs]
input_names = ["input"]
directions = 2 if bidirectional else 1
if initial_state:
h0 = torch.randn(directions * layers, batch_size, RNN_HIDDEN_SIZE)
inputs.append(h0)
input_names.append("h0")
if packed_sequence != 0:
inputs.append(torch.IntTensor(seq_lengths))
input_names.append("seq_lengths")
if len(inputs) == 1:
input = inputs[0]
else:
input = tuple(inputs)
return input, input_names
input, input_names = make_input(RNN_BATCH_SIZE)
dynamic_axes = {"input": [0, 1], "seq_lengths": [0]}
if initial_state:
dynamic_axes.update({"h0": [1]})
export_options = {"input_names": input_names, "dynamic_axes": dynamic_axes}
# test that the model still runs with a different batch size
other_input, _ = make_input(RNN_BATCH_SIZE + 1)
self.run_test(
model, input, additional_test_inputs=[other_input], **export_options
)
def _lstm_test(
self,
layers,
bidirectional,
initial_state,
packed_sequence,
dropout,
**extra_kwargs,
):
batch_first = packed_sequence == 2
if packed_sequence:
model = lstm_flattening_result.LstmFlatteningResultWithSeqLength(
RNN_INPUT_SIZE,
RNN_HIDDEN_SIZE,
layers,
bidirectional,
dropout,
batch_first,
)
if initial_state:
model = (
rnn_model_with_packed_sequence.RnnModelWithPackedSequenceWithState(
model, batch_first
)
)
else:
model = rnn_model_with_packed_sequence.RnnModelWithPackedSequenceWithoutState(
model, batch_first
)
else:
model = lstm_flattening_result.LstmFlatteningResultWithoutSeqLength(
RNN_INPUT_SIZE,
RNN_HIDDEN_SIZE,
layers,
bidirectional,
dropout,
batch_first,
)
def make_input(batch_size):
seq_lengths = np.random.randint(1, RNN_SEQUENCE_LENGTH + 1, size=batch_size)
seq_lengths = sorted(map(int, seq_lengths), reverse=True)
inputs = [torch.randn(l, RNN_INPUT_SIZE) for l in seq_lengths]
inputs = rnn_utils.pad_sequence(inputs, batch_first=batch_first)
inputs = [inputs]
input_names = ["input"]
directions = 2 if bidirectional else 1
if initial_state:
h0 = torch.randn(directions * layers, batch_size, RNN_HIDDEN_SIZE)
c0 = torch.randn(directions * layers, batch_size, RNN_HIDDEN_SIZE)
inputs.append((h0, c0))
input_names.append("h0")
input_names.append("c0")
if packed_sequence != 0:
inputs.append(torch.IntTensor(seq_lengths))
input_names.append("seq_lengths")
if len(inputs) == 1:
input = inputs[0]
else:
input = tuple(inputs)
return input, input_names
input, input_names = make_input(RNN_BATCH_SIZE)
dynamic_axes = {"input": [0, 1], "seq_lengths": [0]}
if initial_state:
dynamic_axes.update({"h0": [1], "c0": [1]})
export_options = {"input_names": input_names, "dynamic_axes": dynamic_axes}
# test that the model still runs with a different batch size
other_input, _ = make_input(RNN_BATCH_SIZE + 1)
self.run_test(
model, input, additional_test_inputs=[other_input], **export_options
)
def _gru_test(
self,
layers,
bidirectional,
initial_state,
packed_sequence,
dropout,
**extra_kwargs,
):
class GRUWithStateModel(torch.nn.Module):
def __init__(self, layers, bidirect, dropout, batch_first):
super().__init__()
self.batch_first = batch_first
self.inner_model = torch.nn.GRU(
RNN_INPUT_SIZE,
RNN_HIDDEN_SIZE,
num_layers=layers,
bidirectional=bidirectional,
dropout=dropout,
batch_first=batch_first,
)
def forward(self, input: rnn_utils.PackedSequence, hx):
return self.inner_model(input, hx)
class GRUWithoutStateModel(torch.nn.Module):
def __init__(self, layers, bidirect, dropout, batch_first):
super().__init__()
self.batch_first = batch_first
self.inner_model = torch.nn.GRU(
RNN_INPUT_SIZE,
RNN_HIDDEN_SIZE,
num_layers=layers,
bidirectional=bidirectional,
dropout=dropout,
batch_first=batch_first,
)
def forward(self, input: rnn_utils.PackedSequence):
return self.inner_model(input)
class GRUNoSeqLengthWithoutStateModel(torch.nn.Module):
def __init__(self, layers, bidirect, dropout, batch_first):
super().__init__()
self.batch_first = batch_first
self.inner_model = torch.nn.GRU(
RNN_INPUT_SIZE,
RNN_HIDDEN_SIZE,
num_layers=layers,
bidirectional=bidirectional,
dropout=dropout,
batch_first=batch_first,
)
def forward(self, input):
return self.inner_model(input)
class GRUNoSeqLengthWithStateModel(torch.nn.Module):
def __init__(self, layers, bidirect, dropout, batch_first):
super().__init__()
self.batch_first = batch_first
self.inner_model = torch.nn.GRU(
RNN_INPUT_SIZE,
RNN_HIDDEN_SIZE,
num_layers=layers,
bidirectional=bidirectional,
dropout=dropout,
batch_first=batch_first,
)
def forward(self, input, hx):
return self.inner_model(input, hx)
batch_first = packed_sequence == 2
if packed_sequence:
if initial_state:
model = GRUWithStateModel(
layers=layers,
bidirect=bidirectional,
dropout=dropout,
batch_first=batch_first,
)
model = (
rnn_model_with_packed_sequence.RnnModelWithPackedSequenceWithState(
model, batch_first
)
)
else:
model = GRUWithoutStateModel(
layers=layers,
bidirect=bidirectional,
dropout=dropout,
batch_first=batch_first,
)
model = rnn_model_with_packed_sequence.RnnModelWithPackedSequenceWithoutState(
model, batch_first
)
else:
if initial_state:
model = GRUNoSeqLengthWithStateModel(
layers=layers,
bidirect=bidirectional,
dropout=dropout,
batch_first=batch_first,
)
else:
model = GRUNoSeqLengthWithoutStateModel(
layers=layers,
bidirect=bidirectional,
dropout=dropout,
batch_first=batch_first,
)
def make_input(batch_size):
seq_lengths = np.random.randint(1, RNN_SEQUENCE_LENGTH + 1, size=batch_size)
seq_lengths = sorted(map(int, seq_lengths), reverse=True)
inputs = [torch.randn(l, RNN_INPUT_SIZE) for l in seq_lengths]
inputs = rnn_utils.pad_sequence(inputs, batch_first=batch_first)
inputs = [inputs]
input_names = ["input"]
directions = 2 if bidirectional else 1
if initial_state:
h0 = torch.randn(directions * layers, batch_size, RNN_HIDDEN_SIZE)
inputs.append(h0)
input_names.append("h0")
if packed_sequence != 0:
inputs.append(torch.IntTensor(seq_lengths))
input_names.append("seq_lengths")
if len(inputs) == 1:
input = inputs[0]
else:
input = tuple(inputs)
return input, input_names
input, input_names = make_input(RNN_BATCH_SIZE)
dynamic_axes = {"input": [0, 1], "seq_lengths": [0]}
if initial_state:
dynamic_axes.update({"h0": [1]})
export_options = {"input_names": input_names, "dynamic_axes": dynamic_axes}
# test that the model still runs with a different batch size
other_input, _ = make_input(RNN_BATCH_SIZE + 1)
self.run_test(
model, input, additional_test_inputs=[other_input], **export_options
)
@skipIfUnsupportedMinOpsetVersion(10)
def test_fake_quantize_per_tensor(self):
class FakeQuantizePerTensorModel(torch.nn.Module):
def forward(self, input):
scale = 1.0 / 127
zero_point = 0
quant_min = -128
quant_max = 127
return torch.fake_quantize_per_tensor_affine(
input, scale, zero_point, quant_min, quant_max
)
x = torch.randn(6, 4, 3, 3)
self.run_test(FakeQuantizePerTensorModel(), (x))
@skipIfUnsupportedMinOpsetVersion(13)
def test_fake_quantize_per_tensor_dynamic_scale_zeropoint(self):
class FakeQuantizePerTensorModel(torch.nn.Module):
def forward(self, input, scale, zero_point):
quant_min = -128
quant_max = 127
return torch.fake_quantize_per_tensor_affine(
input, scale, zero_point, quant_min, quant_max
)
x = torch.randn(6, 4, 3, 3)
scale = torch.tensor(1.0 / 127)
zero_point = torch.tensor(0)
self.run_test(FakeQuantizePerTensorModel(), (x, scale, zero_point))
@skipIfUnsupportedMinOpsetVersion(13)
def test_fake_quantize_per_channel(self):
class FakeQuantizePerChannelModel(torch.nn.Module):
def forward(self, input):
amax = torch.ones(4)
scale = amax / 127.0
zero_point = torch.zeros_like(amax, dtype=torch.int)
# Quantize twice to test different branches
y = torch.fake_quantize_per_channel_affine(
input, scale, zero_point, 1, 0, 255
)
return torch.fake_quantize_per_channel_affine(
y, scale, zero_point, 1, -128, 127
)
x = torch.randn(6, 4, 3, 3)
self.run_test(FakeQuantizePerChannelModel(), (x))
@skipIfUnsupportedMinOpsetVersion(13)
# RuntimeError: Can't redefine method:
# forward on class: __torch__.torch.nn.modules.linear.Linear
@skipScriptTest()
def test_fake_quantize_activation(self):
from torch.ao import quantization
m = torch.nn.Linear(1, 1)
m.qconfig = quantization.QConfig(
activation=quantization.default_fake_quant,
weight=quantization.default_per_channel_weight_fake_quant,
)
quantization.prepare_qat(m.train(), inplace=True)
m.apply(quantization.enable_observer)
m.apply(quantization.enable_fake_quant)
for module in m.modules():
if isinstance(module, quantization.FakeQuantize):
module.calculate_qparams()
m.apply(quantization.disable_observer)
m.eval()
# Fake quantize activation is a special case, as it restricts quantized range to be (0, 127),
# while standard 8bit quantization range is (-128, 127) or (0, 255).
# Set fixed weight, bias and inputs to test if ONNX handles the overflow correctly.
m.weight = torch.nn.Parameter(torch.tensor([[1.0], [1.0], [1.0]]))
m.bias = torch.nn.Parameter(torch.tensor([0.0]))
x = torch.tensor([[150.0], [127.0], [-5.0]])
self.run_test(m, x)
def test_batchnorm_training(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.bn1 = torch.nn.BatchNorm2d(3, affine=False)
self.cv1 = torch.nn.Conv2d(3, 3, 10)
self.bn2 = torch.nn.BatchNorm2d(3, affine=True)
self.cv2 = torch.nn.Conv2d(3, 3, 10)
self.bn3 = torch.nn.BatchNorm2d(3, affine=False)
def forward(self, x):
x = self.bn1(x)
x = self.cv1(x)
x = self.bn2(x)
x = self.cv2(x)
x = self.bn3(x)
return x
x = torch.randn(10, 3, 20, 20) * 2
model_export = MyModule()
self.run_test(
model_export,
(x,),
training=torch.onnx.TrainingMode.TRAINING,
rtol=1e-3,
atol=1e-5,
)
model_export.train()
self.run_test(
model_export,
(x,),
training=torch.onnx.TrainingMode.PRESERVE,
rtol=1e-3,
atol=1e-5,
)
def test_batchnorm_training_mode_fix_layer(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.bn1 = torch.nn.BatchNorm2d(3, affine=True)
self.cv1 = torch.nn.Conv2d(3, 3, 10)
self.bn2 = torch.nn.BatchNorm2d(3, affine=False)
self.cv2 = torch.nn.Conv2d(3, 3, 10)
self.bn3 = torch.nn.BatchNorm2d(3, affine=True)
self.bn3.eval()
def forward(self, x):
x = self.bn1(x)
x = self.cv1(x)
x = self.bn2(x)
x = self.cv2(x)
x = self.bn3(x)
return x
x = torch.randn(10, 3, 128, 128)
model_export = MyModule()
self.run_test(
model_export,
(x,),
training=torch.onnx.TrainingMode.TRAINING,
rtol=1e-3,
atol=1e-5,
)
model_export.train()
self.run_test(
model_export,
(x,),
training=torch.onnx.TrainingMode.PRESERVE,
rtol=1e-3,
atol=1e-5,
)
def test_batchnorm_eval_mode_train_layer(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.bn1 = torch.nn.BatchNorm2d(3, affine=True)
self.cv1 = torch.nn.Conv2d(3, 3, 10)
self.bn2 = torch.nn.BatchNorm2d(3, affine=False)
self.cv2 = torch.nn.Conv2d(3, 3, 10)
self.bn3 = torch.nn.BatchNorm2d(3, affine=True)
self.bn3.train()
def forward(self, x):
x = self.bn1(x)
x = self.cv1(x)
x = self.bn2(x)
x = self.cv2(x)
x = self.bn3(x)
return x
x = torch.randn(10, 3, 128, 128)
model_export = MyModule()
self.run_test(
model_export,
(x,),
training=torch.onnx.TrainingMode.EVAL,
rtol=1e-3,
atol=1e-5,
)
model_export.eval()
self.run_test(
model_export,
(x,),
training=torch.onnx.TrainingMode.PRESERVE,
rtol=1e-3,
atol=1e-5,
)
def test_instancenorm_training(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.in1 = torch.nn.InstanceNorm2d(3, affine=True)
self.cv1 = torch.nn.Conv2d(3, 3, 10)
self.in2 = torch.nn.InstanceNorm2d(3, affine=False)
self.cv2 = torch.nn.Conv2d(3, 3, 10)
self.in3 = torch.nn.InstanceNorm2d(3, affine=True)
def forward(self, x):
x = self.in1(x)
x = self.cv1(x)
x = self.in2(x)
x = self.cv2(x)
x = self.in3(x)
return x
x = torch.randn(10, 3, 128, 128)
model_export = MyModule()
self.run_test(
model_export,
(x,),
training=torch.onnx.TrainingMode.TRAINING,
rtol=1e-3,
atol=1e-5,
)
model_export.train()
self.run_test(
model_export,
(x,),
training=torch.onnx.TrainingMode.PRESERVE,
rtol=1e-3,
atol=1e-5,
)
def test_instancenorm_training_mode_fix_layer(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.in1 = torch.nn.InstanceNorm2d(3, affine=True)
self.cv1 = torch.nn.Conv2d(3, 3, 10)
self.in2 = torch.nn.InstanceNorm2d(3, affine=False)
self.cv2 = torch.nn.Conv2d(3, 3, 10)
self.in3 = torch.nn.InstanceNorm2d(3, affine=True)
self.in3.eval()
def forward(self, x):
x = self.in1(x)
x = self.cv1(x)
x = self.in2(x)
x = self.cv2(x)
x = self.in3(x)
return x
x = torch.randn(10, 3, 128, 128)
model_export = MyModule()
self.run_test(
model_export,
(x,),
training=torch.onnx.TrainingMode.TRAINING,
rtol=1e-3,
atol=1e-5,
)
model_export.train()
self.run_test(
model_export,
(x,),
training=torch.onnx.TrainingMode.PRESERVE,
rtol=1e-3,
atol=1e-5,
)
def test_instancenorm_eval_mode_train_layer(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.in1 = torch.nn.InstanceNorm2d(8, affine=True)
self.cv1 = torch.nn.Conv2d(8, 8, 10)
self.in2 = torch.nn.InstanceNorm2d(8, affine=False)
self.cv2 = torch.nn.Conv2d(8, 8, 10)
self.in3 = torch.nn.InstanceNorm2d(8, affine=True)
self.in3.train()
def forward(self, x):
x = self.in1(x)
x = self.cv1(x)
x = self.in2(x)
x = self.cv2(x)
x = self.in3(x)
return x
x = torch.randn(10, 8, 128, 128)
model_export = MyModule()
self.run_test(
model_export,
(x,),
training=torch.onnx.TrainingMode.EVAL,
rtol=1e-3,
atol=1e-5,
)
model_export.eval()
self.run_test(
model_export,
(x,),
training=torch.onnx.TrainingMode.PRESERVE,
rtol=1e-3,
atol=1e-5,
)
@skipIfUnsupportedMinOpsetVersion(12)
def test_dropout_training(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.dropout = torch.nn.Dropout(0.4)
def forward(self, x):
dropout = self.dropout(x)
return dropout
model = MyModule()
x = torch.randn(10)
model.train()
model_onnx = io.BytesIO()
torch.onnx.export(
model,
x,
model_onnx,
opset_version=self.opset_version,
do_constant_folding=False,
training=torch.onnx.TrainingMode.TRAINING,
dynamo=False,
)
ort_sess = verification._ort_session(model_onnx)
ort_outs = verification._run_onnx(ort_sess, (x,))
assert not torch.all(torch.eq(x, torch.from_numpy(ort_outs[0])))
script_model = torch.jit.script(model)
output = model(x)
model_onnx = io.BytesIO()
torch.onnx.export(
model,
x,
model_onnx,
opset_version=self.opset_version,
do_constant_folding=False,
training=torch.onnx.TrainingMode.TRAINING,
dynamo=False,
)
ort_outs = verification._run_onnx(ort_sess, (x,))
assert not torch.all(torch.eq(x, torch.from_numpy(ort_outs[0])))
@skipIfUnsupportedMinOpsetVersion(12)
def test_dropout_training_zero(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.dropout = torch.nn.Dropout(0.5)
def forward(self, x):
dropout = self.dropout(x)
return dropout
model = MyModule()
# ensure there are no zeros in the input
x = torch.randn(10, 3, 128, 128)
y = x.numpy()
y_mask = np.where(y == 0, 1, y)
input = torch.from_numpy(y_mask)
nb_elements = torch.numel(input)
model.train()
model_onnx = io.BytesIO()
torch.onnx.export(
model,
x,
model_onnx,
opset_version=self.opset_version,
do_constant_folding=False,
training=torch.onnx.TrainingMode.TRAINING,
dynamo=False,
)
ort_sess = verification._ort_session(model_onnx)
ort_outs = verification._run_onnx(ort_sess, (x,))
y = model(input)
output = y.cpu().numpy()
ort_mask = np.where(ort_outs[0] != 0, 1, 0)
pyt_mask = np.where(output != 0, 1, 0)
ratio_pytorch = np.sum(pyt_mask) / nb_elements
ratio_ort = np.sum(ort_mask) / nb_elements
np.testing.assert_allclose(ratio_pytorch, ratio_ort, rtol=0.01, atol=0.01)
script_model = torch.jit.script(model)
y = model(input)
output = y.cpu().numpy()
model_onnx = io.BytesIO()
torch.onnx.export(
model,
x,
model_onnx,
opset_version=self.opset_version,
do_constant_folding=False,
training=torch.onnx.TrainingMode.TRAINING,
dynamo=False,
)
ort_sess = verification._ort_session(model_onnx)
ort_outs = verification._run_onnx(ort_sess, (x,))
ort_mask = np.where(ort_outs[0] != 0, 1, 0)
pyt_mask = np.where(output != 0, 1, 0)
ratio_pytorch = np.sum(pyt_mask) / nb_elements
ratio_ort = np.sum(ort_mask) / nb_elements
np.testing.assert_allclose(ratio_pytorch, ratio_ort, rtol=0.01, atol=0.01)
def test_conv_bn(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = torch.nn.Conv2d(
3, 16, kernel_size=1, stride=2, padding=3, bias=True
)
self.bn = torch.nn.BatchNorm2d(16, affine=True)
def forward(self, x):
x = self.conv(x)
bn = self.bn(x)
return bn
model_export = MyModule()
x = torch.randn(10, 3, 128, 128)
self.run_test(model_export, (x,), training=torch.onnx.TrainingMode.EVAL)
self.run_test(
model_export,
(x,),
training=torch.onnx.TrainingMode.TRAINING,
rtol=1e-3,
atol=1e-5,
)
def test_multiple_conv_bn(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv1 = torch.nn.Conv2d(
3, 64, kernel_size=7, stride=2, padding=3, bias=False
)
self.conv2 = torch.nn.Conv2d(
64, 2, kernel_size=1, stride=1, padding=0, bias=False
)
self.conv3 = torch.nn.Conv2d(
2, 2, kernel_size=3, stride=1, padding=1, bias=False
)
self.bn = torch.nn.BatchNorm2d(64)
self.bn2 = torch.nn.BatchNorm2d(2)
self.relu = torch.nn.ReLU(inplace=True)
self.maxpool = torch.nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
def forward(self, x):
x = self.conv1(x)
x = self.bn(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.relu(x)
x = self.conv3(x)
x = self.bn2(x)
x = self.relu(x)
return x
model_export = MyModule()
x = torch.randn(2, 3, 224, 224)
self.run_test(
model_export,
(x,),
training=torch.onnx.TrainingMode.TRAINING,
rtol=1e-3,
atol=1e-5,
)
self.run_test(model_export, (x,), training=torch.onnx.TrainingMode.EVAL)
@skipIfUnsupportedMinOpsetVersion(11)
def test_nms(self):
num_boxes = 100
boxes = torch.rand(num_boxes, 4)
boxes[:, 2:] += boxes[:, :2]
scores = torch.randn(num_boxes)
class Module(torch.nn.Module):
def forward(self, boxes, scores):
return torchvision.ops.nms(boxes, scores, 0.5)
self.run_test(Module(), (boxes, scores))
@skipIfUnsupportedMinOpsetVersion(11)
def test_batched_nms(self):
num_boxes = 100
boxes = torch.rand(num_boxes, 4)
boxes[:, 2:] += boxes[:, :2]
scores = torch.randn(num_boxes)
idxs = torch.randint(0, 5, size=(num_boxes,))
class Module(torch.nn.Module):
def forward(self, boxes, scores, idxs):
return torchvision.ops.batched_nms(boxes, scores, idxs, 0.5)
self.run_test(Module(), (boxes, scores, idxs))
@skipIfUnsupportedMinOpsetVersion(11)
@skipScriptTest()
def test_clip_boxes_to_image(self):
boxes = torch.randn(5, 4) * 500
boxes[:, 2:] += boxes[:, :2]
size = torch.randn(200, 300)
size_2 = torch.randn(300, 400)
class Module(torch.nn.Module):
def forward(self, boxes, size):
shape = (size.shape[0], size.shape[1])
return torchvision.ops.boxes.clip_boxes_to_image(boxes, shape)
self.run_test(
Module(),
(boxes, size),
input_names=["boxes", "size"],
dynamic_axes={"size": [0, 1]},
additional_test_inputs=[(boxes, size), (boxes, size_2)],
)
@skipScriptTest(
reason="Conditioning on input type via prim::isinstance unsupported in ONNX"
)
@skipIfUnsupportedMinOpsetVersion(11)
def test_roi_align(self):
x = torch.rand(1, 1, 10, 10, dtype=torch.float32)
single_roi = torch.tensor([[0, 0, 0, 4, 4]], dtype=torch.float32)
model = torchvision.ops.RoIAlign((5, 5), 1.0, 2)
self.run_test(model, (x, single_roi))
@skipScriptTest(
reason="Conditioning on input type via prim::isinstance unsupported in ONNX"
)
@skipIfUnsupportedMinOpsetVersion(16)
def test_roi_align_aligned(self):
x = torch.rand(1, 1, 10, 10, dtype=torch.float32)
single_roi = torch.tensor([[0, 1.5, 1.5, 3, 3]], dtype=torch.float32)
model1 = torchvision.ops.RoIAlign((5, 5), 1.0, 2, aligned=True)
self.run_test(model1, (x, single_roi))
x = torch.rand(1, 1, 10, 10, dtype=torch.float32)
single_roi = torch.tensor([[0, 0.2, 0.3, 4.5, 3.5]], dtype=torch.float32)
model2 = torchvision.ops.RoIAlign((5, 5), 0.5, 3, aligned=True)
self.run_test(model2, (x, single_roi))
x = torch.rand(1, 1, 10, 10, dtype=torch.float32)
single_roi = torch.tensor([[0, 0.2, 0.3, 4.5, 3.5]], dtype=torch.float32)
model3 = torchvision.ops.RoIAlign((5, 5), 1.8, 2, aligned=True)
self.run_test(model3, (x, single_roi))
x = torch.rand(1, 1, 10, 10, dtype=torch.float32)
single_roi = torch.tensor([[0, 0.2, 0.3, 4.5, 3.5]], dtype=torch.float32)
model4 = torchvision.ops.RoIAlign((2, 2), 2.5, 0, aligned=True)
self.run_test(model4, (x, single_roi))
@skipScriptTest(
reason="Conditioning on input type via prim::isinstance unsupported in ONNX"
)
@skipIfUnsupportedMinOpsetVersion(11)
def test_roi_pool(self):
x = torch.rand(1, 1, 10, 10, dtype=torch.float32)
rois = torch.tensor([[0, 0, 0, 4, 4]], dtype=torch.float32)
pool_h = 5
pool_w = 5
model = torchvision.ops.RoIPool((pool_h, pool_w), 2.0)
self.run_test(model, (x, rois))
@skipIfUnsupportedMinOpsetVersion(11)
def test_resize_images(self):
class TransformModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.transform = _init_test_generalized_rcnn_transform()
def forward(self, images):
return self.transform.resize(images, None)[0]
input = torch.rand(3, 10, 20)
input_test = torch.rand(3, 100, 150)
self.run_test(
TransformModule(),
(input,),
input_names=["input1"],
dynamic_axes={"input1": [0, 1, 2]},
additional_test_inputs=[(input,), (input_test,)],
)
@skipIfUnsupportedMinOpsetVersion(11)
@skipScriptTest()
def test_transform_images(self):
class TransformModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.transform = _init_test_generalized_rcnn_transform()
def forward(self, images: list[Tensor]):
return self.transform(images)[0].tensors
input = torch.rand(3, 100, 200), torch.rand(3, 200, 200)
input_test = torch.rand(3, 100, 200), torch.rand(3, 200, 200)
self.run_test(
TransformModule(),
(input,),
additional_test_inputs=[(input,), (input_test,)],
)
def get_features(self, images):
s0, s1 = images.shape[-2:]
features = [
("0", torch.rand(2, 256, s0 // 4, s1 // 4)),
("1", torch.rand(2, 256, s0 // 8, s1 // 8)),
("2", torch.rand(2, 256, s0 // 16, s1 // 16)),
("3", torch.rand(2, 256, s0 // 32, s1 // 32)),
("4", torch.rand(2, 256, s0 // 64, s1 // 64)),
]
features = OrderedDict(features)
return features
@skipIfUnsupportedMinOpsetVersion(11)
@skipScriptTest()
def test_rpn(self):
class RPNModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.rpn = _init_test_rpn()
def forward(self, images, features: dict[str, Tensor]):
images_m = torchvision.models.detection.image_list.ImageList(
images, [(i.shape[-1], i.shape[-2]) for i in images]
)
return self.rpn(images_m, features)
images = torch.rand(2, 3, 150, 150)
features = self.get_features(images)
images2 = torch.rand(2, 3, 80, 80)
test_features = self.get_features(images2)
model = RPNModule()
model.eval()
model(images, features)
self.run_test(
model,
(images, features),
input_names=["input1", "input2", "input3", "input4", "input5", "input6"],
dynamic_axes={
"input1": [0, 1, 2, 3],
"input2": [0, 1, 2, 3],
"input3": [0, 1, 2, 3],
"input4": [0, 1, 2, 3],
"input5": [0, 1, 2, 3],
"input6": [0, 1, 2, 3],
},
additional_test_inputs=[(images, features), (images2, test_features)],
# dict_check=False,
)
@skipIfUnsupportedMaxOpsetVersion(15) # TODO: Opset 16 RoiAlign result mismatch
@skipIfUnsupportedMinOpsetVersion(11)
@skipScriptTest()
def test_multi_scale_roi_align(self):
class TransformModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.model = torchvision.ops.MultiScaleRoIAlign(
["feat1", "feat2"], 3, 2
)
self.image_sizes = [(512, 512)]
def forward(self, input: dict[str, Tensor], boxes: list[Tensor]) -> Tensor:
return self.model(input, boxes, self.image_sizes)
i = OrderedDict()
i["feat1"] = torch.rand(1, 5, 64, 64)
i["feat2"] = torch.rand(1, 5, 16, 16)
boxes = torch.rand(6, 4) * 256
boxes[:, 2:] += boxes[:, :2]
i1 = OrderedDict()
i1["feat1"] = torch.rand(1, 5, 64, 64)
i1["feat2"] = torch.rand(1, 5, 16, 16)
boxes1 = torch.rand(6, 4) * 256
boxes1[:, 2:] += boxes1[:, :2]
self.run_test(
TransformModule(),
(
i,
[boxes],
),
additional_test_inputs=[
(
i,
[boxes],
),
(
i1,
[boxes1],
),
],
)
def test_set_(self):
class M(torch.nn.Module):
def forward(self, x, y):
x.set_(y)
return x
x = torch.ones(2, 3)
y = torch.randn(4, 6)
self.run_test(M(), (x, y), remained_onnx_input_idx=[1])
y2 = torch.randn(5, 2)
self.run_test(
M(),
(x, y),
remained_onnx_input_idx=[1],
input_names=["x", "y"],
dynamic_axes={"x": [0, 1], "y": [0, 1]},
additional_test_inputs=[(y, y2)],
)
@skipIfUnsupportedMinOpsetVersion(9)
def test_set_attr_modules(self):
class InnerModule2(torch.nn.Module):
def __init__(self, embedding_dim):
super().__init__()
self.weights = InnerModule2.get_embedding(embedding_dim)
self._float_tensor = torch.nn.Buffer(torch.FloatTensor(1))
self.const = 2
@staticmethod
def get_embedding(embedding_dim: int):
emb = 4 / ((embedding_dim // 2) - 1)
emb = torch.exp(
torch.arange((embedding_dim // 2), dtype=torch.float) * -emb
)
return emb
def forward(self, input, incremental_state: Optional[Tensor] = None):
bsz, seq_len = input.shape[0], input.shape[1]
self.const = 3
if self.weights is None:
self.weights = InnerModule.get_embedding(self.embedding_dim)
self.weights = self.weights.to(self._float_tensor)
self.weights = self.weights * self.const
if incremental_state is not None:
pos = seq_len
return self.weights[1 + pos, :].expand(bsz, 1, -1)
return self.weights.index_select(
0, torch.ones((bsz * seq_len), dtype=torch.int64)
).view(bsz, seq_len, -1)
class InnerModule(torch.nn.Module):
def __init__(self, embedding_dim):
super().__init__()
self.weights = InnerModule.get_embedding(embedding_dim)
self.module = InnerModule2(embedding_dim=8)
@staticmethod
def get_embedding(embedding_dim: int):
emb = 4 / ((embedding_dim // 2) - 1)
emb = torch.exp(
torch.arange((embedding_dim // 2), dtype=torch.float) * -emb
)
return emb
def forward(self, x):
return self.module(x) + self.weights
class Module(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.module = InnerModule(embedding_dim=8)
def forward(self, x):
return self.module(x)
x = torch.randn(3, 256)
self.run_test(Module(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(Module(), (x,), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_set_attr_modules_2(self):
class InnerModule(torch.nn.Module):
def __init__(self, embedding_dim):
super().__init__()
self.embedding_dim = embedding_dim
self.const = 2.5
self.weights = InnerModule.get_embedding(self.embedding_dim)
self._float_tensor = torch.nn.Buffer(torch.FloatTensor(1))
@staticmethod
def get_embedding(embedding_dim: int):
emb = 4 / ((embedding_dim // 2) - 1)
emb = torch.exp(
torch.arange((embedding_dim // 2), dtype=torch.float) * -emb
)
return emb
def forward(self, input, incremental_state: Optional[Tensor] = None):
bsz, seq_len = input.shape[0], input.shape[1]
self.const = 1.5
self.weights = InnerModule.get_embedding(self.embedding_dim)
return (
self.weights.index_select(
0, torch.ones((bsz * seq_len), dtype=torch.int64)
).view(bsz, seq_len, -1)
) * self.const
class Module(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.module = InnerModule(embedding_dim=8)
def forward(self, x):
return self.module(x)
x = torch.randn(3, 256)
self.run_test(Module(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(Module(), (x,), remained_onnx_input_idx=[])
def test_set_attr(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = torch.nn.Conv1d(3, 10, 2)
self.b = False
def forward(self, box_regression, weight):
self.b = True
self.conv.weight = weight
w = torch.softmax(self.conv.weight, dim=0)
self.conv.weight = w + w
if self.b:
return box_regression + self.conv.weight
else:
return box_regression - self.conv.weight
model = torch.jit.script(MyModule())
weight = torch.ones(3, 2)
box_regression = torch.randn(3, 2)
self.run_test(model, (box_regression, weight))
@skipIfUnsupportedMinOpsetVersion(11)
def test_set_attr_2(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = torch.nn.Conv1d(10, 3, 3)
self.conv.bias = torch.nn.Parameter(torch.zeros(3, 10, 3))
def set_cell_anchors(self, anchors):
if self.conv.bias is not None:
b = self.conv.bias
assert b is not None
self.conv.bias = anchors + b
elif self.conv.weight is not None:
self.conv.weight = torch.randn(3, 10)
self.conv.bias = self.conv.weight[:]
def forward(self, anchors) -> Optional[Tensor]:
self.set_cell_anchors(anchors)
return self.conv.bias
model = torch.jit.script(MyModule())
anchors = torch.ones(3, 10, 3)
self.run_test(model, (anchors))
@skipIfUnsupportedMinOpsetVersion(11)
def test_set_attr_3(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = torch.nn.Conv1d(10, 3, 3)
self.conv.weight = torch.nn.Parameter(torch.zeros(3, 10))
self.conv.bias = torch.nn.Parameter(torch.zeros(3, 10, 3))
def set_cell_anchors(self, anchors, boxes):
self.conv.weight = torch.ones(3, 10)
if self.conv.bias is not None:
self.conv.bias = torch.randn(3, 10, 3)
self.conv.weight = anchors + self.conv.weight
boxes[:] = torch.zeros(2, 3)
def forward(self, anchors) -> tuple[Tensor, Tensor]:
boxes = torch.ones(2, 2, 3)
self.set_cell_anchors(anchors, boxes)
if self.conv.bias is not None:
return self.conv.weight, boxes
return anchors, boxes
model = torch.jit.script(MyModule())
anchors = torch.rand(3, 10)
self.run_test(model, (anchors))
@skipIfUnsupportedMinOpsetVersion(11)
def test_set_attr_4(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = torch.nn.Conv1d(10, 3, 3)
self.conv.bias = torch.nn.Parameter(torch.zeros(3, 10, 3))
def set_cell_anchors(self, anchors):
self.conv.weight = torch.zeros(10, 3)
if self.conv.bias is not None:
w = self.conv.bias
assert w is not None
self.conv.bias = anchors + w
else:
self.conv.bias = torch.ones(3, 10, 3)
def forward(self, feature_maps, anchors) -> tuple[Tensor, Tensor]:
self.set_cell_anchors(anchors)
result = []
if self.conv.bias is not None:
a = self.conv.bias
assert a is not None
result += [a]
result += [feature_maps]
return result[0], result[1]
model = torch.jit.script(MyModule())
x = torch.rand(5, 11, 30)
anchors = torch.ones(3, 10, 3)
self.run_test(model, (x, anchors))
@skipIfUnsupportedMinOpsetVersion(11)
def test_set_attr_5(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = torch.nn.Conv1d(10, 3, 3)
self.conv.bias = torch.nn.Parameter(torch.zeros(3, 10, 3))
def set_cell_anchors(self, anchors):
self.conv.weight = torch.arange(10)
for i in range(10):
if i == 3:
for _ in range(10):
w = self.conv.weight
self.conv.weight = torch.arange(10) + w
self.conv.weight = self.conv.weight + torch.arange(10)
# NOTE: `is not None` and `assert` is for passing torchscript.
if self.conv.bias is not None:
a = self.conv.bias
assert a is not None
self.conv.bias = anchors + a
def forward(self, anchors):
self.set_cell_anchors(anchors)
return self.conv.weight, self.conv.bias
model = torch.jit.script(MyModule())
anchors = torch.ones(3, 10, 3)
self.run_test(model, (anchors))
@skipIfUnsupportedMinOpsetVersion(11)
def test_set_attr_in_loop(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = torch.nn.Conv1d(10, 3, 3)
self.conv.weight = torch.nn.Parameter(torch.zeros(3, 10))
self.conv.bias = torch.nn.Parameter(torch.zeros(3, 10, 3))
def set_cell_anchors(self, anchors, boxes):
self.conv.weight = torch.randn(3, 10)
for i in range(self.conv.weight.size(0)):
for j in range(10):
self.conv.bias = torch.randn(3, 10, 3)
self.conv.weight = anchors * i
boxes[j] += torch.ones(3, 3)
def forward(self, anchors) -> tuple[Tensor, Tensor]:
boxes = torch.ones(10, 3, 3)
self.set_cell_anchors(anchors, boxes)
if self.conv.bias is not None:
return self.conv.weight, boxes
return anchors, boxes
model = torch.jit.script(MyModule())
anchors = torch.rand(10)
self.run_test(model, anchors)
@skipIfUnsupportedMinOpsetVersion(13)
def test_set_attr_in_loop_with_list(self):
class MyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = torch.nn.Conv1d(10, 3, 3)
self.conv.weight = torch.nn.Parameter(torch.zeros(3, 10))
self.conv.bias = torch.nn.Parameter(torch.zeros(3, 10, 3))
self.boxes: list[Tensor] = [
torch.ones(1)
] # Workaround placeholder for TorchScript
def set_cell_anchors(self, anchors):
self.conv.weight = torch.randn(3, 10)
for i in range(self.conv.weight.size(0)):
for _ in range(10):
self.conv.bias = torch.randn(3, 10, 3)
self.conv.weight = anchors * i
self.boxes.append(torch.ones(3, 3))
def forward(self, anchors) -> tuple[Tensor, list[Tensor]]:
self.boxes = []
self.set_cell_anchors(anchors)
if self.conv.bias is not None:
return self.conv.weight, self.boxes
return anchors, self.boxes
model = torch.jit.script(MyModule())
anchors = torch.rand(10)
self.run_test(model, anchors)
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_if(self):
@torch.jit.script
def check_init(
input_data: Tensor, hidden_size: int, prev_state: Tensor
) -> tuple[Tensor, Tensor]:
batch_size = input_data.size(0)
spatial_size_0 = input_data.size(2)
spatial_size_1 = input_data.size(3)
# generate empty prev_state, if None is provided
state_size = (2, batch_size, hidden_size, spatial_size_0, spatial_size_1)
state = torch.zeros(state_size, device=input_data.device)
state_copy = torch.zeros(state_size, device=input_data.device)
if prev_state.size(0) == 0:
state[:] = (
torch.zeros(batch_size, hidden_size, spatial_size_0, spatial_size_1)
+ state[:]
)
state_copy[:] = (
torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1)
* 2
)
state_copy[:] = (
torch.zeros(batch_size, hidden_size, spatial_size_0, spatial_size_1)
* 2
)
else:
state[:] = (
torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1)
* 4
)
return state, state_copy
class Example(torch.nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.hidden_size = hidden_size
def forward(self, input_data, prev_state):
prev_state = check_init(input_data, self.hidden_size, prev_state)
return prev_state[0], prev_state[1]
model = Example(10)
random_data = torch.rand((1, 5, 30, 30))
empty_tensor = torch.tensor([], dtype=torch.float).view(0, 0, 0, 0, 0)
self.run_test(
model,
(random_data, empty_tensor),
input_names=["random_data", "empty_tensor"],
dynamic_axes={"random_data": [0, 1, 2, 3], "empty_tensor": [0, 1, 2, 3, 4]},
)
self.run_test(model, (random_data, empty_tensor), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_if_2(self):
@torch.jit.script
def check_init(
input_data: Tensor, hidden_size: int, prev_state: Tensor
) -> tuple[Tensor, Tensor]:
batch_size = input_data.size(0)
spatial_size_0 = input_data.size(2)
spatial_size_1 = input_data.size(3)
# generate empty prev_state, if None is provided
state_size = (2, batch_size, hidden_size, spatial_size_0, spatial_size_1)
state = torch.zeros(state_size, device=input_data.device)
state_copy = torch.zeros(state_size, device=input_data.device)
if prev_state.size(0) == 0:
for i in range(2):
state[:] = (
torch.ones(
batch_size, hidden_size, spatial_size_0, spatial_size_1
)
* i
)
state_copy[:] = (
torch.ones(
batch_size, hidden_size, spatial_size_0, spatial_size_1
)
* i
)
elif prev_state.size(0) == 1:
s = state[:]
state[:] = prev_state + s
elif prev_state.size(0) == 2:
state[:] = (
torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1)
* 4
)
return state, state_copy
class Example(torch.nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.hidden_size = hidden_size
def forward(self, input_data, prev_state):
prev_state = check_init(input_data, self.hidden_size, prev_state)
return prev_state[0], prev_state[1]
model = Example(10)
random_data = torch.rand((1, 5, 30, 30))
empty_tensor = torch.tensor([], dtype=torch.float).view(0, 0, 0, 0, 0)
random_state = torch.rand((1, 1, 10, 30, 30))
self.run_test(
model,
(random_data, empty_tensor),
input_names=["data", "state"],
dynamic_axes={"data": [0, 1, 2], "state": [0, 1, 2, 3, 4]},
additional_test_inputs=[(random_data, random_state)],
)
self.run_test(
model,
(random_data, empty_tensor),
input_names=["data", "state"],
dynamic_axes={"state": [0, 1, 2, 3, 4]},
additional_test_inputs=[(random_data, random_state)],
remained_onnx_input_idx=[1],
)
self.run_test(model, (random_data, empty_tensor), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_if_3(self):
@torch.jit.script
def check_init(
input_data: Tensor, hidden_size: int, prev_state: Tensor
) -> Tensor:
batch_size = input_data.size(0)
spatial_size_0 = input_data.size(2)
spatial_size_1 = input_data.size(3)
# generate empty prev_state, if None is provided
state_size = (2, batch_size, hidden_size, spatial_size_0, spatial_size_1)
state = torch.zeros(state_size, device=input_data.device)
if prev_state.size(0) < 2:
state = state * 3
if prev_state.size(0) == 0:
state[:] = (
torch.ones(
batch_size, hidden_size, spatial_size_0, spatial_size_1
)
* 3
)
else:
state = state + 2
return state
class Example(torch.nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.hidden_size = hidden_size
def forward(self, input_data, prev_state):
prev_state = check_init(input_data, self.hidden_size, prev_state)
return prev_state
model = Example(4)
random_data = torch.rand((1, 5, 4, 4))
empty_tensor = torch.tensor([], dtype=torch.float).view(0, 0, 0, 0, 0)
self.run_test(
model,
(random_data, empty_tensor),
input_names=["random_data", "empty_tensor"],
dynamic_axes={"random_data": [0, 1, 2, 3], "empty_tensor": [0, 1, 2, 3, 4]},
)
self.run_test(model, (random_data, empty_tensor), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_if_4(self):
@torch.jit.script
def check_init(
input_data: Tensor, hidden_size: int, prev_state: Tensor
) -> Tensor:
batch_size = input_data.size(0)
spatial_size_0 = input_data.size(2)
spatial_size_1 = input_data.size(3)
# generate empty prev_state, if None is provided
state_size = (2, batch_size, hidden_size, spatial_size_0, spatial_size_1)
state = torch.zeros(state_size, device=input_data.device)
if prev_state.size(0) == 0:
state = state + 3
state[:] = (
torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1)
* 3
)
state = state + 3
state[:] = (
torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1)
* 4
)
else:
state = state + 2
return state
class Example(torch.nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.hidden_size = hidden_size
def forward(self, input_data, prev_state):
prev_state = check_init(input_data, self.hidden_size, prev_state)
return prev_state
model = Example(4)
random_data = torch.rand((1, 5, 4, 4))
empty_tensor = torch.tensor([], dtype=torch.float).view(0, 0, 0, 0, 0)
self.run_test(
model,
(random_data, empty_tensor),
input_names=["random_data", "empty_tensor"],
dynamic_axes={"random_data": [0, 1, 2, 3], "empty_tensor": [0, 1, 2, 3, 4]},
)
self.run_test(model, (random_data, empty_tensor), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_if_5(self):
@torch.jit.script
def check_init(
input_data: Tensor, hidden_size: int, prev_state: Tensor
) -> tuple[Tensor, Tensor]:
batch_size = input_data.size(0)
spatial_size_0 = input_data.size(2)
spatial_size_1 = input_data.size(3)
# generate empty prev_state, if None is provided
state_size = (2, batch_size, hidden_size, spatial_size_0, spatial_size_1)
state = torch.zeros(state_size, device=input_data.device)
state_ref = state
if prev_state.size(0) == 0:
state[:] = (
torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1)
* 3
)
state = state + 3
state[:] = (
torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1)
* 4
)
else:
state = state + 2
return state, state_ref
class Example(torch.nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.hidden_size = hidden_size
def forward(self, input_data, prev_state):
prev_state, state_ref = check_init(
input_data, self.hidden_size, prev_state
)
return prev_state, state_ref
model = Example(4)
random_data = torch.rand((1, 5, 4, 4))
empty_tensor = torch.tensor([], dtype=torch.float).view(0, 0, 0, 0, 0)
self.run_test(
model,
(random_data, empty_tensor),
input_names=["random_data", "empty_tensor"],
dynamic_axes={"random_data": [0, 1, 2, 3], "empty_tensor": [0, 1, 2, 3, 4]},
)
self.run_test(model, (random_data, empty_tensor), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(11)
def test_list_append_in_block(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
res.append(torch.matmul(x[i], y))
return res
model = torch.jit.script(ListModel())
x = torch.randn(16, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(13)
def test_list_append_in_nested_block(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
for i in range(x.size(0)):
for j in range(x.size(1)):
res.append(torch.matmul(x[i][j], y))
return res
model = torch.jit.script(ListModel())
x = torch.randn(4, 4, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(13)
def test_list_pop_in_block(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
elem = torch.matmul(x[0], y)
for i in range(x.size(0)):
res.append(torch.matmul(x[i], y))
for _ in range(x.size(0)):
elem = res.pop()
for i in range(x.size(0)):
res.append(torch.matmul(x[i], y))
elem = res.pop()
return res.append(elem)
model = torch.jit.script(ListModel())
x = torch.randn(16, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(13)
def test_list_del_in_block(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
elem = torch.matmul(x[0], y)
for i in range(x.size(0)):
res.append(torch.matmul(x[i], y))
for _ in range(x.size(0)):
del res[0]
for i in range(x.size(0)):
res.append(torch.matmul(x[i], y))
del res[0]
return res.append(elem)
model = torch.jit.script(ListModel())
x = torch.randn(16, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(11)
def test_list_unpack(self):
class ListModel(torch.nn.Module):
def forward(self, x, y):
res = []
elem = torch.matmul(x[0], y)
for i in range(x.size(0)):
res.append(torch.matmul(x[i], y))
a, b, c = res
return a, b
model = torch.jit.script(ListModel())
x = torch.randn(3, 3, 4)
y = torch.randn(4, 5)
self.run_test(model, (x, y))
@skipIfUnsupportedMinOpsetVersion(11)
def test_index_put_inplace_ops(self):
@torch.jit.script
def check_init(input_data: Tensor, hidden_size: int) -> Tensor:
batch_size = input_data.size(0)
spatial_size_0 = input_data.size(2)
spatial_size_1 = input_data.size(3)
# generate empty prev_state, if None is provided
state_size = (2, batch_size, hidden_size, spatial_size_0, spatial_size_1)
state = torch.zeros(state_size, device=input_data.device)
if input_data.size(0) == 1:
state[1] += (
torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1)
* 2
)
state[1] /= (
torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1)
* 3
)
for i in range(input_data.size(0)):
state[1] += torch.ones(
batch_size, hidden_size, spatial_size_0, spatial_size_1
)
state[1] /= (
torch.ones(batch_size, hidden_size, spatial_size_0, spatial_size_1)
* i
)
return state
class Example(torch.nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.hidden_size = hidden_size
def forward(self, input_data):
state = check_init(input_data, self.hidden_size)
return state
model = Example(10)
random_data = torch.rand((1, 5, 30, 30))
self.run_test(
model,
(random_data),
input_names=["random_data"],
dynamic_axes={"random_data": [0, 1, 2, 3]},
)
self.run_test(model, (random_data), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(11)
def test_input_mask_model(self):
class InputMaskModel(torch.nn.Module):
def __init__(self, output_size):
super().__init__()
self.bias = torch.nn.Parameter(
torch.empty(output_size, dtype=torch.float)
)
with torch.no_grad():
self.bias.zero_()
def forward(self, model_input, y):
input_mask = (model_input <= 0) | (model_input > 25)
y[input_mask, :] = 0.0
output = y + self.bias
return output
output_size = 4
m = InputMaskModel(output_size)
x = torch.tensor([0, 4, 24, 25], dtype=torch.int64)
y = torch.tensor(
[
[0.1, 0.2, 0.3, 0.4],
[0.1, 0.2, 0.3, 0.4],
[0.1, 0.2, 0.3, 0.4],
[0.1, 0.2, 0.3, 0.4],
],
dtype=torch.float,
)
self.run_test(m, (x, y))
class InputMaskModel(torch.nn.Module):
def __init__(self, output_size):
super().__init__()
def forward(self, model_input_1, model_input_2, y):
input_mask_1 = (model_input_1 <= 0) | (model_input_1 > 25)
input_mask_2 = (model_input_2 < 1) | (model_input_2 >= 12)
y[input_mask_1, input_mask_2] = 0.0
return y
output_size = 4
m = InputMaskModel(output_size)
x1 = torch.tensor([0, 4, 24, 25], dtype=torch.int64)
x2 = torch.tensor([0, 3, 12, 15], dtype=torch.int64)
y = torch.tensor(
[
[0.1, 0.2, 0.3, 0.4],
[0.1, 0.2, 0.3, 0.4],
[0.1, 0.2, 0.3, 0.4],
[0.1, 0.2, 0.3, 0.4],
],
dtype=torch.float,
)
self.run_test(m, (x1, x2, y))
@skipScriptTest()
def test_unsafe_chunk(self):
class ChunkModel(torch.nn.Module):
def forward(self, x):
return torch.unsafe_chunk(x, 3, dim=1)
model = ChunkModel()
model.eval()
x = torch.randn(1, 18)
self.run_test(model, x, input_names=["x"])
def test_symbolic_shape_inference(self):
# ConstantOfShape is tested in test_embedding_bag
# Tile is tested in test_repeat
# test Shape, Reshape, Transpose, Gather
class ShapeModel(torch.nn.Module):
def forward(self, x, y):
shape = x.size()[:3] + (-1,) # shape [4], ("batch", 3, 4, -1)
y = y.reshape(shape) # batch, 3, 4, 10/batch
return y.transpose(1, 2)
model = ShapeModel()
model.eval()
x = torch.ones(2, 3, 4, 5)
y = torch.ones(3, 4, 5, 2)
self.run_test(
model,
(x, y),
input_names=["x", "y"],
dynamic_axes={"x": [0, 1, 2, 3], "y": [0, 1, 2, 3]},
)
self.run_test(model, (x, y), remained_onnx_input_idx=[1])
class ViewModel(torch.nn.Module):
def forward(self, x):
return x.view(-1)
model = ViewModel()
model.eval()
x = torch.tensor(2.0)
self.run_test(model, (x,))
# test prim::ListConstruct for Reshape input 1
class ViewModel_2(torch.nn.Module):
def forward(self, x):
N, C, H, W = x.shape[0], x.shape[2], x.shape[3], x.shape[4]
x1 = x.view(N, -1, C, H, W)
x2 = x1.permute(0, 3, 4, 1, 2)
return x2.reshape(N, -1, C)
model = ViewModel_2()
model.eval()
x = torch.ones(2, 3, 4, 5, 6)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_symbolic_shape_inference_arange(self):
# test Range
class ArangeModel(torch.nn.Module):
def forward(self, signal):
frame_step = 2
outer_dimensions = signal.size()[:-2]
frames, frame_length = signal.size()[-2:]
subframe_length = signal.size()[0]
subframe_step = frame_step // subframe_length
subframes_per_frame = frame_length // subframe_length
output_size = frame_step * (frames - 1) + frame_length
output_subframes = output_size // subframe_length
frame = torch.arange(0, output_subframes)
return frame
model = ArangeModel()
model.eval()
M, C, K, N = 1, 2, 3, 4
x = torch.randint(5, (M, C, K, N))
y = torch.randint(5, (M, C + 1, K + 1, N + 1))
self.run_test(model, x, input_names=["x"], dynamic_axes={"x": [0, 1, 2, 3]})
self.run_test(model, x, remained_onnx_input_idx=[])
self.run_test(
model,
x,
input_names=["x"],
dynamic_axes={"x": [0, 1, 2, 3]},
additional_test_inputs=[(x,), (y,)],
)
@skipIfUnsupportedMinOpsetVersion(11)
def test_symbolic_shape_inference_box(self):
# test NonZero
class BoxModel(torch.nn.Module):
def forward(self, boxes):
min_size = 1e-2
ws, hs = boxes[:, 2] - boxes[:, 0], boxes[:, 3] - boxes[:, 1]
keep = (ws >= min_size) & (hs >= min_size)
keep = torch.where(keep)[0]
return keep
model = BoxModel()
model.eval()
x = torch.ones(2, 4)
y = torch.ones(3, 5)
self.run_test(model, x)
self.run_test(
model,
x,
input_names=["x"],
dynamic_axes={"x": [0, 1]},
additional_test_inputs=[(x,), (y,)],
)
@skipIfUnsupportedMinOpsetVersion(11)
def test_symbolic_shape_inference_box_if(self):
# test If
class BoxIfModel(torch.nn.Module):
def forward(self, boxes, scores):
score_thresh = 0.0
inds = torch.where(scores > score_thresh)[0]
boxes_1 = boxes[inds]
if boxes_1.numel() > 3:
return boxes_1
else:
return boxes_1 * 2
model = BoxIfModel()
model.eval()
boxes = torch.ones(2, 4)
scores = torch.ones(1, 4)
self.run_test(model, (boxes, scores))
@skipIfUnsupportedMinOpsetVersion(11)
@skipDtypeChecking
def test_symbolic_shape_inference_arange_2(self):
# test Range
class ArangeModel(torch.nn.Module):
def forward(self, start):
return torch.arange(start.size(0), 8.5, 1.5, dtype=torch.int64)
x = torch.randn(2, 3, 4)
self.run_test(
ArangeModel(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1, 2]}
)
self.run_test(ArangeModel(), (x,), remained_onnx_input_idx=[])
class ArangeModel2(torch.nn.Module):
def forward(self, start):
return torch.arange(start.size(0), 8.5, 1.5, dtype=torch.double)
x = torch.randn(2, 3, 4)
self.run_test(
ArangeModel2(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1, 2]}
)
self.run_test(ArangeModel2(), (x,), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_symbolic_shape_inference_nonzero(self):
class OneLikeModel(torch.nn.Module):
def forward(self, x):
ones = torch.ones_like(
x,
dtype=torch.float,
layout=torch.strided,
device=torch.device("cpu"),
)
return torch.nonzero(ones)
x = torch.randn(2)
self.run_test(OneLikeModel(), x, input_names=["x"], dynamic_axes={"x": [0]})
self.run_test(OneLikeModel(), x, remained_onnx_input_idx=[])
x = torch.randn(2, 3, 4)
self.run_test(
OneLikeModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]}
)
self.run_test(OneLikeModel(), x, remained_onnx_input_idx=[])
class ZeroLikeModel(torch.nn.Module):
def forward(self, x):
zeros = torch.zeros_like(
x,
dtype=torch.float,
layout=torch.strided,
device=torch.device("cpu"),
)
return torch.nonzero(zeros)
x = torch.randn(2)
self.run_test(ZeroLikeModel(), x, input_names=["x"], dynamic_axes={"x": [0]})
self.run_test(ZeroLikeModel(), x, remained_onnx_input_idx=[])
x = torch.randn(2, 3, 4)
self.run_test(
ZeroLikeModel(), x, input_names=["x"], dynamic_axes={"x": [0, 1, 2]}
)
self.run_test(ZeroLikeModel(), x, remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(9)
def test_symbolic_shape_inference_expand_1(self):
class ExpandModel(torch.nn.Module):
def forward(self, x):
return x.expand(4, 6, 2)
x = torch.randn(6, 1, requires_grad=True)
self.run_test(ExpandModel(), (x,))
@skipIfUnsupportedMinOpsetVersion(9)
def test_symbolic_shape_inference_expand_2(self):
class M(torch.nn.Module):
def forward(self, x):
input_shape = x.size()
batch_size, seq_length = input_shape
seq_ids = torch.arange(seq_length)
causal_mask = (
seq_ids[None, None, :].repeat(batch_size, seq_length, 1)
<= seq_ids[None, :, None]
)
return causal_mask.transpose(0, 1)
x = torch.randn(3, 16)
self.run_test(M(), (x,), input_names=["x"], dynamic_axes={"x": [0, 1]})
self.run_test(M(), (x,), remained_onnx_input_idx=[])
@skipIfUnsupportedMinOpsetVersion(10)
def test_symbolic_shape_inference_slice(self):
class M(torch.nn.Module):
def forward(self, x, position_bias):
input_shape = x.size()
batch_size, seq_length = input_shape
position_bias = position_bias[:, :, -seq_length:, :]
return position_bias.transpose(0, 1)
x = torch.randn(3, 16)
position_bias = torch.randn(1, 3, 20, 8)
self.run_test(
M(),
(x, position_bias),
input_names=["x", "position_bias"],
dynamic_axes={"x": [0, 1], "position_bias": [0, 1, 2, 3]},
)
self.run_test(M(), (x, position_bias), remained_onnx_input_idx=[1])
def test_symbolic_shape_inference_slice_2(self):
class M(torch.nn.Module):
def forward(self, position_bias):
position_bias = position_bias[:, :, -2:, :]
return position_bias.transpose(0, 1)
position_bias = torch.randn(1, 3, 20, 8)
self.run_test(M(), (position_bias,))
@skipIfUnsupportedMinOpsetVersion(9)
@skipScriptTest()
def test_symbolic_shape_inference_time(self):
input = torch.randn(RNN_SEQUENCE_LENGTH, BATCH_SIZE, RNN_INPUT_SIZE)
h0 = torch.randn(1, BATCH_SIZE, RNN_HIDDEN_SIZE)
c0 = torch.randn(1, BATCH_SIZE, RNN_HIDDEN_SIZE)
model_lstm = torch.nn.LSTM(
RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, 1, bidirectional=False
)
self.run_test(
model_lstm,
(input, (h0, c0)),
input_names=["x", "y"],
dynamic_axes={"x": [0, 1]},
)
model_gru = torch.nn.GRU(
RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, 1, bidirectional=False, bias=False
)
self.run_test(
model_gru, (input, h0), input_names=["x", "y"], dynamic_axes={"x": [0, 1]}
)
model_rnn = torch.nn.RNN(
RNN_INPUT_SIZE, RNN_HIDDEN_SIZE, 1, bidirectional=False, bias=False
)
self.run_test(
model_rnn, (input, h0), input_names=["x", "y"], dynamic_axes={"x": [0, 1]}
)
def test_symbolic_shape_inference_dynamic_axes(self):
class M(torch.nn.Module):
def forward(self, input_ids):
input_shape = input_ids.size()
input_ids = input_ids.view(-1, input_shape[-1])
return input_ids.transpose(0, 1)
x = torch.randn(3, 16)
self.run_test(
M(),
(x,),
input_names=["input_ids"],
dynamic_axes={"input_ids": {0: "batch", 1: "sequence"}},
)
@skipIfUnsupportedMinOpsetVersion(9)
def test_hann_window_periodic(self):
class HannWindowModule_Periodic(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.window_length = 0
def forward(self, x, window_length: int):
self.window_length = window_length
return torch.add(
x,
torch.hann_window(
self.window_length, periodic=True, dtype=torch.float
),
)
win_length = 100
x = torch.randn(win_length)
module = HannWindowModule_Periodic()
self.run_test(module, (x, win_length))
@skipIfUnsupportedMinOpsetVersion(9)
def test_hann_window_not_periodic(self):
class HannWindowModule_NotPeriodic(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.window_length = 0
def forward(self, x, window_length: int):
self.window_length = window_length
return torch.add(
x,
torch.hann_window(
self.window_length, periodic=False, dtype=torch.float
),
)
win_length = 100
x = torch.randn(win_length)
module = HannWindowModule_NotPeriodic()
self.run_test(module, (x, win_length))
@skipIfUnsupportedMinOpsetVersion(9)
@skipScriptTest()
def test_hann_window_default_values(self):
class HannWindowModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.window_length = 0
def forward(self, x, window_length: int):
import torch.nn.functional as F
self.window_length = window_length
return torch.add(x, F.relu(torch.hann_window(self.window_length)))
win_length = 100
x = torch.randn(win_length, dtype=torch.float)
module = HannWindowModule()
output = module(x, win_length)
self.run_test(module, (x, win_length))
@skipIfUnsupportedMinOpsetVersion(12)
def test_tensordot_dim_count(self):
class M(torch.nn.Module):
def forward(self, x, y):
output = torch.tensordot(x, y, 2)
return output
x = torch.randint(6, (7, 5, 3, 4))
y = torch.randint(6, (3, 4, 9, 2))
self.run_test(M(), (x, y))
@skipIfUnsupportedMinOpsetVersion(12)
def test_tensordot_dim_list(self):
class M(torch.nn.Module):
def forward(self, x, y):
output = torch.tensordot(x, y, ([1, -2, -1], [1, 0, 3]))
return output
x = torch.randint(6, (7, 4, 3, 5, 2))
y = torch.randint(6, (5, 4, 4, 2, 6))
self.run_test(M(), (x, y))
@skipIfUnsupportedMinOpsetVersion(12)
def test_tensordot_dynamic_dim(self):
class M(torch.nn.Module):
def forward(self, x, y):
output = torch.tensordot(x, y, 2)
return output
x = torch.randint(6, (7, 5, 3, 4))
y = torch.randint(6, (3, 4, 9, 2))
new_x = torch.randint(6, (8, 6, 2, 5))
new_y = torch.randint(6, (2, 5, 3, 4))
self.run_test(
M(),
(x, y),
additional_test_inputs=[(new_x, new_y)],
input_names=["input_x", "input_y"],
dynamic_axes={"input_x": [0, 1, 2, 3], "input_y": [0, 1, 2, 3]},
)
@skipIfUnsupportedMinOpsetVersion(9)
def test_to_device(self):
class M_ToDevice(torch.nn.Module):
def forward(self, x, y):
return x.to(y.device), y
class M_ToDeviceDtype(torch.nn.Module):
def forward(self, x, y):
return x.to(y.device, dtype=torch.long), y
x = torch.randn(6)
y = torch.randn(6)
self.run_test(M_ToDevice(), (x, y))
self.run_test(M_ToDeviceDtype(), (x, y))
@skipIfUnsupportedMinOpsetVersion(9)
def test_fill(self):
class FillModule(torch.nn.Module):
def forward(self, x, filled_value: int):
return x.fill_(filled_value)
x = torch.randn((4, 5, 6))
filled_value = 7
self.run_test(FillModule(), (x, filled_value))
class FillFloatModule(torch.nn.Module):
def forward(self, x, filled_value: float):
return x.fill_(filled_value)
x = torch.randn((4, 5, 6))
filled_value = 7.5
self.run_test(FillFloatModule(), (x, filled_value))
class FillScalarModule(torch.nn.Module):
def forward(self, x):
res = x + 2
res.fill_(2.5)
return res, x
x = torch.ones(2, 3, 4, dtype=torch.long)
self.run_test(FillScalarModule(), x)
@skipIfUnsupportedMinOpsetVersion(9)
def test_index_add_normal(self):
class M(torch.nn.Module):
def __init__(self, dim, index, updates):
super().__init__()
self.dim = dim
self.index = index
self.updates = updates
def forward(self, x):
x.index_add_(self.dim, self.index, self.updates)
return x
x = torch.ones(5, 1)
updates = torch.tensor([[1], [4], [7], [3], [2]], dtype=torch.float)
index = torch.tensor([0, 2, 3, 1, 4])
self.run_test(M(0, index, updates), (x,))
x = torch.ones(1, 4, 3)
updates = torch.tensor(
[[[1, 5, 7], [2, 4, 5], [5, 5, 6], [2, 3, 4]]], dtype=torch.float
)
index = torch.tensor([0, 2, 3, 1])
self.run_test(M(1, index, updates), (x,))
updates = torch.tensor(
[[[1, 2, 3], [4, 5, 6], [7, 8, 9], [2, 3, 4]]], dtype=torch.float
)
index = torch.tensor([0, 2, 1])
self.run_test(M(2, index, updates), (x,))
@skipIfUnsupportedMinOpsetVersion(9)
def test_index_add_dim_size_differ(self):
class M(torch.nn.Module):
def __init__(self, dim, index, updates):
super().__init__()
self.dim = dim
self.index = index
self.updates = updates
def forward(self, x):
x.index_add_(self.dim, self.index, self.updates)
return x
x = torch.ones(1, 4, 3)
updates = torch.tensor([[[1, 5, 7], [2, 4, 5], [5, 5, 6]]], dtype=torch.float)
index = torch.tensor([0, 2, 1])
self.run_test(M(1, index, updates), (x,))
@skipIfUnsupportedMinOpsetVersion(9)
def test_index_add_in_loop(self):
class M(torch.nn.Module):
def __init__(self, dim, index, updates, loop_count):
super().__init__()
self.dim = dim
self.index = index
self.updates = updates
self.loop_count = loop_count
def forward(self, x):
for _ in range(self.loop_count):
x.index_add_(self.dim, self.index, self.updates)
return x
x = torch.ones(1, 4, 3)
updates = torch.tensor(
[[[1, 5, 7], [2, 4, 5], [5, 5, 6], [2, 3, 4]]], dtype=torch.float
)
index = torch.tensor([0, 2, 3, 1])
loop_count = torch.randint(20, (1,))[0].item()
self.run_test(M(1, index, updates, loop_count), (x,))
@skipIfUnsupportedMinOpsetVersion(9)
def test_index_add_if(self):
class M(torch.nn.Module):
def __init__(self, dim, updates, index_true, index_false):
super().__init__()
self.dim = dim
self.updates = updates
self.index_true = index_true
self.index_false = index_false
def forward(self, x, cond):
if cond:
x.index_add_(self.dim, self.index_true, self.updates)
else:
x.index_add_(self.dim, self.index_false, self.updates)
return x
x = torch.ones(1, 4, 3)
updates = torch.tensor(
[[[1, 5, 7], [2, 4, 5], [5, 5, 6], [2, 3, 4]]], dtype=torch.float
)
index_true = torch.tensor([0, 2, 3, 1])
index_false = torch.tensor([1, 0, 2, 3])
cond = torch.tensor(1, dtype=torch.bool)
self.run_test(
torch.jit.script(M(1, updates, index_true, index_false)), (x, cond)
)
@skipIfUnsupportedMinOpsetVersion(9)
def test_index_add_dynamic_axes(self):
class M(torch.nn.Module):
def __init__(self, dim, index, updates):
super().__init__()
self.dim = dim
self.index = index
self.updates = updates
def forward(self, x):
x.index_add_(self.dim, self.index, self.updates)
return x
x = torch.ones(1, 4, 3)
updates = torch.tensor(
[[[1, 5, 7], [2, 4, 5], [5, 5, 6], [2, 3, 4]]], dtype=torch.float
)
index = torch.tensor([0, 2, 3, 1])
self.run_test(
M(1, index, updates),
(x,),
input_names=["input_1"],
dynamic_axes={"input_1": [0, 1]},
)
def test_roll(self):
class M(torch.nn.Module):
def __init__(self, shifts, dims):
super().__init__()
self.shifts = shifts
self.dims = dims
def forward(self, x):
return torch.roll(x, self.shifts, self.dims)
x = torch.randn(2, 3, 4)
self.run_test(M([1, 1], [1, 0]), (x,))
self.run_test(M([0, 1, 2], [1, 0, 2]), (x,))
self.run_test(M(2, 1), (x,))
self.run_test(M([-1, 3], [-2, -1]), (x,))
def test_sum(self):
class M(torch.nn.Module):
def forward(self, x):
return torch.sum(x)
x = torch.ones(12, 3)
self.run_test(M(), (x,), input_names=["x"], dynamic_axes={"x": [0]})
@skipShapeChecking
def test_sum_empty_tensor(self):
class M(torch.nn.Module):
def forward(self, x):
return x[0:0].sum(), x.sum()
x = torch.ones(12)
self.run_test(M(), (x,))
x = torch.ones(2, 0, 3)
self.run_test(M(), (x,))
x = torch.ones(0)
self.run_test(M(), (x,))
@skipIfUnsupportedMinOpsetVersion(11)
def test_broad_cast_tensors(self):
class M(torch.nn.Module):
def forward(self, x, y):
m = torch.broadcast_tensors(x, y)
return m
x = torch.randint(5, (1,))
y = torch.randint(5, (5,))
self.run_test(M(), (x, y))
x = torch.randint(5, (4, 2, 1, 4))
y = torch.randint(5, (2, 3, 1))
self.run_test(M(), (x, y))
x = torch.randn(2, 1, 4)
y = torch.randn(5, 2, 3, 1)
self.run_test(M(), (x, y))
@skipIfUnsupportedMinOpsetVersion(14)
def test_scaled_dot_product_attention(self):
class M(torch.nn.Module):
def forward(self, q, k, v):
return torch.nn.functional.scaled_dot_product_attention(
q, k, v, scale=1.0
)
# Parameters
batch_size = 2 # Number of samples in the batch
num_heads = 4 # Number of attention heads
seq_length = 5 # Sequence length
head_dim = 8 # Dimensionality of each head
# Create random query, key, and value tensors
q = torch.randn(batch_size, num_heads, seq_length, head_dim)
k = torch.randn(batch_size, num_heads, seq_length, head_dim)
v = torch.randn(batch_size, num_heads, seq_length, head_dim)
self.run_test(M(), (q, k, v))
@skipScriptTest()
@skipIfUnsupportedMinOpsetVersion(11)
def test_dist_normal(self):
class M(torch.nn.Module):
def forward(self, x, y):
return torch.distributions.Normal(x, y).sample().size(0), x, y
self.run_test(M(), (torch.tensor([0.0]), torch.tensor([[1.0], [2.0]])))
self.run_test(M(), (torch.tensor([0.0]), torch.tensor([1.0])))
self.run_test(
M(),
(
torch.tensor([[[0.0], [10.0]], [[2.0], [8.0]], [[2.0], [8.0]]]),
torch.tensor([[1.0], [3.0]]),
),
)
@skipScriptTest()
@skipIfUnsupportedMinOpsetVersion(11)
def test_dist_normal_correctness(self):
class M(torch.nn.Module):
def forward(self, x, y):
return torch.distributions.Normal(x, y).sample([20000])
expected_mean = 5.0
expected_std = 10.0
model_export = M()
dummy_input = (torch.tensor([expected_mean]), torch.tensor([expected_std]))
model_onnx = io.BytesIO()
torch.onnx.export(
model_export,
dummy_input,
model_onnx,
opset_version=self.opset_version,
dynamo=False,
)
ort_sess = verification._ort_session(model_onnx)
ort_out = verification._run_onnx(ort_sess, inputs=dummy_input)
actual_std = np.std(ort_out)
actual_mean = np.mean(ort_out)
assert abs(abs(actual_mean) - expected_mean) <= expected_mean * 0.1, (
"the gap of mean between ort outputs and expected one is unacceptable."
)
assert abs(abs(actual_std) - expected_std) <= expected_std * 0.1, (
"the gap of variance between ort outputs and expected one is unacceptable."
)
@skipScriptTest()
@skipIfUnsupportedMinOpsetVersion(11)
def test_nn_init_normal_correctness(self):
expected_mean = 5.0
expected_std = 10.0
class M(torch.nn.Module):
def forward(self):
x = torch.ones([]).new_empty(1, 400, 50)
torch.nn.init.normal_(x, expected_mean, expected_std)
return x
model_export = M()
model_onnx = io.BytesIO()
test_inputs = ()
torch.onnx.export(
model_export,
test_inputs,
model_onnx,
opset_version=self.opset_version,
dynamo=False,
)
ort_sess = verification._ort_session(model_onnx)
ort_out = verification._run_onnx(ort_sess, inputs=test_inputs)
actual_std = np.std(ort_out)
actual_mean = np.mean(ort_out)
assert abs(abs(actual_mean) - expected_mean) <= expected_mean * 0.1, (
"the gap of mean between ort outputs and expected one is unacceptable."
)
assert abs(abs(actual_std) - expected_std) <= expected_std * 0.1, (
"the gap of variance between ort outputs and expected one is unacceptable."
)
@skipScriptTest()
@skipIfUnsupportedMinOpsetVersion(11)
def test_dist_uniform(self):
class M(torch.nn.Module):
def forward(self, x, y):
return torch.distributions.Uniform(x, y).sample().size(0), x, y
self.run_test(M(), (torch.tensor([0.0]), torch.tensor([10.0])))
self.run_test(M(), (torch.tensor([[0.0], [6.0]]), torch.tensor([[1.0], [7.0]])))
self.run_test(
M(), (torch.tensor([1.0]), torch.tensor([[10.0], [7.0], [9.0], [20.0]]))
)
@skipScriptTest()
@skipIfUnsupportedMinOpsetVersion(11)
def test_dist_uniform_correctness(self):
class M(torch.nn.Module):
def forward(self, x, y):
return torch.distributions.Uniform(x, y).sample([10000])
expected_min = 5.0
expected_max = 10.0
expected_mean = (expected_min + expected_max) / 2
model_export = M()
dummy_input = (torch.tensor([expected_min]), torch.tensor([expected_max]))
model_onnx = io.BytesIO()
torch.onnx.export(
model_export,
dummy_input,
model_onnx,
opset_version=self.opset_version,
dynamo=False,
)
ort_sess = verification._ort_session(model_onnx)
ort_out = verification._run_onnx(ort_sess, inputs=dummy_input)
actual_min = np.min(ort_out)
actual_max = np.max(ort_out)
actual_mean = np.mean(ort_out)
assert actual_min >= expected_min, (
"the minimum value of ort outputs is out of scope."
)
assert actual_max <= expected_max, (
"the maximum value of ort outputs is out of scope."
)
assert abs(actual_mean - expected_mean) <= expected_mean * 0.05, (
"the mean value of ort outputs is out of scope."
)
@skipIfUnsupportedMinOpsetVersion(13)
def test_sequence_to_int(self):
class M(torch.nn.Module):
def forward(self, x):
result = torch.tensor([2 for i in range(x.size()[0])], dtype=torch.int)
return x, result
x = torch.randn(10, 5)
self.run_test(M(), (x,))
@skipIfUnsupportedMinOpsetVersion(13)
def test_sequence_to_float(self):
class M(torch.nn.Module):
def forward(self, x):
result = torch.tensor(
[1.1 for i in range(x.size()[0])], dtype=torch.float
)
return x, result
x = torch.randn(10, 5)
self.run_test(M(), (x,))
@skipIfUnsupportedMinOpsetVersion(13)
def test_sequence_to_bool(self):
class M(torch.nn.Module):
def forward(self, x):
result = torch.tensor(
[False for i in range(x.size()[0])], dtype=torch.bool
)
return x, result
x = torch.randn(10, 5)
self.run_test(M(), (x,))
def test_tuple_output_from_if_with_raised_exception(self):
class M(torch.nn.Module):
def forward(self, t: Tensor) -> tuple[Tensor, Tensor]:
if float(t) < 0:
raise Exception("Negative input") # noqa: TRY002
else:
return torch.zeros(5), torch.zeros(5)
x = torch.zeros(1)
self.run_test(torch.jit.script(M()), (x,))
# NOTE: For quantization tests, choose scale and zero point carefully
# such that inputs and outputs do not always overflow/underflow.
# Otherwise test results could be inaccurate.
@skipIfUnsupportedMinOpsetVersion(10)
def test_quantized_linear(self):
model = torch.ao.nn.quantized.Linear(4, 8)
# Set fixed weight to avoid flaky test.
weight = torch.quantize_per_tensor(
torch.arange(32, dtype=torch.float).view(8, 4), 0.5, 0, torch.qint8
)
# Set non-zero bias.
bias = torch.arange(8, dtype=torch.float)
model.set_weight_bias(weight, bias)
# Set fixed input to avoid flaky test.
input = torch.randn(4, 4)
input = torch.arange(16, dtype=torch.float).view(4, 4) - 8
input_tensor = torch.quantize_per_tensor(input, 0.5, 128, torch.quint8)
self.run_test(model, input_tensor)
@skipIfUnsupportedMinOpsetVersion(10)
def test_quantized_conv1d(self):
model = torch.ao.nn.quantized.Conv1d(16, 33, 3, stride=2)
# Manually initialize model weight and bias to random numbers.
# By default all zeros.
q_weight = torch.quantize_per_tensor(
torch.randn(33, 16, 3), 0.5, 0, torch.qint8
)
bias = torch.arange(33).to(torch.float) - 16
model.set_weight_bias(q_weight, bias)
input = torch.randn(3, 16, 32)
q_input = torch.quantize_per_tensor(input, 0.5, 128, torch.quint8)
self.run_test(model, q_input)
@skipIfUnsupportedMinOpsetVersion(10)
def test_quantized_conv2d(self):
model = torch.ao.nn.quantized.Conv2d(16, 33, 3, stride=2)
# Manually initialize model weight and bias to random numbers.
# By default all zeros.
q_weight = torch.quantize_per_tensor(
torch.randn(33, 16, 3, 3), 0.5, 0, torch.qint8
)
bias = torch.arange(33).to(torch.float) - 16
model.set_weight_bias(q_weight, bias)
input = torch.randn(3, 16, 32, 32)
q_input = torch.quantize_per_tensor(input, 0.5, 128, torch.quint8)
self.run_test(model, q_input)
@skipIfUnsupportedMinOpsetVersion(10)
@skipIfQuantizationBackendQNNPack
def test_quantized_conv3d(self):
model = torch.ao.nn.quantized.Conv3d(16, 33, [2, 3, 4], stride=[3, 1, 2])
# Manually initialize model weight and bias to random numbers.
# By default all zeros.
q_weight = torch.quantize_per_tensor(
torch.randn(33, 16, 2, 3, 4), 0.5, 0, torch.qint8
)
bias = torch.arange(33).to(torch.float) - 16
model.set_weight_bias(q_weight, bias)
input = torch.randn(3, 16, 8, 8, 8)
q_input = torch.quantize_per_tensor(input, 0.5, 128, torch.quint8)
self.run_test(model, q_input)
@skipIfUnsupportedMinOpsetVersion(10)
def test_quantized_adaptive_avg_pool2d(self):
model = torch.nn.AdaptiveAvgPool2d((5, 7))
input = torch.randn(4, 3, 10, 14)
q_input = torch.quantize_per_tensor(input, 0.2, 128, torch.quint8)
self.run_test(model, q_input)
@skipIfUnsupportedMinOpsetVersion(10)
def test_quantized_conv1d_relu(self):
model = torch.ao.nn.intrinsic.quantized.ConvReLU1d(16, 33, 3, stride=2)
# Manually initialize model weight and bias to random numbers.
# By default all zeros.
q_weight = torch.quantize_per_tensor(
torch.randn(33, 16, 3), 0.5, 0, torch.qint8
)
bias = torch.arange(33).to(torch.float) - 16
model.set_weight_bias(q_weight, bias)
input = torch.randn(3, 16, 32)
q_input = torch.quantize_per_tensor(input, 0.5, 128, torch.quint8)
self.run_test(model, q_input)
@skipIfUnsupportedMinOpsetVersion(10)
def test_quantized_conv2d_relu(self):
model = torch.ao.nn.intrinsic.quantized.ConvReLU2d(16, 33, 3, stride=2)
# Manually initialize model weight and bias to random numbers.
# By default all zeros.
q_weight = torch.quantize_per_tensor(
torch.randn(33, 16, 3, 3), 0.5, 0, torch.qint8
)
bias = torch.arange(33).to(torch.float) - 16
model.set_weight_bias(q_weight, bias)
input = torch.randn(3, 16, 32, 32)
q_input = torch.quantize_per_tensor(input, 0.5, 128, torch.quint8)
self.run_test(model, q_input)
@skipIfUnsupportedMinOpsetVersion(10)
@skipIfQuantizationBackendQNNPack
def test_quantized_conv3d_relu(self):
model = torch.ao.nn.intrinsic.quantized.ConvReLU3d(
16, 33, [2, 3, 4], stride=[3, 1, 2]
)
# Manually initialize model weight and bias to random numbers.
# By default all zeros.
q_weight = torch.quantize_per_tensor(
torch.randn(33, 16, 2, 3, 4), 0.5, 0, torch.qint8
)
bias = torch.arange(33).to(torch.float) - 16
model.set_weight_bias(q_weight, bias)
input = torch.randn(3, 16, 8, 8, 8)
q_input = torch.quantize_per_tensor(input, 0.5, 128, torch.quint8)
self.run_test(model, q_input)
@skipIfUnsupportedMinOpsetVersion(10)
def test_quantized_conv_transpose1d(self):
model = torch.ao.nn.quantized.ConvTranspose1d(
16, 33, 3, output_padding=1, stride=2
)
# Manually initialize model weight and bias to random numbers.
# By default all zeros.
q_weight = torch.quantize_per_tensor(
torch.randn(16, 33, 3), 0.5, 0, torch.qint8
)
bias = torch.arange(33).to(torch.float) - 16
model.set_weight_bias(q_weight, bias)
input = torch.randn(3, 16, 32)
q_input = torch.quantize_per_tensor(input, 0.5, 128, torch.quint8)
self.run_test(model, q_input)
@skipIfUnsupportedMinOpsetVersion(10)
def test_quantized_conv_transpose2d(self):
model = torch.ao.nn.quantized.ConvTranspose2d(
16, 33, 3, output_padding=(0, 1), stride=2
)
# Manually initialize model weight and bias to random numbers.
# By default all zeros.
q_weight = torch.quantize_per_tensor(
torch.randn(16, 33, 3, 3), 0.5, 0, torch.qint8
)
bias = torch.arange(33).to(torch.float) - 16
model.set_weight_bias(q_weight, bias)
input = torch.randn(3, 16, 32, 32)
q_input = torch.quantize_per_tensor(input, 0.5, 128, torch.quint8)
self.run_test(model, q_input)
@skipIfUnsupportedMinOpsetVersion(10)
@skipIfQuantizationBackendQNNPack
def test_quantized_conv_transpose3d(self):
model = torch.ao.nn.quantized.ConvTranspose3d(
16, 33, [2, 3, 4], output_padding=(0, 1, 2), stride=[3, 1, 2]
)
# Manually initialize model weight and bias to random numbers.
# By default all zeros.
q_weight = torch.quantize_per_tensor(
torch.randn(16, 33, 2, 3, 4), 0.5, 0, torch.qint8
)
bias = torch.arange(33).to(torch.float) - 16
model.set_weight_bias(q_weight, bias)
input = torch.randn(3, 16, 8, 8, 8)
q_input = torch.quantize_per_tensor(input, 0.5, 128, torch.quint8)
self.run_test(model, q_input)
@common_utils.parametrize(
"function_or_module",
[
common_utils.subtest(
torch.nn.ReLU(),
name="relu",
),
common_utils.subtest(
torch.nn.LeakyReLU(),
name="leaky_relu",
),
common_utils.subtest(
torch.ao.nn.quantized.LeakyReLU(2.0, 1),
name="quantized_leaky_relu",
),
common_utils.subtest(
torch.ao.nn.quantized.Hardswish(2.0, 1),
name="quantized_hardswish",
),
common_utils.subtest(
torch.nn.Sigmoid(),
name="sigmoid",
),
common_utils.subtest(
torch.ao.nn.quantized.Sigmoid(2.0, 1),
name="quantized_sigmoid",
),
common_utils.subtest(
torch.nn.Hardsigmoid(),
name="hardsigmoid",
),
common_utils.subtest(
torch.nn.Tanh(),
name="tanh",
),
common_utils.subtest(
torch.nn.Hardtanh(),
name="hardtanh",
),
common_utils.subtest(
lambda x: torch.transpose(x, 0, 1),
name="transpose",
),
common_utils.subtest(
lambda x: x.expand(2, 4, 2, 3),
name="expand",
),
common_utils.subtest(
lambda x: x.view(1, 4, 6),
name="view",
),
common_utils.subtest(
lambda x: x.select(1, 1),
name="select",
),
common_utils.subtest(
torch.ao.nn.quantized.LayerNorm(
[4, 2, 3],
torch.nn.Parameter(torch.ones([4, 2, 3])),
torch.nn.Parameter(torch.zeros([4, 2, 3])),
2.0,
1,
),
name="layer_norm",
),
common_utils.subtest(
torch.ao.nn.quantized.InstanceNorm1d(
2,
torch.nn.Parameter(torch.ones(4)),
torch.nn.Parameter(torch.zeros(4)),
2.0,
1,
),
name="instance_norm",
),
common_utils.subtest(
torch.ao.nn.quantized.GroupNorm(
2,
4,
torch.nn.Parameter(torch.zeros(4)),
torch.nn.Parameter(torch.zeros(4)),
2.0,
1,
),
name="group_norm",
),
common_utils.subtest(
lambda x: torch.as_strided(x, (2, 2), (1, 2)),
name="as_strided",
),
],
)
@skipScriptTest()
@skipIfUnsupportedMinOpsetVersion(10)
def test_quantized_unary_ops(self, function_or_module):
input = torch.randn(1, 4, 2, 3)
q_input = torch.quantize_per_tensor(input, 0.26, 128, torch.quint8)
class Model(torch.nn.Module):
def __init__(self, function_or_module):
super().__init__()
self.function_or_module = function_or_module
def forward(self, x):
return self.function_or_module(x)
self.run_test(Model(function_or_module), q_input)
@skipIfUnsupportedMinOpsetVersion(10)
def test_quantized_flatten(self):
class FlattenModel(torch.nn.Module):
def forward(self, input):
return torch.flatten(input)
x = torch.quantize_per_tensor(torch.randn(1, 2, 3, 4), 1, 0, torch.quint8)
self.run_test(FlattenModel(), x)
@skipIfUnsupportedMinOpsetVersion(10)
@skipScriptTest() # torch.jit.frontend.FrontendError: Cannot instantiate class 'QFunctional' in a script function:
def test_quantized_cat_when_concatinating_the_same_tensor(self):
class QuantizedSelfConcatenationModel(torch.nn.Module):
def forward(self, x):
return torch.ao.nn.quantized.QFunctional().cat((x, x), dim=1)
q_input = torch.quantize_per_tensor(torch.ones(2, 3), 0.26, 128, torch.quint8)
self.run_test(QuantizedSelfConcatenationModel(), q_input)
@common_utils.parametrize(
"x, y",
[
common_utils.subtest(
[
torch.quantize_per_tensor(
torch.ones(2, 3), 0.26, 128, torch.quint8
),
torch.quantize_per_tensor(
torch.zeros(1, 3), 0.26, 128, torch.quint8
),
],
name="different_shape",
),
common_utils.subtest(
[
torch.quantize_per_tensor(
torch.ones(2, 3), 0.26, 128, torch.quint8
),
torch.quantize_per_tensor(torch.ones(2, 3), 42, 1, torch.quint8),
],
name="different_scale",
),
common_utils.subtest(
[
torch.quantize_per_tensor(
torch.ones(2, 3), 0.26, 128, torch.quint8
),
torch.quantize_per_tensor(torch.ones(2, 3), 0.26, 63, torch.quint8),
],
name="different_zero_point",
),
common_utils.subtest(
[
torch.quantize_per_tensor(
torch.ones(2, 3), 0.26, 128, torch.quint8
),
torch.quantize_per_tensor(torch.ones(2, 3), 0.1, 63, torch.quint8),
],
name="different_zero_point_and_scale",
),
],
)
@skipIfUnsupportedMinOpsetVersion(10)
@skipScriptTest() # torch.jit.frontend.FrontendError: Cannot instantiate class 'QFunctional' in a script function:
def test_quantized_cat(self, x: torch.Tensor, y: torch.Tensor):
class QuantizedConcatenationModel(torch.nn.Module):
def forward(self, x, y):
return torch.ao.nn.quantized.QFunctional().cat((x, y), dim=0)
self.run_test(QuantizedConcatenationModel(), (x, y))
@skipIfUnsupportedMinOpsetVersion(10)
# torch.jit.frontend.FrontendError:
# Cannot instantiate class 'QFunctional' in a script function
@skipScriptTest()
def test_quantized_arithmetic_qfunctional(self):
x = torch.quantize_per_tensor(torch.randn(3, 4), 0.2, 128, torch.quint8)
y = torch.quantize_per_tensor(torch.randn(3, 4), 0.2, 128, torch.quint8)
class ArithmeticModel(torch.nn.Module):
def forward(self, x, y):
o = torch.ao.nn.quantized.QFunctional().add(x, y)
o = torch.ao.nn.quantized.QFunctional().mul(o, x)
return o
self.run_test(ArithmeticModel(), (x, y))
@skipIfUnsupportedMinOpsetVersion(10)
def test_quantized_arithmetic(self):
x = torch.quantize_per_tensor(torch.randn(3, 4), 0.2, 128, torch.quint8)
y = torch.quantize_per_tensor(torch.randn(3, 4), 0.2, 128, torch.quint8)
class ArithmeticModel2(torch.nn.Module):
def forward(self, x, y):
o = torch.ops.quantized.add(x, y, 0.4, 100)
o = torch.ops.quantized.mul(o, x, 0.4, 100)
return o
self.run_test(ArithmeticModel2(), (x, y))
@skipIfUnsupportedMinOpsetVersion(10)
def test_quantize_per_tensor(self):
class Module(torch.nn.Module):
def forward(self, x):
return (
torch.quantize_per_tensor(x, 0.2, 0, torch.qint8),
torch.quantize_per_tensor(x, 0.2, 128, torch.quint8),
)
x = torch.randn(4, 6)
self.run_test(Module(), x)
@skipIfUnsupportedMinOpsetVersion(10)
def test_dequantize(self):
class Module(torch.nn.Module):
def forward(self, x):
return torch.dequantize(x)
x = torch.quantize_per_tensor(torch.randn(3, 4), 0.2, 0, torch.qint8)
self.run_test(Module(), x)
@skipIfUnsupportedMinOpsetVersion(13)
def test_qat_linear_per_channel(self):
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.quant = torch.ao.quantization.QuantStub()
self.linear = torch.nn.Linear(4, 3)
self.dequant = torch.ao.quantization.DeQuantStub()
def forward(self, x):
x = self.quant(x)
x = self.linear(x)
x = self.dequant(x)
return x
model = M()
model.qconfig = torch.ao.quantization.get_default_qconfig("fbgemm")
model = torch.ao.quantization.prepare_qat(model)
# Set fixed weight and bias to avoid flaky test.
model.linear.weight = torch.nn.Parameter(
_construct_tensor_for_quantization_test((3, 4))
)
model.linear.bias = torch.nn.Parameter(torch.arange(3, dtype=torch.float))
model = torch.ao.quantization.convert(model)
# Set fixed input to avoid flaky test.
input = _construct_tensor_for_quantization_test((4, 4), offset=-8)
self.run_test(model, input)
@unittest.skip(
"ORT fails with Validating no unexpected access using an invalid node_index on torch converted model"
)
@skipIfUnsupportedMinOpsetVersion(13)
def test_quantized_list_of_inputs_with_cat(self):
class TestModel(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.quant = torch.ao.quantization.QuantStub()
self.dequant = torch.ao.quantization.DeQuantStub()
def forward(self, x):
x = self.quant(x)
x = torch.cat([x, x], 1)
x = self.dequant(x)
return x
model = TestModel()
model.qconfig = torch.ao.quantization.get_default_qconfig("fbgemm")
model = torch.ao.quantization.prepare_qat(model)
model = torch.ao.quantization.convert(model)
x = torch.randn(2, 4, 6)
self.run_test(model, x)
@skipIfUnsupportedMinOpsetVersion(13)
def test_qat_relu(self):
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.quant = torch.ao.quantization.QuantStub()
self.relu = torch.nn.ReLU()
self.dequant = torch.ao.quantization.DeQuantStub()
def forward(self, x):
x = self.quant(x)
x = self.relu(x)
x = self.dequant(x)
return x
model = M()
model.qconfig = torch.ao.quantization.get_default_qconfig("fbgemm")
model = torch.ao.quantization.prepare_qat(model)
model = torch.ao.quantization.convert(model)
input = torch.randn(8, 4)
self.run_test(model, input)
@skipIfUnsupportedMinOpsetVersion(13)
def test_qat_conv2d(self):
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.quant = torch.ao.quantization.QuantStub()
self.conv = torch.nn.Conv2d(4, 2, 3, stride=2)
self.dequant = torch.ao.quantization.DeQuantStub()
def forward(self, x):
x = self.quant(x)
x = self.conv(x)
x = self.dequant(x)
return x
model = M()
model.qconfig = torch.ao.quantization.get_default_qconfig("fbgemm")
model = torch.ao.quantization.prepare_qat(model)
# Set fixed weight and bias to avoid flaky test.
model.conv.weight = torch.nn.Parameter(
_construct_tensor_for_quantization_test((2, 4, 3, 3), max_val=2)
)
model.conv.bias = torch.nn.Parameter(torch.tensor([0.0, 1.0]))
model = torch.ao.quantization.convert(model)
# Set fixed input to avoid flaky test.
input = _construct_tensor_for_quantization_test(
(3, 4, 8, 8), offset=-384, max_val=12
)
self.run_test(model, input)
@skipIfUnsupportedMinOpsetVersion(13)
def test_qat_conv2d_relu(self):
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.quant = torch.ao.quantization.QuantStub()
self.conv = torch.nn.Conv2d(4, 2, 3, stride=2)
self.relu = torch.nn.ReLU()
self.dequant = torch.ao.quantization.DeQuantStub()
def forward(self, x):
x = self.quant(x)
x = self.conv(x)
x = self.relu(x)
x = self.dequant(x)
return x
model = M()
model.qconfig = torch.ao.quantization.get_default_qconfig("fbgemm")
model = torch.ao.quantization.prepare_qat(model)
# Set fixed weight and bias to avoid flaky test.
model.conv.weight = torch.nn.Parameter(
_construct_tensor_for_quantization_test((2, 4, 3, 3), max_val=2)
)
model.conv.bias = torch.nn.Parameter(torch.tensor([0.0, 1.0]))
model = torch.ao.quantization.convert(model)
# Set fixed input to avoid flaky test.
input = _construct_tensor_for_quantization_test(
(3, 4, 8, 8), offset=-384, max_val=12
)
self.run_test(model, input)
@skipIfUnsupportedMinOpsetVersion(13)
def test_qat_conv2d_relu_fused(self):
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.quant = torch.ao.quantization.QuantStub()
self.conv = torch.nn.Conv2d(4, 2, 3, stride=2)
self.relu = torch.nn.ReLU()
self.dequant = torch.ao.quantization.DeQuantStub()
def forward(self, x):
x = self.quant(x)
x = self.conv(x)
x = self.relu(x)
x = self.dequant(x)
return x
model = M()
model.qconfig = torch.ao.quantization.get_default_qconfig("fbgemm")
model = torch.ao.quantization.fuse_modules(model.eval(), [["conv", "relu"]])
model = torch.ao.quantization.prepare_qat(model.train())
# Set fixed weight and bias to avoid flaky test.
model.conv.weight = torch.nn.Parameter(
_construct_tensor_for_quantization_test((2, 4, 3, 3), max_val=2)
)
model.conv.bias = torch.nn.Parameter(torch.tensor([0.0, 1.0]))
model = torch.ao.quantization.convert(model)
# Set fixed input to avoid flaky test.
input = _construct_tensor_for_quantization_test(
(3, 4, 8, 8), offset=-384, max_val=12
)
self.run_test(model, input)
@skipIfUnsupportedMinOpsetVersion(13)
def test_qat_linear_relu_fused(self):
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.quant = torch.ao.quantization.QuantStub()
self.linear = torch.nn.Linear(4, 2)
self.relu = torch.nn.ReLU()
self.dequant = torch.ao.quantization.DeQuantStub()
def forward(self, x):
x = self.quant(x)
x = self.linear(x)
x = self.relu(x)
x = self.dequant(x)
return x
model = M()
model.qconfig = torch.ao.quantization.get_default_qconfig("fbgemm")
model = torch.ao.quantization.fuse_modules(model.eval(), [["linear", "relu"]])
model = torch.ao.quantization.prepare_qat(model.train())
# Set fixed weight and bias to avoid flaky test.
model.linear.weight = torch.nn.Parameter(
_construct_tensor_for_quantization_test((2, 4), max_val=2)
)
model.linear.bias = torch.nn.Parameter(torch.tensor([0.0, 1.0]))
model = torch.ao.quantization.convert(model)
# Set fixed input to avoid flaky test.
input = _construct_tensor_for_quantization_test((3, 4), offset=-384, max_val=12)
self.run_test(model, input)
@skipIfUnsupportedMinOpsetVersion(10)
def test_qat_maxpool2d(self):
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.quant = torch.ao.quantization.QuantStub()
self.pool = torch.nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.dequant = torch.ao.quantization.DeQuantStub()
def forward(self, x):
x = self.quant(x)
x = self.pool(x)
x = self.dequant(x)
return x
model = M()
model.qconfig = torch.ao.quantization.get_default_qconfig("fbgemm")
model = torch.ao.quantization.prepare_qat(model.train())
model = torch.ao.quantization.convert(model)
# Set fixed input to avoid flaky test.
input = _construct_tensor_for_quantization_test((4, 4, 3, 2))
self.run_test(model, input)
@skipIfUnsupportedMinOpsetVersion(10)
@skipScriptTest() # Scale and Zero-point must be a scalar in ORT:optimization
def test_qat_avg_pool2d(self):
model = torch.nn.Sequential(
torch.ao.quantization.QuantStub(),
torch.nn.AvgPool2d(kernel_size=3, stride=2, padding=1),
torch.ao.quantization.DeQuantStub(),
)
model.qconfig = torch.ao.quantization.get_default_qconfig("fbgemm")
model = torch.ao.quantization.prepare_qat(model.train())
model = torch.ao.quantization.convert(model)
input = _construct_tensor_for_quantization_test((4, 4, 3, 2))
self.run_test(model, input)
@skipIfUnsupportedMinOpsetVersion(11)
def test_qat_upsample_nearest2d(self):
model = torch.nn.Sequential(
torch.ao.quantization.QuantStub(),
torch.nn.UpsamplingNearest2d(scale_factor=1.5),
torch.ao.quantization.DeQuantStub(),
)
model.qconfig = torch.ao.quantization.get_default_qconfig("fbgemm")
model = torch.ao.quantization.prepare_qat(model.train())
model = torch.ao.quantization.convert(model)
input = _construct_tensor_for_quantization_test((4, 3, 2, 2))
self.run_test(model, input)
def test_0d_tensor_broadcast(self):
class fn(torch.nn.Module):
def forward(self, x, y):
a = torch.add(x, y)
b = torch.mul(y, y)
return a + b
x = torch.ones(0)
y = torch.ones(1)
self.run_test(fn(), (x, y), input_names=["x", "y"], output_names=["output"])
@skipIfUnsupportedMinOpsetVersion(9)
def test_convolution_allow_tf32(self):
class Module(torch.nn.Module):
def __init__(self, allow_tf32):
super().__init__()
self.allow_tf32 = allow_tf32
weight = torch.rand(32, 3, 3, 3)
self.weight = torch.nn.Parameter(weight)
def forward(self, x):
if self.allow_tf32:
return torch._convolution(
x,
self.weight,
None,
[2, 2],
[0, 0],
[1, 1],
False,
[0, 0],
1,
False,
False,
True,
True,
)
else:
return torch._convolution(
x,
self.weight,
None,
[2, 2],
[0, 0],
[1, 1],
False,
[0, 0],
1,
False,
False,
True,
)
x = torch.randn(1, 3, 224, 224)
self.run_test(Module(False), x, rtol=1e-3, atol=1e-6)
self.run_test(Module(True), x, rtol=1e-3, atol=1e-6)
class AffineGridModule(torch.nn.Module):
def __init__(self, align_corners) -> None:
super().__init__()
self.align_corners = align_corners
def forward(self, theta, size):
return torch.nn.functional.affine_grid(theta, size, self.align_corners)
@skipIfUnsupportedMinOpsetVersion(20)
@skipScriptTest()
@common_utils.parametrize(
"align_corners",
(True, False),
)
@common_utils.parametrize(
"theta_params",
(
(
10,
np.array([0.3, -0.5]),
np.array([1.5, 0.5]),
),
(
60,
np.array([-0.5, -0.5]),
np.array([3.0, 5.5]),
),
),
)
@common_utils.parametrize(
"size",
([1, 1, 3, 2], [2, 10, 2, 3]),
)
def test_affine_grid_2d(self, align_corners, theta_params, size):
angle, translation, scale = theta_params
theta = np.array([], dtype=np.float32)
for _ in range(size[0]):
angle_radian = (angle / 180.0) * np.pi
theta = np.append(
theta,
[
np.cos(angle_radian) * scale[0],
-np.sin(angle_radian),
translation[0],
np.sin(angle_radian),
np.cos(angle_radian) * scale[1],
translation[1],
],
)
theta = theta.reshape(size[0], 2, 3)
theta = torch.Tensor(theta)
self.run_test(TestONNXRuntime.AffineGridModule(align_corners), (theta, size))
@skipIfUnsupportedMinOpsetVersion(20)
@skipScriptTest()
@common_utils.parametrize(
"align_corners",
(True, False),
)
@common_utils.parametrize(
"theta_params",
(
(
[10, 20],
np.array([0.3, -0.5, 1.8]),
np.array([1.5, 2.0, 0.5]),
),
(
[60, -30],
np.array([-0.5, -0.5, 0.3]),
np.array([0.3, 3.0, 5.5]),
),
),
)
@common_utils.parametrize(
"size",
([1, 1, 3, 2, 2], [2, 10, 2, 2, 3]),
)
def test_affine_grid_3d(self, align_corners, theta_params, size):
angle, translation, scale = theta_params
theta = np.array([], dtype=np.float32)
for _ in range(size[0]):
angle_radian_x = (angle[0] / 180.0) * np.pi
angle_radian_y = (angle[1] / 180.0) * np.pi
rot_matrix_x = np.array(
[
[1, 0, 0],
[0, np.cos(angle_radian_x), -np.sin(angle_radian_x)],
[0, np.sin(angle_radian_x), np.cos(angle_radian_x)],
]
)
rot_matrix_y = np.array(
[
[np.cos(angle_radian_y), 0, np.sin(angle_radian_y)],
[0, 1, 0],
[-np.sin(angle_radian_y), 0, np.cos(angle_radian_y)],
]
)
rot_matrix = np.matmul(rot_matrix_x, rot_matrix_y)
rot_matrix = rot_matrix * scale.reshape(3, 1)
rot_matrix = np.append(rot_matrix, np.reshape(translation, (3, 1)), axis=1)
theta = np.append(theta, rot_matrix.flatten())
theta = theta.reshape(size[0], 3, 4)
theta = torch.Tensor(theta)
self.run_test(TestONNXRuntime.AffineGridModule(align_corners), (theta, size))
@skipIfUnsupportedMinOpsetVersion(16)
@common_utils.parametrize(
"mode",
("bilinear", "nearest", "bicubic"),
)
@common_utils.parametrize(
"padding_mode",
("zeros", "border", "reflection"),
)
@common_utils.parametrize(
"align_corners",
(True, False),
name_fn=lambda align_corners: str(align_corners),
)
def test_grid_sample(self, mode, padding_mode, align_corners):
n, c, d_in, h_in, w_in, d_out, h_out, w_out = 1, 1, 2, 3, 2, 3, 2, 4
atol_rtol = {}
if (mode, padding_mode) == ("bicubic", "border"):
if align_corners:
atol_rtol.update({"atol": 0.3, "rtol": 0.4})
else:
atol_rtol.update({"atol": 0.02, "rtol": 0.02})
input, grid = torch.randn(n, c, h_in, w_in), torch.randn(n, h_out, w_out, 2)
class GridSampleModule(torch.nn.Module):
def __init__(self, mode, padding_mode, align_corners) -> None:
super().__init__()
self.mode, self.padding_mode, self.align_corners = (
mode,
padding_mode,
align_corners,
)
def forward(self, input, grid):
return torch.nn.functional.grid_sample(
input, grid, self.mode, self.padding_mode, self.align_corners
)
self.run_test(
GridSampleModule(mode, padding_mode, align_corners),
(input, grid),
**atol_rtol,
)
# ONNX Opset 16 GridSample with 5D volumetric input is not supported.
volumetric_input_tensor = torch.randn(n, c, d_in, h_in, w_in)
volumetric_grid_tensor = torch.randn(n, d_out, h_out, w_out, 3)
for mode, padding_mode, align_corners in itertools.product(
(
"bilinear",
"nearest",
), # PyTorch grid_sample "bicubic" mode does not support 5D volumetric input.
(
"zeros",
"border",
"reflection",
),
(
True,
False,
),
):
if self.opset_version < 20:
with self.assertRaises(
torch.onnx.OnnxExporterError,
):
self.run_test(
GridSampleModule(mode, padding_mode, align_corners),
(volumetric_input_tensor, volumetric_grid_tensor),
**atol_rtol,
)
else:
self.run_test(
GridSampleModule(mode, padding_mode, align_corners),
(volumetric_input_tensor, volumetric_grid_tensor),
**atol_rtol,
)
class IfNoneInput(torch.nn.Module):
def forward(self, x) -> Optional[Tensor]:
y: Optional[Tensor] = None
if x.size(0) > 1:
y = x
return y
class IfNoneOutput(torch.nn.Module):
def forward(self, x) -> Optional[Tensor]:
y: Optional[Tensor] = x
if x.size(0) > 1:
y = None
return y
class LoopNoneInput(torch.nn.Module):
def forward(self, x) -> Optional[Tensor]:
y: Optional[Tensor] = None
for _ in range(x.size(0)):
y = x
return y
class LoopNoneOutput(torch.nn.Module):
def forward(self, x) -> Optional[Tensor]:
y: Optional[Tensor] = x
for _ in range(x.size(0)):
y = None
return y
@common_utils.parametrize(
"module_class",
(IfNoneOutput, IfNoneInput, LoopNoneOutput, LoopNoneInput),
name_fn=lambda module_class: module_class.__name__,
)
@common_utils.parametrize("x_size", (0, 1), name_fn=lambda x_size: str(x_size))
@skipTraceTest()
@skipIfUnsupportedMinOpsetVersion(16)
def test_optional_output(self, module_class: type[torch.nn.Module], x_size: int):
# Need scripting to preserve control flow for this test to be
# meaningful.
model = torch.jit.script(module_class())
f = io.BytesIO()
x = torch.ones(x_size)
dynamic_axis_name = "condition"
torch.onnx.export(
model,
x,
f,
opset_version=self.opset_version,
# Ensure condition is not constant
dynamic_axes={"x": {0: dynamic_axis_name}},
input_names=["x"],
dynamo=False,
)
exported = onnx.load_from_string(f.getvalue())
expected_elem_type = JitScalarType.from_value(x).onnx_type()
expected_output_type = onnx.helper.make_optional_type_proto(
onnx.helper.make_tensor_type_proto(expected_elem_type, (dynamic_axis_name,))
)
self.assertEqual(expected_output_type, exported.graph.output[0].type)
for node in exported.graph.node:
# Both branches output types should match.
if node.op_type == "If":
for attr in node.attribute:
if attr.name in ("then_branch", "else_branch"):
self.assertEqual(expected_output_type, attr.g.output[0].type)
self.run_test(
module_class(),
x,
# Ensure condition is not constant
dynamic_axes={"x": {0: dynamic_axis_name}},
input_names=["x"],
)
@skipTraceTest()
@skipIfUnsupportedMinOpsetVersion(16)
def test_uninitialized_optional(self):
class Module(torch.nn.Module):
def forward(self, y: Optional[Tensor]) -> Optional[Tensor]:
if y is not None:
if y.shape[1] < 5:
if y.size(0) == 1:
y = y + 4
else:
return y
return y
self.run_test(
Module(),
torch.ones((3, 4), dtype=torch.int),
dynamic_axes={"y": {0: "y0", 1: "y1"}},
input_names=["y"],
)
@skipIfUnsupportedMinOpsetVersion(9)
def test_device_eq(self):
class M(torch.nn.Module):
def forward(self, a):
# exercise both Tensor.device (prim::device)
# and torch.device (prim::Constant).
if a.device != torch.device("cpu"):
return a
return torch.zeros_like(a)
mod = torch.jit.script(M()) # preserve control flow
self.run_test(
mod,
# In order for the ONNX model behavior to match the torch model, we
# need to construct input that has the same device that is checked for
# in forward(). In ONNX there is no such thing as a device, so the if
# condition is always false.
torch.randn(3, 3, device="cpu"),
# Force dynamic axes so that the output shape depends on the input.
# Otherwise the entire model will just return a constant and not have
# any inputs.
input_names=["a"],
dynamic_axes={"a": {0: "a0"}},
)
@skipIfUnsupportedMinOpsetVersion(9)
def test_lerp(self):
class LerpModel(torch.nn.Module):
def forward(self, x):
return (
x.lerp(torch.full_like(x, 10), 0.4),
x.lerp(torch.full_like(x, 20), 0.7),
x.lerp(torch.full_like(x, 30), torch.tensor(0.4)),
x.lerp(torch.full_like(x, 40), x / 10.0),
x.lerp(torch.tensor(10.0), x / 10.0),
x.lerp(torch.tensor(10.0), 0.4),
x.lerp(torch.tensor(10.0), torch.tensor(0.4)),
)
self.run_test(LerpModel(), torch.rand(5, 4, 3))
@common_utils.parametrize("input_dtype", [torch.cfloat, torch.float])
@skipIfUnsupportedMinOpsetVersion(9)
def test_print_tensor_within_torch_nn_module(self, input_dtype: torch.dtype):
class PrintTensorOnMyModel(torch.nn.Module):
def forward(self, x):
# 'print' has side effect calling 'resolve_conj' and 'resolve_neg'.
x_firsts = x[:, 0]
print(f"x_firsts: {x_firsts}")
# 'tolist' has side effect calling 'resolve_conj' and 'resolve_neg'.
# Annotation added to pass torch script.
_: list[float] = x.tolist()
return x_firsts
m = PrintTensorOnMyModel()
x = torch.randn(10, 5, dtype=input_dtype)
if input_dtype == torch.cfloat:
with self.assertRaises(RuntimeError):
self.run_test(
m,
x,
)
else:
self.run_test(
m,
x,
)
@skipScriptTest()
@skipIfUnsupportedMinOpsetVersion(16)
@unittest.skipIf(
not torch.hub._check_module_exists("torch_geometric"),
"torch_geometric not installed.",
)
def test_sage_conv(self):
from torch_geometric import nn as torch_geometric_nn
# Input
coords0 = torch.randn(1, 6)
coords1 = torch.randn(1, 6)
coords = torch.transpose(torch.cat((coords0, coords1), dim=0), 0, 1)
adj = torch_geometric_nn.knn_graph(coords, k=2, batch=None, loop=True)
edge_from = adj[0:1, :]
edge_to = adj[1:, :]
inputs = (coords0, coords1, edge_from, edge_to)
class MySAGEConv(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.SAGEConvBlock1 = torch_geometric_nn.SAGEConv(
2, 512, normalize=True
)
self.bano1 = torch_geometric_nn.BatchNorm(512)
self.relu = torch.nn.ReLU()
self.dense1 = torch.nn.Seq(Lin(512, 1)) # noqa: F821
self.sigmoid = torch.nn.Sigmoid()
def forward(self, coords0, coords1, edge_from, edge_to):
adj = torch.cat((edge_from, edge_to), dim=0)
gra = torch.transpose(torch.cat((coords0, coords1), dim=0), 0, 1)
x1 = self.SAGEConvBlock1(gra, edge_index=adj)
x = torch.unsqueeze(torch.sum(x1), dim=0)
return x
input_names = ["coords0", "coords1", "edge_from", "edge_to"]
output_names = ["outputs"]
dynamic_axes = {
"coords0": {0: "batch_size", 1: "features"},
"coords1": {0: "batch_size", 1: "features"},
"edge_from": {0: "batch_size", 1: "features"},
"edge_to": {0: "batch_size", 1: "features"},
"outputs": {0: "batch_size"},
}
self.run_test(
MySAGEConv(),
inputs,
input_names=input_names,
output_names=output_names,
dynamic_axes=dynamic_axes,
)
# Cannot export with older opsets because of "ConstantFill" op
# ConstantFill was a temp op removed at opset 8. This is no longer supported by onnxruntime
# There are still some issues prevent us from enabling script test for these scenarios:
# test_gru_*:
# Operator aten::as_tensor is not supported by exporter yet.
# - https://msdata.visualstudio.com/Vienna/_workitems/edit/1055382
# Operator aten::_pack_padded_sequence is not supported by exporter yet.
# - https://msdata.visualstudio.com/Vienna/_workitems/edit/1055384
# test_elman_*:
# Compiling in script mode fails with errors like:
# torch.jit.frontend.UnsupportedNodeError: annotated assignments
# without assigned value aren't supported
# - https://msdata.visualstudio.com/Vienna/_workitems/edit/1160723
# test_lstm_*:
# Compiling in script mode fails with errors like:
# RuntimeError: Arguments for call are not valid.
# - https://msdata.visualstudio.com/Vienna/_workitems/edit/1160723
@skipScriptTest()
@skipIfUnsupportedMinOpsetVersion(9)
@common_utils.parametrize(
"name, nonlinearity",
[
("elman", "relu"),
("elman", "tanh"),
("lstm", None),
("gru", None),
],
)
@common_utils.parametrize(**_parametrize_rnn_args("layers"))
@common_utils.parametrize(**_parametrize_rnn_args("bidirectional"))
@common_utils.parametrize(**_parametrize_rnn_args("initial_state"))
@common_utils.parametrize(**_parametrize_rnn_args("packed_sequence"))
@common_utils.parametrize(**_parametrize_rnn_args("dropout"))
def test_rnn(self, *args, **kwargs):
self._dispatch_rnn_test(*args, **kwargs)
if __name__ == "__main__":
common_utils.TestCase._default_dtype_check_enabled = True
common_utils.run_tests()
|
TestONNXRuntime
|
python
|
walkccc__LeetCode
|
solutions/315. Count of Smaller Numbers After Self/315.py
|
{
"start": 421,
"end": 898
}
|
class ____:
def countSmaller(self, nums: list[int]) -> list[int]:
ans = []
ranks = self._getRanks(nums)
tree = FenwickTree(len(ranks))
for num in reversed(nums):
ans.append(tree.get(ranks[num] - 1))
tree.add(ranks[num], 1)
return ans[::-1]
def _getRanks(self, nums: list[int]) -> dict[int, int]:
ranks = collections.Counter()
rank = 0
for num in sorted(set(nums)):
rank += 1
ranks[num] = rank
return ranks
|
Solution
|
python
|
plotly__plotly.py
|
plotly/graph_objs/sunburst/_insidetextfont.py
|
{
"start": 233,
"end": 17196
}
|
class ____(_BaseTraceHierarchyType):
_parent_path_str = "sunburst"
_path_str = "sunburst.insidetextfont"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"size",
"sizesrc",
"style",
"stylesrc",
"textcase",
"textcasesrc",
"variant",
"variantsrc",
"weight",
"weightsrc",
}
@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
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `color`.
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"]
@colorsrc.setter
def colorsrc(self, val):
self["colorsrc"] = 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
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
@property
def familysrc(self):
"""
Sets the source reference on Chart Studio Cloud for `family`.
The 'familysrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["familysrc"]
@familysrc.setter
def familysrc(self, val):
self["familysrc"] = 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')
- A list or array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = val
@property
def linepositionsrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`lineposition`.
The 'linepositionsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["linepositionsrc"]
@linepositionsrc.setter
def linepositionsrc(self, val):
self["linepositionsrc"] = 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
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
str|numpy.ndarray
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = val
@property
def shadowsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `shadow`.
The 'shadowsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["shadowsrc"]
@shadowsrc.setter
def shadowsrc(self, val):
self["shadowsrc"] = 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]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def sizesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `size`.
The 'sizesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["sizesrc"]
@sizesrc.setter
def sizesrc(self, val):
self["sizesrc"] = 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']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = val
@property
def stylesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `style`.
The 'stylesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["stylesrc"]
@stylesrc.setter
def stylesrc(self, val):
self["stylesrc"] = 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']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = val
@property
def textcasesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `textcase`.
The 'textcasesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["textcasesrc"]
@textcasesrc.setter
def textcasesrc(self, val):
self["textcasesrc"] = 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']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = val
@property
def variantsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `variant`.
The 'variantsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["variantsrc"]
@variantsrc.setter
def variantsrc(self, val):
self["variantsrc"] = 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')
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|numpy.ndarray
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
@property
def weightsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `weight`.
The 'weightsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["weightsrc"]
@weightsrc.setter
def weightsrc(self, val):
self["weightsrc"] = val
@property
def _prop_descriptions(self):
return """\
color
colorsrc
Sets the source reference on Chart Studio Cloud for
`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.
familysrc
Sets the source reference on Chart Studio Cloud for
`family`.
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.
linepositionsrc
Sets the source reference on Chart Studio Cloud for
`lineposition`.
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.
shadowsrc
Sets the source reference on Chart Studio Cloud for
`shadow`.
size
sizesrc
Sets the source reference on Chart Studio Cloud for
`size`.
style
Sets whether a font should be styled with a normal or
italic face from its family.
stylesrc
Sets the source reference on Chart Studio Cloud for
`style`.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
textcasesrc
Sets the source reference on Chart Studio Cloud for
`textcase`.
variant
Sets the variant of the font.
variantsrc
Sets the source reference on Chart Studio Cloud for
`variant`.
weight
Sets the weight (or boldness) of the font.
weightsrc
Sets the source reference on Chart Studio Cloud for
`weight`.
"""
def __init__(
self,
arg=None,
color=None,
colorsrc=None,
family=None,
familysrc=None,
lineposition=None,
linepositionsrc=None,
shadow=None,
shadowsrc=None,
size=None,
sizesrc=None,
style=None,
stylesrc=None,
textcase=None,
textcasesrc=None,
variant=None,
variantsrc=None,
weight=None,
weightsrc=None,
**kwargs,
):
"""
Construct a new Insidetextfont object
Sets the font used for `textinfo` lying inside the sector.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.sunburst.Insidetextfont`
color
colorsrc
Sets the source reference on Chart Studio Cloud for
`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.
familysrc
Sets the source reference on Chart Studio Cloud for
`family`.
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.
linepositionsrc
Sets the source reference on Chart Studio Cloud for
`lineposition`.
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.
shadowsrc
Sets the source reference on Chart Studio Cloud for
`shadow`.
size
sizesrc
Sets the source reference on Chart Studio Cloud for
`size`.
style
Sets whether a font should be styled with a normal or
italic face from its family.
stylesrc
Sets the source reference on Chart Studio Cloud for
`style`.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
textcasesrc
Sets the source reference on Chart Studio Cloud for
`textcase`.
variant
Sets the variant of the font.
variantsrc
Sets the source reference on Chart Studio Cloud for
`variant`.
weight
Sets the weight (or boldness) of the font.
weightsrc
Sets the source reference on Chart Studio Cloud for
`weight`.
Returns
-------
Insidetextfont
"""
super().__init__("insidetextfont")
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.sunburst.Insidetextfont
constructor must be a dict or
an instance of :class:`plotly.graph_objs.sunburst.Insidetextfont`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("colorsrc", arg, colorsrc)
self._set_property("family", arg, family)
self._set_property("familysrc", arg, familysrc)
self._set_property("lineposition", arg, lineposition)
self._set_property("linepositionsrc", arg, linepositionsrc)
self._set_property("shadow", arg, shadow)
self._set_property("shadowsrc", arg, shadowsrc)
self._set_property("size", arg, size)
self._set_property("sizesrc", arg, sizesrc)
self._set_property("style", arg, style)
self._set_property("stylesrc", arg, stylesrc)
self._set_property("textcase", arg, textcase)
self._set_property("textcasesrc", arg, textcasesrc)
self._set_property("variant", arg, variant)
self._set_property("variantsrc", arg, variantsrc)
self._set_property("weight", arg, weight)
self._set_property("weightsrc", arg, weightsrc)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
|
Insidetextfont
|
python
|
kennethreitz__tablib
|
tests/test_tablib.py
|
{
"start": 29346,
"end": 30592
}
|
class ____(BaseTestCase):
def test_tsv_import_set(self):
"""Generate and import TSV set serialization."""
data.append(self.john)
data.append(self.george)
data.headers = self.headers
_tsv = data.tsv
data.tsv = _tsv
self.assertEqual(_tsv, data.tsv)
def test_tsv_format_detect(self):
"""Test TSV format detection."""
_tsv = StringIO(
'1\t2\t3\n'
'4\t5\t6\n'
'7\t8\t9\n'
)
_bunk = StringIO(
'¡¡¡¡¡¡¡¡£™∞¢£§∞§¶•¶ª∞¶•ªº••ª–º§•†•§º¶•†¥ª–º•§ƒø¥¨©πƒø†ˆ¥ç©¨√øˆ¥≈†ƒ¥ç©ø¨çˆ¥ƒçø¶'
)
fmt = registry.get_format('tsv')
self.assertTrue(fmt.detect(_tsv))
self.assertFalse(fmt.detect(_bunk))
def test_tsv_export(self):
"""Verify exporting dataset object as TSV."""
# Build up the tsv string with headers first, followed by each row
tsv = ''
for col in self.headers:
tsv += col + '\t'
tsv = tsv.strip('\t') + '\r\n'
for founder in self.founders:
for col in founder:
tsv += str(col) + '\t'
tsv = tsv.strip('\t') + '\r\n'
self.assertEqual(tsv, self.founders.tsv)
|
TSVTests
|
python
|
davidhalter__jedi
|
test/completion/inheritance.py
|
{
"start": 1,
"end": 113
}
|
class ____(object):
attribute = 3
def func(self):
return 1
class Inner():
pass
|
Super
|
python
|
MongoEngine__mongoengine
|
tests/fixtures.py
|
{
"start": 105,
"end": 194
}
|
class ____(EmbeddedDocument):
date = DateTimeField(default=datetime.now)
|
PickleEmbedded
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.