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 | encode__django-rest-framework | tests/test_validators.py | {
"start": 815,
"end": 983
} | class ____(models.Model):
user = models.OneToOneField(UniquenessModel, on_delete=models.CASCADE)
email = models.CharField(unique=True, max_length=80)
| RelatedModel |
python | optuna__optuna | tests/artifacts_tests/stubs.py | {
"start": 234,
"end": 589
} | class ____:
def open_reader(self, artifact_id: str) -> BinaryIO:
raise Exception("something error raised")
def write(self, artifact_id: str, content_body: BinaryIO) -> None:
raise Exception("something error raised")
def remove(self, artifact_id: str) -> None:
raise Exception("something error raised")
| FailArtifactStore |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/tokens.py | {
"start": 8620,
"end": 8711
} | class ____(Token):
__slots__ = ()
id = '<block mapping start>'
| BlockMappingStartToken |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_numeric.py | {
"start": 102865,
"end": 103267
} | class ____(TestCase):
def test_outer_out_param(self):
arr1 = np.ones((5,))
arr2 = np.ones((2,))
arr3 = np.linspace(-2, 2, 5)
out1 = np.empty(shape=(5, 5))
out2 = np.empty(shape=(2, 5))
res1 = np.outer(arr1, arr3, out1)
assert_equal(res1, out1)
assert_equal(np.outer(arr2, arr3, out2), out2)
@instantiate_parametrized_tests
| TestOuterMisc |
python | astropy__astropy | astropy/units/format/vounit.py | {
"start": 694,
"end": 8093
} | class ____(Base, _GenericParserMixin):
"""
The IVOA standard for units used by the VO.
This is an implementation of `Units in the VO 1.0
<https://www.ivoa.net/documents/VOUnits/20140523/index.html>`_.
"""
_explicit_custom_unit_regex: ClassVar[Pattern[str]] = re.compile(
r"^[YZEPTGMkhdcmunpfazy]?'((?!\d)\w)+'$"
)
_custom_unit_regex: ClassVar[Pattern[str]] = re.compile(r"^((?!\d)\w)+$")
_custom_units: ClassVar[dict[str, UnitBase]] = {}
_space: ClassVar[str] = "."
_scale_unit_separator: ClassVar[str] = ""
@classproperty(lazy=True)
def _all_units(cls) -> tuple[dict[str, UnitBase], frozenset[str]]:
from astropy import units as u
from astropy.units import required_by_vounit as uvo
names = {"as": u.attosecond}
deprecated_names = set()
# The tropical year is missing here compared to the standard
bases = [
"A", "a", "adu", "arcmin", "arcsec", "barn", "beam", "bin",
"C", "cd", "chan", "count", "ct", "d", "D", "deg", "erg", "eV",
"F", "g", "G", "H", "h", "Hz", "J", "Jy", "K", "lm", "lx", "lyr",
"m", "mag", "min", "mol", "N", "Ohm", "Pa", "pc", "ph", "photon",
"pix", "pixel", "R", "rad", "Ry", "s", "S", "solLum", "solMass",
"solRad", "sr", "T", "u", "V", "voxel", "W", "Wb", "yr",
] # fmt: skip
binary_bases = ["bit", "byte", "B"]
simple_units = ["Angstrom", "angstrom", "AU", "au", "Ba", "dB", "mas", "Sun"]
si_prefixes = [
"y", "z", "a", "f", "p", "n", "u", "m", "c", "d",
"", "da", "h", "k", "M", "G", "T", "P", "E", "Z", "Y"
] # fmt: skip
binary_prefixes = ["Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"]
deprecated_units = {"angstrom", "Angstrom", "Ba", "barn", "erg", "G", "ta"}
def do_defines(bases, prefixes, skips=[]):
for base in bases:
for prefix in prefixes:
if (key := prefix + base) not in skips:
names[key] = getattr(u if hasattr(u, key) else uvo, key)
if base in deprecated_units:
deprecated_names.add(key)
do_defines(bases, si_prefixes, ["pct", "pcount", "yd", "as"])
do_defines(binary_bases, si_prefixes + binary_prefixes, ["dB", "dbyte"])
do_defines(simple_units, [""])
return names, frozenset(deprecated_names)
@classproperty(lazy=True)
def _units(cls) -> dict[str, UnitBase]:
return cls._all_units[0]
@classproperty(lazy=True)
def _deprecated_units(cls) -> frozenset[str]:
return cls._all_units[1]
@classmethod
def parse(cls, s: str, debug: bool = False) -> UnitBase:
if s in ("unknown", "UNKNOWN"):
return None
if s == "":
return dimensionless_unscaled
# Check for excess solidi, but exclude fractional exponents (allowed)
if s.count("/") > 1 and s.count("/") - len(re.findall(r"\(\d+/\d+\)", s)) > 1:
raise UnitsError(
f"'{s}' contains multiple slashes, which is "
"disallowed by the VOUnit standard."
)
result = cls._do_parse(s, debug)
if hasattr(result, "function_unit"):
raise ValueError("Function units are not yet supported in VOUnit.")
return result
@classmethod
def _get_unit(cls, t: LexToken) -> UnitBase:
try:
return super()._get_unit(t)
except ValueError:
if cls._explicit_custom_unit_regex.match(t.value):
return cls._def_custom_unit(t.value)
if cls._custom_unit_regex.match(t.value):
warnings.warn(
cls._invalid_unit_error_message(t.value), UnitParserWarning
)
return cls._def_custom_unit(t.value)
raise
@classmethod
def _decompose_to_known_units(
cls,
unit: CompositeUnit | NamedUnit,
deprecations: DeprecatedUnitAction = DeprecatedUnitAction.WARN,
) -> UnitBase:
# The da- and d- prefixes are discouraged. This has the
# effect of adding a scale to value in the result.
if isinstance(unit, PrefixUnit) and unit._represents.scale in (0.1, 10.0):
return cls._decompose_to_known_units(unit._represents)
if (
isinstance(unit, NamedUnit)
and unit._get_format_name(cls.name) in cls._custom_units
):
return unit
return super()._decompose_to_known_units(unit, deprecations)
@classmethod
def _def_custom_unit(cls, unit: str) -> UnitBase:
def def_base(name):
if name in cls._custom_units:
return cls._custom_units[name]
if name.startswith("'"):
return def_unit(
[name[1:-1], name],
format={"vounit": name},
namespace=cls._custom_units,
)
else:
return def_unit(name, namespace=cls._custom_units)
if unit in cls._custom_units:
return cls._custom_units[unit]
for short, _, factor in si_prefixes:
for prefix in short:
if unit.startswith(prefix):
base_name = unit[len(prefix) :]
base_unit = def_base(base_name)
return PrefixUnit(
[prefix + x for x in base_unit.names],
CompositeUnit(factor, [base_unit], [1], _error_check=False),
format={"vounit": prefix + base_unit.names[-1]},
namespace=cls._custom_units,
)
return def_base(unit)
@classmethod
def _format_superscript(cls, number: str) -> str:
return f"**({number})" if "/" in number or "." in number else f"**{number}"
@classmethod
def format_exponential_notation(
cls, val: UnitScale | np.number, format_spec: str = ".8g"
) -> str:
return format(val, format_spec)
@classmethod
def _format_inline_fraction(
cls, scale: str, numerator: str, denominator: str
) -> str:
if cls._space in denominator:
denominator = f"({denominator})"
if scale and numerator == "1":
return f"{scale}/{denominator}"
return f"{scale}{numerator}/{denominator}"
@classmethod
def to_string(
cls,
unit: UnitBase,
fraction: bool | Literal["inline", "multiline"] = False,
deprecations: DeprecatedUnitAction = DeprecatedUnitAction.WARN,
) -> str:
# Remove units that aren't known to the format
unit = cls._decompose_to_known_units(unit, deprecations)
if unit.physical_type == "dimensionless" and unit.scale != 1:
raise UnitScaleError(
"The VOUnit format is not able to "
"represent scale for dimensionless units. "
f"Multiply your data by {unit.scale:e}."
)
return super().to_string(unit, fraction=fraction)
@classmethod
def _fix_deprecated(cls, x: str) -> list[str]:
return (
[f"{x} (deprecated)", cls.to_string(cls._units[x]._represents)]
if x in cls._deprecated_units
else [x]
)
| VOUnit |
python | allegroai__clearml | clearml/backend_api/services/v2_23/workers.py | {
"start": 64045,
"end": 70435
} | class ____(Request):
"""
Returns statistics for the selected workers and time range aggregated by date intervals.
:param worker_ids: List of worker ids to collect metrics for. If not provided
or empty then all the company workers metrics are analyzed.
:type worker_ids: Sequence[str]
:param from_date: Starting time (in seconds from epoch) for collecting
statistics
:type from_date: float
:param to_date: Ending time (in seconds from epoch) for collecting statistics
:type to_date: float
:param interval: Time interval in seconds for a single statistics point. The
minimal value is 1
:type interval: int
:param items: List of metric keys and requested statistics
:type items: Sequence[StatItem]
:param split_by_variant: If true then break statistics by hardware sub types
:type split_by_variant: bool
"""
_service = "workers"
_action = "get_stats"
_version = "2.23"
_schema = {
"definitions": {
"aggregation_type": {
"description": "Metric aggregation type",
"enum": ["avg", "min", "max"],
"type": "string",
},
"stat_item": {
"properties": {
"category": {
"oneOf": [
{"$ref": "#/definitions/aggregation_type"},
{"type": "null"},
]
},
"key": {
"description": "Name of a metric",
"type": ["string", "null"],
},
},
"type": "object",
},
},
"properties": {
"from_date": {
"description": "Starting time (in seconds from epoch) for collecting statistics",
"type": "number",
},
"interval": {
"description": "Time interval in seconds for a single statistics point. The minimal value is 1",
"type": "integer",
},
"items": {
"description": "List of metric keys and requested statistics",
"items": {"$ref": "#/definitions/stat_item"},
"type": "array",
},
"split_by_variant": {
"default": False,
"description": "If true then break statistics by hardware sub types",
"type": "boolean",
},
"to_date": {
"description": "Ending time (in seconds from epoch) for collecting statistics",
"type": "number",
},
"worker_ids": {
"description": "List of worker ids to collect metrics for. If not provided or empty then all the company workers metrics are analyzed.",
"items": {"type": "string"},
"type": ["array", "null"],
},
},
"required": ["from_date", "to_date", "interval", "items"],
"type": "object",
}
def __init__(
self,
from_date: float,
to_date: float,
interval: int,
items: List[Any],
worker_ids: Optional[List[str]] = None,
split_by_variant: Optional[bool] = False,
**kwargs: Any
) -> None:
super(GetStatsRequest, self).__init__(**kwargs)
self.worker_ids = worker_ids
self.from_date = from_date
self.to_date = to_date
self.interval = interval
self.items = items
self.split_by_variant = split_by_variant
@schema_property("worker_ids")
def worker_ids(self) -> Optional[List[str]]:
return self._property_worker_ids
@worker_ids.setter
def worker_ids(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_worker_ids = None
return
self.assert_isinstance(value, "worker_ids", (list, tuple))
self.assert_isinstance(value, "worker_ids", six.string_types, is_array=True)
self._property_worker_ids = value
@schema_property("from_date")
def from_date(self) -> float:
return self._property_from_date
@from_date.setter
def from_date(self, value: float) -> None:
if value is None:
self._property_from_date = None
return
self.assert_isinstance(value, "from_date", six.integer_types + (float,))
self._property_from_date = value
@schema_property("to_date")
def to_date(self) -> float:
return self._property_to_date
@to_date.setter
def to_date(self, value: float) -> None:
if value is None:
self._property_to_date = None
return
self.assert_isinstance(value, "to_date", six.integer_types + (float,))
self._property_to_date = value
@schema_property("interval")
def interval(self) -> int:
return self._property_interval
@interval.setter
def interval(self, value: int) -> None:
if value is None:
self._property_interval = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "interval", six.integer_types)
self._property_interval = value
@schema_property("items")
def items(self) -> List[Any]:
return self._property_items
@items.setter
def items(self, value: List[Any]) -> None:
if value is None:
self._property_items = None
return
self.assert_isinstance(value, "items", (list, tuple))
if any((isinstance(v, dict) for v in value)):
value = [StatItem.from_dict(v) if isinstance(v, dict) else v for v in value]
else:
self.assert_isinstance(value, "items", StatItem, is_array=True)
self._property_items = value
@schema_property("split_by_variant")
def split_by_variant(self) -> Optional[bool]:
return self._property_split_by_variant
@split_by_variant.setter
def split_by_variant(self, value: Optional[bool]) -> None:
if value is None:
self._property_split_by_variant = None
return
self.assert_isinstance(value, "split_by_variant", (bool,))
self._property_split_by_variant = value
| GetStatsRequest |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py | {
"start": 10569,
"end": 12335
} | class ____:
assetKey = graphene.Field(GrapheneAssetKey)
runOrError = graphene.NonNull("dagster_graphql.schema.pipelines.pipeline.GrapheneRunOrError")
stepStats = graphene.NonNull(lambda: GrapheneRunStepStats)
partition = graphene.Field(graphene.String)
tags = non_null_list(GrapheneEventTag)
def __init__(self, event: EventLogEntry, metadata):
self._event = event
self._metadata = metadata
def resolve_assetKey(self, _graphene_info) -> Optional[GrapheneAssetKey]:
asset_key = self._metadata.asset_key
if not asset_key:
return None
return GrapheneAssetKey(path=asset_key.path)
async def resolve_runOrError(
self,
graphene_info: ResolveInfo,
) -> Union["GrapheneRun", GrapheneRunNotFoundError]:
return await gen_run_by_id(graphene_info, self._event.run_id)
def resolve_stepStats(self, graphene_info) -> "GrapheneRunStepStats":
run_id = self.runId # type: ignore # (value obj access)
step_key = self.stepKey # type: ignore # (value obj access)
stats = get_step_stats(graphene_info, run_id, step_keys=[step_key])
return stats[0]
def resolve_metadataEntries(self, _graphene_info: ResolveInfo):
from dagster_graphql.implementation.events import _to_metadata_entries
return _to_metadata_entries(self._metadata.metadata)
def resolve_partition(self, _graphene_info: ResolveInfo):
return self._metadata.partition
def resolve_tags(self, _graphene_info):
if self._metadata.tags is None:
return []
else:
return [
GrapheneEventTag(key=key, value=value) for key, value in self._metadata.tags.items()
]
| AssetEventMixin |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_bigquery.py | {
"start": 15183,
"end": 17776
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.bigquery.BigQueryHook")
def test_execute(self, mock_hook):
table_resource = {"friendlyName": "Test TB"}
operator = BigQueryUpdateTableOperator(
table_resource=table_resource,
task_id=TASK_ID,
dataset_id=TEST_DATASET,
table_id=TEST_TABLE_ID,
project_id=TEST_GCP_PROJECT_ID,
)
operator.execute(context=MagicMock())
mock_hook.return_value.update_table.assert_called_once_with(
table_resource=table_resource,
fields=None,
dataset_id=TEST_DATASET,
table_id=TEST_TABLE_ID,
project_id=TEST_GCP_PROJECT_ID,
)
@mock.patch("airflow.providers.google.cloud.operators.bigquery.BigQueryHook")
def test_get_openlineage_facets_on_complete(self, mock_hook):
table_resource = {
"tableReference": {
"projectId": TEST_GCP_PROJECT_ID,
"datasetId": TEST_DATASET,
"tableId": TEST_TABLE_ID,
},
"description": "Table description.",
"schema": {
"fields": [
{"name": "field1", "type": "STRING", "description": "field1 description"},
{"name": "field2", "type": "INTEGER"},
]
},
}
mock_hook.return_value.update_table.return_value = table_resource
operator = BigQueryUpdateTableOperator(
table_resource={},
task_id=TASK_ID,
dataset_id=TEST_DATASET,
table_id=TEST_TABLE_ID,
project_id=TEST_GCP_PROJECT_ID,
)
operator.execute(context=MagicMock())
result = operator.get_openlineage_facets_on_complete(None)
assert not result.run_facets
assert not result.job_facets
assert not result.inputs
assert len(result.outputs) == 1
assert result.outputs[0].namespace == BIGQUERY_NAMESPACE
assert result.outputs[0].name == f"{TEST_GCP_PROJECT_ID}.{TEST_DATASET}.{TEST_TABLE_ID}"
assert result.outputs[0].facets == {
"schema": SchemaDatasetFacet(
fields=[
SchemaDatasetFacetFields(name="field1", type="STRING", description="field1 description"),
SchemaDatasetFacetFields(name="field2", type="INTEGER"),
]
),
"documentation": DocumentationDatasetFacet(description="Table description."),
}
| TestBigQueryUpdateTableOperator |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/lambda13.py | {
"start": 527,
"end": 940
} | class ____(Generic[T]):
def __init__(self, value: T) -> None:
self.value = value
def func2(callable: Callable[[type[A[T]]], A[T]]) -> T:
return callable(A).value
v3 = func2(lambda A: A(0))
reveal_type(v3, expected_text="int")
v4 = func2(lambda A: A(""))
reveal_type(v4, expected_text="str")
def test2(untyped):
v1 = func2(lambda A: A(untyped))
reveal_type(v1, expected_text="Unknown")
| A |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/pg8000.py | {
"start": 4746,
"end": 4843
} | class ____(_PGNumeric):
def bind_processor(self, dialect):
return None
| _PGNumericNoBind |
python | huggingface__transformers | src/transformers/models/udop/modeling_udop.py | {
"start": 10828,
"end": 15716
} | class ____(PreTrainedModel):
config: UdopConfig
base_model_prefix = "transformer"
input_modalities = ("image", "text")
supports_gradient_checkpointing = True
_can_compile_fullgraph = False
_keep_in_fp32_modules = ["wo"]
@torch.no_grad()
def _init_weights(self, module):
"""Initialize the weights"""
factor = self.config.initializer_factor # Used for testing weights initialization
if isinstance(module, UdopLayerNorm):
init.constant_(module.weight, factor * 1.0)
elif isinstance(module, nn.Embedding):
init.normal_(module.weight, mean=0.0, std=factor)
# Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
init.zeros_(module.weight[module.padding_idx])
elif isinstance(module, nn.Conv2d):
init.trunc_normal_(module.weight, mean=0.0, std=factor)
if module.bias is not None:
init.zeros_(module.bias)
elif isinstance(module, RelativePositionBiasBase):
factor = self.config.initializer_factor
d_model = self.config.d_model
init.normal_(module.relative_attention_bias.weight, mean=0.0, std=factor * ((d_model) ** -0.5))
elif isinstance(module, UdopModel):
init.normal_(module.shared.weight, mean=0.0, std=factor * 1.0)
elif isinstance(module, UdopForConditionalGeneration):
if hasattr(module, "lm_head") and not self.config.tie_word_embeddings:
init.normal_(module.lm_head.weight, mean=0.0, std=factor * 1.0)
elif isinstance(module, UdopDenseActDense):
init.normal_(module.wi.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
if hasattr(module.wi, "bias") and module.wi.bias is not None:
init.zeros_(module.wi.bias)
init.normal_(module.wo.weight, mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
if hasattr(module.wo, "bias") and module.wo.bias is not None:
init.zeros_(module.wo.bias)
elif isinstance(module, UdopDenseGatedActDense):
init.normal_(module.wi_0.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
if hasattr(module.wi_0, "bias") and module.wi_0.bias is not None:
init.zeros_(module.wi_0.bias)
init.normal_(module.wi_1.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
if hasattr(module.wi_1, "bias") and module.wi_1.bias is not None:
init.zeros_(module.wi_1.bias)
init.normal_(module.wo.weight, mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
if hasattr(module.wo, "bias") and module.wo.bias is not None:
init.zeros_(module.wo.bias)
elif isinstance(module, UdopAttention):
d_model = self.config.d_model
key_value_proj_dim = self.config.d_kv
n_heads = self.config.num_heads
init.normal_(module.q.weight, mean=0.0, std=factor * ((d_model * key_value_proj_dim) ** -0.5))
init.normal_(module.k.weight, mean=0.0, std=factor * (d_model**-0.5))
init.normal_(module.v.weight, mean=0.0, std=factor * (d_model**-0.5))
init.normal_(module.o.weight, mean=0.0, std=factor * ((n_heads * key_value_proj_dim) ** -0.5))
if module.has_relative_attention_bias:
init.normal_(module.relative_attention_bias.weight, mean=0.0, std=factor * ((d_model) ** -0.5))
# Copied from transformers.models.prophetnet.modeling_prophetnet.ProphetNetPreTrainedModel._shift_right with ProphetNet->Udop
def _shift_right(self, input_ids):
decoder_start_token_id = self.config.decoder_start_token_id
pad_token_id = self.config.pad_token_id
assert decoder_start_token_id is not None, (
"self.model.config.decoder_start_token_id has to be defined. In Udop it is usually set to the"
" pad_token_id. See Udop docs for more information"
)
# shift inputs to the right
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
shifted_input_ids[..., 0] = decoder_start_token_id
assert pad_token_id is not None, "self.model.config.pad_token_id has to be defined."
# replace possible -100 values in labels by `pad_token_id`
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
assert torch.all(shifted_input_ids >= 0).item(), "Verify that `shifted_input_ids` has only positive values"
return shifted_input_ids
# Copied from transformers.models.t5.modeling_t5.T5LayerNorm with T5->Udop
| UdopPreTrainedModel |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/partitions/snap/snap.py | {
"start": 7993,
"end": 9263
} | class ____(PartitionsSnap):
partition_dimensions: Sequence[PartitionDimensionSnap]
@classmethod
def from_def(cls, partitions_def: "MultiPartitionsDefinition") -> Self: # pyright: ignore[reportIncompatibleMethodOverride]
from dagster._core.definitions.partitions.definition import MultiPartitionsDefinition
check.inst_param(partitions_def, "partitions_def", MultiPartitionsDefinition)
return cls(
partition_dimensions=[
PartitionDimensionSnap(
name=dimension.name,
partitions=PartitionsSnap.from_def(dimension.partitions_def),
)
for dimension in partitions_def.partitions_defs
]
)
def get_partitions_definition(self):
from dagster._core.definitions.partitions.definition import MultiPartitionsDefinition
return MultiPartitionsDefinition(
{
partition_dimension.name: (
partition_dimension.partitions.get_partitions_definition()
)
for partition_dimension in self.partition_dimensions
}
)
@whitelist_for_serdes(storage_name="ExternalDynamicPartitionsDefinitionData")
@record
| MultiPartitionsSnap |
python | tensorflow__tensorflow | tensorflow/python/distribute/mirrored_strategy_test.py | {
"start": 55072,
"end": 57780
} | class ____(
multi_worker_test_base.MultiWorkerTestBase,
strategy_test_lib.DistributionTestBase):
@classmethod
def setUpClass(cls):
"""Create a local cluster with 2 workers and 1 chief."""
cls._cluster_spec = multi_worker_test_base.create_in_process_cluster(
num_workers=2, num_ps=0, has_chief=True)
cls._default_target = "grpc://" + cls._cluster_spec["chief"][0]
def _make_cross_device_ops(self):
return cross_device_ops_lib.ReductionToOneDevice()
def testMinimizeLossGraph(self):
with context.graph_mode():
strategy = mirrored_strategy.MirroredStrategy(
cross_device_ops=self._make_cross_device_ops())
strategy.configure(cluster_spec=self._cluster_spec)
self._test_minimize_loss_graph(strategy, learning_rate=0.05)
def testMinimizeLossGraphMirroredStrategy(self):
with context.graph_mode():
strategy = mirrored_strategy.MirroredStrategy(
mirrored_strategy.all_local_devices(),
cross_device_ops=self._make_cross_device_ops())
strategy.configure(cluster_spec=self._cluster_spec)
self._test_minimize_loss_graph(strategy, learning_rate=0.05)
def testMinimizeLossGraphMirroredStrategyWithOneNode(self):
with context.graph_mode():
cluster_spec = {}
cluster_spec["chief"] = self._cluster_spec["chief"]
tf_config = {"cluster": cluster_spec}
with test.mock.patch.dict("os.environ",
{"TF_CONFIG": json.dumps(tf_config)}):
strategy = mirrored_strategy.MirroredStrategy()
if context.num_gpus() == 0:
self.assertIsInstance(strategy.extended._cross_device_ops,
cross_device_ops_lib.ReductionToOneDevice)
self.skipTest("b/130551176, run the following once fixed.")
self._test_minimize_loss_graph(strategy, learning_rate=0.05)
def testInitializeFromTFConfig(self):
with context.graph_mode():
tf_config = {"cluster": self._cluster_spec}
with test.mock.patch.dict("os.environ",
{"TF_CONFIG": json.dumps(tf_config)}):
strategy = mirrored_strategy.MirroredStrategy(
cross_device_ops=self._make_cross_device_ops())
self.assertEqual(
max(context.num_gpus(), 1) * 3, strategy.num_replicas_in_sync)
def testSummaryForReplicaZeroOnly(self):
with context.graph_mode():
strategy = mirrored_strategy.MirroredStrategy(
mirrored_strategy.all_local_devices(),
cross_device_ops=self._make_cross_device_ops())
strategy.configure(cluster_spec=self._cluster_spec)
self._test_summary_for_replica_zero_only(strategy)
| MultiWorkerMirroredStrategyTestWithChief |
python | Netflix__metaflow | metaflow/plugins/debug_logger.py | {
"start": 265,
"end": 879
} | class ____(object):
def __init__(self):
pass
def process_message(self, msg):
# type: (Message) -> None
if msg.msg_type == MessageTypes.SHUTDOWN:
print("Debug[shutdown]: got shutdown!", file=sys.stderr)
self._shutdown()
elif msg.msg_type == MessageTypes.BEST_EFFORT:
print("Debug[best_effort]: %s" % str(msg.payload), file=sys.stderr)
elif msg.msg_type == MessageTypes.MUST_SEND:
print("Debug[must_send]: %s" % str(msg.payload), file=sys.stderr)
def _shutdown(self):
sys.stderr.flush()
| DebugEventLoggerSidecar |
python | huggingface__transformers | src/transformers/models/dpr/modeling_dpr.py | {
"start": 17736,
"end": 21934
} | class ____(DPRPretrainedReader):
def __init__(self, config: DPRConfig):
super().__init__(config)
self.config = config
self.span_predictor = DPRSpanPredictor(config)
# Initialize weights and apply final processing
self.post_init()
@auto_docstring
def forward(
self,
input_ids: Optional[Tensor] = None,
attention_mask: Optional[Tensor] = None,
inputs_embeds: Optional[Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[DPRReaderOutput, tuple[Tensor, ...]]:
r"""
input_ids (`tuple[torch.LongTensor]` of shapes `(n_passages, sequence_length)`):
Indices of input sequence tokens in the vocabulary. It has to be a sequence triplet with 1) the question
and 2) the passages titles and 3) the passages texts To match pretraining, DPR `input_ids` sequence should
be formatted with [CLS] and [SEP] with the format:
`[CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>`
DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
rather than the left.
Indices can be obtained using [`DPRReaderTokenizer`]. See this class documentation for more details.
[What are input IDs?](../glossary#input-ids)
inputs_embeds (`torch.FloatTensor` of shape `(n_passages, sequence_length, hidden_size)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
model's internal embedding lookup matrix.
Examples:
```python
>>> from transformers import DPRReader, DPRReaderTokenizer
>>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
>>> model = DPRReader.from_pretrained("facebook/dpr-reader-single-nq-base")
>>> encoded_inputs = tokenizer(
... questions=["What is love ?"],
... titles=["Haddaway"],
... texts=["'What Is Love' is a song recorded by the artist Haddaway"],
... return_tensors="pt",
... )
>>> outputs = model(**encoded_inputs)
>>> start_logits = outputs.start_logits
>>> end_logits = outputs.end_logits
>>> relevance_logits = outputs.relevance_logits
```
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
elif input_ids is not None:
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
input_shape = input_ids.size()
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
else:
raise ValueError("You have to specify either input_ids or inputs_embeds")
device = input_ids.device if input_ids is not None else inputs_embeds.device
if attention_mask is None:
attention_mask = torch.ones(input_shape, device=device)
return self.span_predictor(
input_ids,
attention_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
__all__ = [
"DPRContextEncoder",
"DPRPretrainedContextEncoder",
"DPRPreTrainedModel",
"DPRPretrainedQuestionEncoder",
"DPRPretrainedReader",
"DPRQuestionEncoder",
"DPRReader",
]
| DPRReader |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_notifications.py | {
"start": 581,
"end": 2536
} | class ____(TestCase):
def test_notification_custom(self, send, render_to_string):
render_to_string.return_value = "Test"
class TestNotification(EmailNotification):
name = "foo"
subject = "This is {{ foo.id }}"
context_object_name = "foo"
user = fixture.get(User)
build = fixture.get(Build)
notify = TestNotification(context_object=build, user=user)
self.assertEqual(
notify.get_template_names("html"),
["builds/notifications/foo_email.html"],
)
self.assertEqual(
notify.get_template_names("txt"),
["builds/notifications/foo_email.txt"],
)
self.assertEqual(
notify.get_subject(),
"This is {}".format(build.id),
)
self.assertEqual(
notify.get_context_data(),
{
"foo": build,
"production_uri": "https://readthedocs.org",
# readthedocs_processor context
"ADMIN_URL": mock.ANY,
"DASHBOARD_ANALYTICS_CODE": mock.ANY,
"DO_NOT_TRACK_ENABLED": mock.ANY,
"GLOBAL_ANALYTICS_CODE": mock.ANY,
"PRODUCTION_DOMAIN": "readthedocs.org",
"PUBLIC_DOMAIN": mock.ANY,
"PUBLIC_API_URL": mock.ANY,
"SITE_ROOT": mock.ANY,
"SUPPORT_EMAIL": "support@readthedocs.org",
"TEMPLATE_ROOT": mock.ANY,
"USE_PROMOS": mock.ANY,
"USE_ORGANIZATIONS": mock.ANY,
"GITHUB_APP_NAME": mock.ANY,
},
)
notify.render("html")
render_to_string.assert_has_calls(
[
mock.call(
context=mock.ANY,
template_name=["builds/notifications/foo_email.html"],
),
]
)
| NotificationTests |
python | walkccc__LeetCode | solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041.py | {
"start": 0,
"end": 338
} | class ____:
def maxSelectedElements(self, nums: list[int]) -> int:
ans = 0
# {num: the length of the longest consecutive elements ending in num}
dp = {}
for num in sorted(nums):
dp[num + 1] = dp.get(num, 0) + 1
dp[num] = dp.get(num - 1, 0) + 1
ans = max(ans, dp[num], dp[num + 1])
return ans
| Solution |
python | scikit-learn__scikit-learn | sklearn/cross_decomposition/_pls.py | {
"start": 22499,
"end": 27018
} | class ____(_PLS):
"""Partial Least Squares transformer and regressor.
For a comparison between other cross decomposition algorithms, see
:ref:`sphx_glr_auto_examples_cross_decomposition_plot_compare_cross_decomposition.py`.
Read more in the :ref:`User Guide <cross_decomposition>`.
.. versionadded:: 0.8
Parameters
----------
n_components : int, default=2
Number of components to keep. Should be in `[1, min(n_samples,
n_features, n_targets)]`.
scale : bool, default=True
Whether to scale `X` and `y`.
algorithm : {'nipals', 'svd'}, default='nipals'
The algorithm used to estimate the first singular vectors of the
cross-covariance matrix. 'nipals' uses the power method while 'svd'
will compute the whole SVD.
max_iter : int, default=500
The maximum number of iterations of the power method when
`algorithm='nipals'`. Ignored otherwise.
tol : float, default=1e-06
The tolerance used as convergence criteria in the power method: the
algorithm stops whenever the squared norm of `u_i - u_{i-1}` is less
than `tol`, where `u` corresponds to the left singular vector.
copy : bool, default=True
Whether to copy `X` and `y` in fit before applying centering, and
potentially scaling. If False, these operations will be done inplace,
modifying both arrays.
Attributes
----------
x_weights_ : ndarray of shape (n_features, n_components)
The left singular vectors of the cross-covariance matrices of each
iteration.
y_weights_ : ndarray of shape (n_targets, n_components)
The right singular vectors of the cross-covariance matrices of each
iteration.
x_loadings_ : ndarray of shape (n_features, n_components)
The loadings of `X`.
y_loadings_ : ndarray of shape (n_targets, n_components)
The loadings of `y`.
x_rotations_ : ndarray of shape (n_features, n_components)
The projection matrix used to transform `X`.
y_rotations_ : ndarray of shape (n_targets, n_components)
The projection matrix used to transform `y`.
coef_ : ndarray of shape (n_targets, n_features)
The coefficients of the linear model such that `y` is approximated as
`y = X @ coef_.T + intercept_`.
intercept_ : ndarray of shape (n_targets,)
The intercepts of the linear model such that `y` is approximated as
`y = X @ coef_.T + intercept_`.
.. versionadded:: 1.1
n_iter_ : list of shape (n_components,)
Number of iterations of the power method, for each
component. Empty if `algorithm='svd'`.
n_features_in_ : int
Number of features seen during :term:`fit`.
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
.. versionadded:: 1.0
See Also
--------
CCA : Canonical Correlation Analysis.
PLSSVD : Partial Least Square SVD.
Examples
--------
>>> from sklearn.cross_decomposition import PLSCanonical
>>> X = [[0., 0., 1.], [1.,0.,0.], [2.,2.,2.], [2.,5.,4.]]
>>> y = [[0.1, -0.2], [0.9, 1.1], [6.2, 5.9], [11.9, 12.3]]
>>> plsca = PLSCanonical(n_components=2)
>>> plsca.fit(X, y)
PLSCanonical()
>>> X_c, y_c = plsca.transform(X, y)
"""
_parameter_constraints: dict = {**_PLS._parameter_constraints}
for param in ("deflation_mode", "mode"):
_parameter_constraints.pop(param)
# This implementation provides the same results that the "plspm" package
# provided in the R language (R-project), using the function plsca(X, y).
# Results are equal or collinear with the function
# ``pls(..., mode = "canonical")`` of the "mixOmics" package. The
# difference relies in the fact that mixOmics implementation does not
# exactly implement the Wold algorithm since it does not normalize
# y_weights to one.
def __init__(
self,
n_components=2,
*,
scale=True,
algorithm="nipals",
max_iter=500,
tol=1e-06,
copy=True,
):
super().__init__(
n_components=n_components,
scale=scale,
deflation_mode="canonical",
mode="A",
algorithm=algorithm,
max_iter=max_iter,
tol=tol,
copy=copy,
)
| PLSCanonical |
python | pytorch__pytorch | torch/distributed/tensor/examples/comm_mode_features_example.py | {
"start": 1082,
"end": 31125
} | class ____:
"""
Checks if the set of keys in ground truth dictionary and the set
produced in advanced_module_tracker are in the same order
"""
def __init__(self, world_size: int, rank: int) -> None:
self.world_size = world_size
self.rank = rank
self.device_type = get_device_type()
def _MLP_model_setup(
self, model_type: type, parallelize_plan: None | dict = None
) -> tuple[nn.Module, torch.Tensor]:
"""
Creates MLP or MLPStacked model for examples
"""
if parallelize_plan is None:
parallelize_plan = {
"net1": ColwiseParallel(),
"net2": RowwiseParallel(),
}
device_mesh = DeviceMesh(
self.device_type,
torch.arange(0, NUM_DEVICES),
)
inp_size = [8, 10]
inp = torch.rand(*inp_size, device=self.device_type)
model = model_type(self.device_type)
model = parallelize_module(model, device_mesh, parallelize_plan)
return model, inp
def _transformer_model_setup(
self, is_seq_parallel: bool = False
) -> tuple[nn.Module, torch.Tensor]:
"""
Creates transformer model for examples
"""
device_mesh = DeviceMesh(
self.device_type,
torch.arange(0, NUM_DEVICES),
)
model_args = ModelArgs()
model = Transformer(model_args).to(device=self.device_type)
model = Transformer.parallelize(model, device_mesh, is_seq_parallel)
inp_size = [8, 8]
inp = torch.randint(model_args.vocab_size, inp_size, device=self.device_type)
return model, inp
def example_MLP_distributed_sharding_display(self) -> None:
"""
Example of obtaining all module's FQN and parameters for a given distributed model and printing the sharding info
Expected output:
MLPModule.net1.weight: (Shard(dim=0),)
MLPModule.net1.bias: (Shard(dim=0),)
MLPModule.net2.weight: (Shard(dim=1),)
MLPModule.net2.bias: (Replicate(),)
"""
torch.manual_seed(0)
model, inp = self._MLP_model_setup(model_type=MLPModule)
comm_mode = CommDebugMode()
with comm_mode:
output_tp = model(inp)
output_tp.sum().backward()
print(comm_mode.get_sharding_info())
def example_MLPStacked_distributed_sharding_display(self) -> None:
"""
Example of obtaining all module's FQN and parameters for a given
distributed model with nested modules and printing the sharding info
Expected output:
MLPStacked.layers.0.net1.weight: (Shard(dim=0),)
MLPStacked.layers.0.net1.bias: (Shard(dim=0),)
MLPStacked.layers.0.net2.weight: (Shard(dim=1),)
MLPStacked.layers.0.net2.bias: (Replicate(),)
MLPStacked.layers.1.net1.weight: (Shard(dim=0),)
MLPStacked.layers.1.net1.bias: (Shard(dim=0),)
MLPStacked.layers.1.net2.weight: (Shard(dim=1),)
MLPStacked.layers.1.net2.bias: (Replicate(),)
"""
torch.manual_seed(0)
parallelize_plan = {
"MLPStacked.layers.0.net1": ColwiseParallel(),
"MLPStacked.layers.0.net2": RowwiseParallel(),
"MLPStacked.layers.1.net1": ColwiseParallel(),
"MLPStacked.layers.1.net2": RowwiseParallel(),
}
model, inp = self._MLP_model_setup(
model_type=MLPStacked, parallelize_plan=parallelize_plan
)
comm_mode = CommDebugMode()
with comm_mode:
output_tp = model(inp)
output_tp.sum().backward()
print(comm_mode.get_sharding_info())
def example_MLP_module_tracing(self) -> None:
"""
Example code to demonstrate CommModeDebug's module level tracing using a MLP model.
Prints a table of module level collective tracing information and logs table to comm_mode_log.txt
Expected Output:
Global
FORWARD PASS
*c10d_functional.all_reduce: 1
MLPModule
FORWARD PASS
*c10d_functional.all_reduce: 1
MLPModule.net1
MLPModule.relu
MLPModule.net2
FORWARD PASS
*c10d_functional.all_reduce: 1
"""
torch.manual_seed(0)
model, inp = self._MLP_model_setup(model_type=MLPModule)
comm_mode = CommDebugMode()
with comm_mode:
output_tp = model(inp)
output_tp.sum().backward()
# print the module level collective tracing information
print(comm_mode.generate_comm_debug_tracing_table(noise_level=0))
comm_mode.log_comm_debug_tracing_table_to_file(noise_level=0)
def example_transformer_module_tracing(self) -> None:
"""
Example code to demonstrate CommModeDebug's module level tracing using a distributed Transformer model.
Prints a table of module level collective tracing information and logs table to comm_mode_log.txt
Expected output:
Global
FORWARD PASS
*c10d_functional.all_reduce: 6
*c10d_functional.all_gather_into_tensor: 1
Transformer
FORWARD PASS
*c10d_functional.all_reduce: 6
*c10d_functional.all_gather_into_tensor: 1
Transformer.tok_embeddings
FORWARD PASS
*c10d_functional.all_reduce: 1
Transformer.pos_embeddings
FORWARD PASS
*c10d_functional.all_reduce: 1
Transformer.dropout
Transformer.layers.0
FORWARD PASS
*c10d_functional.all_reduce: 2
Transformer.layers.0.attention_norm
Transformer.layers.0.attention
FORWARD PASS
*c10d_functional.all_reduce: 1
Transformer.layers.0.attention.wq
Transformer.layers.0.attention.wk
Transformer.layers.0.attention.wv
Transformer.layers.0.attention.wo
FORWARD PASS
*c10d_functional.all_reduce: 1
Transformer.layers.0.attention.resid_dropout
Transformer.layers.0.ffn_norm
Transformer.layers.0.feed_forward
FORWARD PASS
*c10d_functional.all_reduce: 1
Transformer.layers.0.feed_forward.w1
Transformer.layers.0.feed_forward.gelu
Transformer.layers.0.feed_forward.w2
FORWARD PASS
*c10d_functional.all_reduce: 1
Transformer.layers.0.feed_forward.resid_dropout
Transformer.layers.1
FORWARD PASS
*c10d_functional.all_reduce: 2
Transformer.layers.1.attention_norm
Transformer.layers.1.attention
FORWARD PASS
*c10d_functional.all_reduce: 1
Transformer.layers.1.attention.wq
Transformer.layers.1.attention.wk
Transformer.layers.1.attention.wv
Transformer.layers.1.attention.wo
FORWARD PASS
*c10d_functional.all_reduce: 1
Transformer.layers.1.attention.resid_dropout
Transformer.layers.1.ffn_norm
Transformer.layers.1.feed_forward
FORWARD PASS
*c10d_functional.all_reduce: 1
Transformer.layers.1.feed_forward.w1
Transformer.layers.1.feed_forward.gelu
Transformer.layers.1.feed_forward.w2
FORWARD PASS
*c10d_functional.all_reduce: 1
Transformer.layers.1.feed_forward.resid_dropout
Transformer.norm
Transformer.output
FORWARD PASS
*c10d_functional.all_gather_into_tensor: 1
"""
torch.manual_seed(0)
model, inp = self._transformer_model_setup()
comm_mode = CommDebugMode()
with comm_mode:
model(inp)
# print the module level collective tracing information
print(comm_mode.generate_comm_debug_tracing_table(noise_level=0))
comm_mode.log_comm_debug_tracing_table_to_file(noise_level=0)
def example_MLP_operation_tracing(self) -> None:
"""
Example code to demonstrate CommModeDebug's module operation level tracing using a distributed MLP model.
Prints a table of module opoeration level collective tracing information and logs table to comm_mode_log.txt
Expected output:
Global
FORWARD PASS
*c10d_functional.all_reduce: 1
**aten.view.default
**aten.sum.default
**aten.ones_like.default
BACKWARD PASS
**aten.expand.default
MLPModule
*module type: class 'torch.testing._internal.distributed._tensor.common_dtensor.MLPModule'
FORWARD PASS
*c10d_functional.all_reduce: 1
**aten.view.default
**aten.view.default
**aten.view.default
MLPModule.net1
*module type: class 'torch.nn.modules.linear.Linear'
*Parameter List
*weight: (Shard(dim=0),)
*bias: (Shard(dim=0),)
FORWARD PASS
**aten.detach.default
shape: [torch.Size([16, 10])]
sharding: [(Shard(dim=0),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
**aten.detach.default
shape: [torch.Size([16, 10])]
sharding: [(Shard(dim=0),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
**aten.detach.default
shape: [torch.Size([16, 10])]
sharding: [(Shard(dim=0),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
**aten.detach.default
shape: [torch.Size([16, 10])]
sharding: [(Shard(dim=0),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
**aten.detach.default
shape: [torch.Size([16])]
sharding: [(Shard(dim=0),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
**aten.detach.default
shape: [torch.Size([16])]
sharding: [(Shard(dim=0),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
**aten.detach.default
shape: [torch.Size([16])]
sharding: [(Shard(dim=0),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
**aten.detach.default
shape: [torch.Size([16])]
sharding: [(Shard(dim=0),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
**aten.view.default
**aten.t.default
shape: [torch.Size([16, 10])]
sharding: [(Shard(dim=0),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.t.default
**aten.addmm.default
shape: [torch.Size([16]), torch.Size([8, 10]), torch.Size([10, 16])]
sharding: [(Shard(dim=0),), (Replicate(),), (Shard(dim=1),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.addmm.default
**aten.view.default
BACKWARD PASS
**aten.t.default
shape: [torch.Size([8, 16])]
sharding: [(Shard(dim=1),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.t.default
**aten.mm.default
shape: [torch.Size([16, 8]), torch.Size([8, 10])]
sharding: [(Shard(dim=0),), (Replicate(),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.mm.default
**aten.t.default
shape: [torch.Size([16, 10])]
sharding: [(Shard(dim=0),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.t.default
**aten.sum.dim_IntList
shape: [torch.Size([8, 16])]
sharding: [(Shard(dim=1),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.sum.dim_IntList
**aten.view.default
shape: [torch.Size([1, 16])]
sharding: [(Shard(dim=1),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.view.default
**aten.detach.default
shape: [torch.Size([16])]
sharding: [(Shard(dim=0),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
shape: [torch.Size([16])]
sharding: [(Shard(dim=0),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
**aten.t.default
shape: [torch.Size([10, 16])]
sharding: [(Shard(dim=1),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.t.default
**aten.detach.default
shape: [torch.Size([16, 10])]
sharding: [(Shard(dim=0),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
shape: [torch.Size([16, 10])]
sharding: [(Shard(dim=0),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
MLPModule.relu
*module type: class 'torch.nn.modules.activation.ReLU'
FORWARD PASS
**aten.view.default
**aten.relu.default
**aten.detach.default
BACKWARD PASS
**aten.detach.default
**aten.threshold_backward.default
MLPModule.net2
*module type: class 'torch.nn.modules.linear.Linear'
*Parameter List
*weight: (Shard(dim=1),)
*bias: (Replicate(),)
FORWARD PASS
*c10d_functional.all_reduce: 1
**aten.detach.default
shape: [torch.Size([10, 16])]
sharding: [(Shard(dim=1),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
**aten.detach.default
shape: [torch.Size([10, 16])]
sharding: [(Shard(dim=1),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
**aten.detach.default
shape: [torch.Size([10, 16])]
sharding: [(Shard(dim=1),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
**aten.detach.default
shape: [torch.Size([10, 16])]
sharding: [(Shard(dim=1),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
**aten.detach.default
shape: [torch.Size([10])]
sharding: [(Replicate(),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
**aten.detach.default
shape: [torch.Size([10])]
sharding: [(Replicate(),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
**aten.detach.default
shape: [torch.Size([10])]
sharding: [(Replicate(),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
**aten.detach.default
shape: [torch.Size([10])]
sharding: [(Replicate(),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
**aten.view.default
**aten.view.default
shape: [torch.Size([8, 16])]
sharding: [(Shard(dim=1),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.view.default
**aten.t.default
shape: [torch.Size([10, 16])]
sharding: [(Shard(dim=1),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.t.default
**aten.addmm.default
shape: [torch.Size([10]), torch.Size([8, 16]), torch.Size([16, 10])]
sharding: [(Replicate(),), (Shard(dim=1),), (Shard(dim=0),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.div.Tensor
**aten.addmm.default
**_c10d_functional.all_reduce.default
**aten.view.default
BACKWARD PASS
**aten.t.default
shape: [torch.Size([16, 10])]
sharding: [(Shard(dim=0),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.t.default
**aten.mm.default
shape: [torch.Size([8, 10]), torch.Size([10, 16])]
sharding: [(Replicate(),), (Shard(dim=1),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.mm.default
**aten.t.default
shape: [torch.Size([8, 10])]
sharding: [(Replicate(),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.t.default
**aten.mm.default
shape: [torch.Size([10, 8]), torch.Size([8, 16])]
sharding: [(Replicate(),), (Shard(dim=1),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.mm.default
**aten.t.default
shape: [torch.Size([10, 16])]
sharding: [(Shard(dim=1),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.t.default
**aten.sum.dim_IntList
shape: [torch.Size([8, 10])]
sharding: [(Replicate(),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.sum.dim_IntList
**aten.view.default
shape: [torch.Size([1, 10])]
sharding: [(Replicate(),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.view.default
**aten.detach.default
shape: [torch.Size([10])]
sharding: [(Replicate(),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
shape: [torch.Size([10])]
sharding: [(Replicate(),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
**aten.t.default
shape: [torch.Size([16, 10])]
sharding: [(Shard(dim=0),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.t.default
**aten.detach.default
shape: [torch.Size([10, 16])]
sharding: [(Shard(dim=1),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
shape: [torch.Size([10, 16])]
sharding: [(Shard(dim=1),)]
device mesh: DeviceMesh([0, 1, 2, 3])
**aten.detach.default
**aten.detach.default
"""
torch.manual_seed(0)
model, inp = self._MLP_model_setup(model_type=MLPModule)
comm_mode = CommDebugMode()
with comm_mode:
output_tp = model(inp)
output_tp.sum().backward()
# print the operation level collective tracing information
print(comm_mode.generate_comm_debug_tracing_table(noise_level=3))
comm_mode.log_comm_debug_tracing_table_to_file(noise_level=3)
def example_transformer_operation_tracing(
self, is_seq_parallel: bool = False
) -> None:
"""
Example code to demonstrate CommModeDebug's module operation level tracing using a distributed transformer model.
Prints a table of module opoeration level collective tracing information, excluding trivial operations and logs
table to transformer_operation_log.txt
"""
torch.manual_seed(0)
model, inp = self._transformer_model_setup()
comm_mode = CommDebugMode()
with comm_mode:
model(inp)
# print the operation level collective tracing information
print(comm_mode.generate_comm_debug_tracing_table(noise_level=2))
comm_mode.log_comm_debug_tracing_table_to_file(
noise_level=1, file_name="transformer_operation_log.txt"
)
def example_MLP_json_dump(self) -> None:
"""
Example code to demonstrate CommModeDebug's json dump using a MLP model. Sends the information to default
comm_mode_log.json file
"""
torch.manual_seed(0)
model, inp = self._MLP_model_setup(model_type=MLPModule)
comm_mode = CommDebugMode()
with comm_mode:
output_tp = model(inp)
output_tp.sum().backward()
comm_mode.generate_json_dump()
def example_transformer_json_dump(self, is_seq_parallel: bool = False) -> None:
"""
Example code to demonstrate CommModeDebug's json dump using a transformer model, excluding the trivial
operations. Sends the information to user-passed transformer_log.json file
"""
torch.manual_seed(0)
model, inp = self._transformer_model_setup()
comm_mode = CommDebugMode()
with comm_mode:
model(inp)
comm_mode.generate_json_dump(file_name="transformer_log.json", noise_level=1)
comm_mode.generate_json_dump(file_name="transformer_log_2.json", noise_level=2)
def example_activation_checkpointing(self) -> None:
"""
Example code showing that CommDebugMode is able to differentiate between backward passes
and activation checkpointing. Sends the information to default comm_mode_log.json file.
The output for the example output is shown below:
Global
FORWARD PASS
**aten.sum.default
**aten.ones_like.default
BACKWARD PASS
**aten.expand.default
Foo
*module type: class '__main__.CommDebugModeExample.example_activation_checkpointing.locals.Foo'
FORWARD PASS
**aten.relu.default
**aten.empty.memory_format
**aten.empty.memory_format
**aten.relu.default
BACKWARD PASS
**aten.threshold_backward.default
Foo.linears.0
*module type: class 'torch.nn.modules.linear.Linear'
FORWARD PASS
**aten.addmm.default
BACKWARD PASS
**aten.mm.default
**aten.sum.dim_IntList
Foo.linears.1
*module type: class 'torch.nn.modules.linear.Linear'
FORWARD PASS
**aten.addmm.default
ACTIVATION CHECKPOINTING
**aten.mm.default
**aten.mm.default
**aten.sum.dim_IntList
**aten.threshold_backward.default
"""
class Foo(torch.nn.Module):
def __init__(self, n_layers: int, dim: int, use_ac: bool = False):
super().__init__()
self.linears = torch.nn.ModuleList()
self.use_ac = use_ac
for _ in range(n_layers):
self.linears.append(torch.nn.Linear(dim, dim))
def forward(self, x: torch.Tensor) -> torch.Tensor:
for i, block in enumerate(self.linears):
if i >= 1 and self.use_ac:
x = checkpoint(
block, x, preserve_rng_state=True, use_reentrant=False
)
else:
x = block(x)
assert x is not None
x = torch.nn.functional.relu(x)
return x
bsz = 2
dim = 8
n_layers = 2
model = Foo(n_layers, dim, True)
x = torch.randn(bsz, dim)
comm_mode = CommDebugMode()
with comm_mode:
model(x).sum().backward()
print(comm_mode.generate_comm_debug_tracing_table(noise_level=2))
comm_mode.log_comm_debug_tracing_table_to_file(noise_level=2)
comm_mode.generate_json_dump(noise_level=2)
def run_example(world_size: int, rank: int, example_name: str) -> None:
# set manual seed
# initializing class with all of the functions
instantiated_example = CommDebugModeExample(world_size, rank)
# dict that stores example code function names
name_to_example_code: dict[str, Callable[[], None]] = {
"MLP_distributed_sharding_display": instantiated_example.example_MLP_distributed_sharding_display,
"MLPStacked_distributed_sharding_display": instantiated_example.example_MLPStacked_distributed_sharding_display,
"MLP_module_tracing": instantiated_example.example_MLP_module_tracing,
"transformer_module_tracing": instantiated_example.example_transformer_module_tracing,
"MLP_operation_tracing": instantiated_example.example_MLP_operation_tracing,
"transformer_operation_tracing": instantiated_example.example_transformer_operation_tracing,
"MLP_json_dump": instantiated_example.example_MLP_json_dump,
"transformer_json_dump": instantiated_example.example_transformer_json_dump,
"activation_checkpointing": instantiated_example.example_activation_checkpointing,
}
name_to_example_code[example_name]()
if __name__ == "__main__":
# this script is launched via torchrun which automatically manages ProcessGroup
rank = int(os.environ["RANK"])
world_size = int(os.environ["WORLD_SIZE"])
assert world_size == 4 # our example uses 4 worker ranks
parser = argparse.ArgumentParser(
description="comm_mode_feature examples",
formatter_class=argparse.RawTextHelpFormatter,
)
example_prompt = (
"choose one comm_mode_feature example from below:\n"
"\t1. MLP_distributed_sharding_display\n"
"\t2. MLPStacked_distributed_sharding_display\n"
"\t3. MLP_module_tracing\n"
"\t4. transformer_module_tracing\n"
"\t5. MLP_operation_tracing\n"
"\t6. transformer_operation_tracing\n"
"\t7. MLP_json_dump\n"
"\t8. transformer_json_dump\n"
"\t9. activation_checkpointing\n"
"e.g. you want to try the MLPModule sharding display example, please input 'MLP_distributed_sharding_display'\n"
)
parser.add_argument("-e", "--example", help=example_prompt, required=True)
example = parser.parse_args().example
run_example(world_size, rank, example)
| CommDebugModeExample |
python | celery__celery | t/unit/worker/test_control.py | {
"start": 908,
"end": 1501
} | class ____(consumer.Consumer):
def __init__(self, app):
self.app = app
self.buffer = FastQueue()
self.timer = Timer()
self.event_dispatcher = Mock()
self.controller = WorkController()
self.task_consumer = Mock()
self.prefetch_multiplier = 1
self.initial_prefetch_count = 1
from celery.concurrency.base import BasePool
self.pool = BasePool(10)
self.task_buckets = defaultdict(lambda: None)
self.hub = None
def call_soon(self, p, *args, **kwargs):
return p(*args, **kwargs)
| Consumer |
python | tensorflow__tensorflow | tensorflow/python/framework/indexed_slices.py | {
"start": 2069,
"end": 6944
} | class ____(
internal.IndexedSlices,
internal.NativeObject,
composite_tensor.CompositeTensor):
"""A sparse representation of a set of tensor slices at given indices.
This class is a simple wrapper for a pair of `Tensor` objects:
* `values`: A `Tensor` of any dtype with shape `[D0, D1, ..., Dn]`.
* `indices`: A 1-D integer `Tensor` with shape `[D0]`.
An `IndexedSlices` is typically used to represent a subset of a larger
tensor `dense` of shape `[LARGE0, D1, .. , DN]` where `LARGE0 >> D0`.
The values in `indices` are the indices in the first dimension of
the slices that have been extracted from the larger tensor.
The dense tensor `dense` represented by an `IndexedSlices` `slices` has
```python
dense[slices.indices[i], :, :, :, ...] = slices.values[i, :, :, :, ...]
```
The `IndexedSlices` class is used principally in the definition of
gradients for operations that have sparse gradients
(e.g. `tf.gather`).
>>> v = tf.Variable([[0.,1, 2], [2, 3, 4], [4, 5, 6], [6, 7, 8]])
>>> with tf.GradientTape() as tape:
... r = tf.gather(v, [1,3])
>>> index_slices = tape.gradient(r,v)
>>> index_slices
<...IndexedSlices object ...>
>>> index_slices.indices.numpy()
array([1, 3], dtype=int32)
>>> index_slices.values.numpy()
array([[1., 1., 1.],
[1., 1., 1.]], dtype=float32)
Contrast this representation with
`tf.sparse.SparseTensor`,
which uses multi-dimensional indices and scalar values.
"""
def __init__(self, values, indices, dense_shape=None):
"""Creates an `IndexedSlices`."""
self._values = values
self._indices = indices
self._dense_shape = dense_shape
@property
def values(self):
"""A `Tensor` containing the values of the slices."""
return self._values
@property
def indices(self):
"""A 1-D `Tensor` containing the indices of the slices."""
return self._indices
@property
def dense_shape(self):
"""A 1-D `Tensor` containing the shape of the corresponding dense tensor."""
return self._dense_shape
@property
def shape(self):
"""Gets the `tf.TensorShape` representing the shape of the dense tensor.
Returns:
A `tf.TensorShape` object.
"""
if self._dense_shape is None:
return tensor_shape.TensorShape(None)
return tensor_util.constant_value_as_shape(self._dense_shape)
@property
def name(self):
"""The name of this `IndexedSlices`."""
return self.values.name
@property
def device(self):
"""The name of the device on which `values` will be produced, or `None`."""
return self.values.device
@property
def op(self) -> ops.Operation:
"""The `Operation` that produces `values` as an output."""
return self.values.op
@property
def dtype(self):
"""The `DType` of elements in this tensor."""
return self.values.dtype
@property
def graph(self) -> ops.Graph:
"""The `Graph` that contains the values, indices, and shape tensors."""
return self._values.graph
def __str__(self):
return "IndexedSlices(indices=%s, values=%s%s)" % (
self._indices, self._values,
(", dense_shape=%s" %
(self._dense_shape,)) if self._dense_shape is not None else "")
def __neg__(self):
return IndexedSlices(-self.values, self.indices, self.dense_shape)
__composite_gradient__ = IndexedSlicesCompositeTensorGradient()
@property
def _type_spec(self):
indices_shape = self._indices.shape.merge_with(self._values.shape[:1])
dense_shape = tensor_shape.TensorShape([None]).concatenate(
self._values.shape[1:])
if self._dense_shape is not None:
dense_shape_dtype = self._dense_shape.dtype
dense_shape = dense_shape.merge_with(
tensor_util.constant_value_as_shape(self._dense_shape))
else:
dense_shape_dtype = None
return IndexedSlicesSpec(dense_shape, self.dtype, self._indices.dtype,
dense_shape_dtype, indices_shape)
def _shape_invariant_to_type_spec(self, shape):
# From tf.while_loop docs: "If a loop variable is an IndexedSlices, the
# shape invariant must be a shape invariant of the values tensor of the
# IndexedSlices. It means the shapes of the three tensors of the
# IndexedSlices are (shape, [shape[0]], [shape.ndims])."
indices_shape = shape[:1]
dense_shape = tensor_shape.TensorShape([None]).concatenate(shape[1:])
if self._dense_shape is None:
dense_shape_dtype = None
else:
dense_shape_dtype = self._dense_shape.dtype
return IndexedSlicesSpec(dense_shape, self.dtype, self._indices.dtype,
dense_shape_dtype, indices_shape)
def consumers(self):
return self._consumers()
IndexedSlicesValue = collections.namedtuple(
"IndexedSlicesValue", ["values", "indices", "dense_shape"])
@tf_export("IndexedSlicesSpec")
| IndexedSlices |
python | cython__cython | tests/run/pep3135_class_cell.py | {
"start": 3182,
"end": 3453
} | class ____:
"""
>>> obj = I()
>>> obj.method()()().__name__
'J'
"""
def method(self):
def inner():
class J:
def inner(self):
return __class__
return J().inner
return inner
| I |
python | redis__redis-py | redis/commands/search/aggregation.py | {
"start": 10829,
"end": 11185
} | class ____:
def __init__(self, cid: int) -> None:
self.cid = cid
self.max_idle = 0
self.count = 0
def build_args(self):
args = [str(self.cid)]
if self.max_idle:
args += ["MAXIDLE", str(self.max_idle)]
if self.count:
args += ["COUNT", str(self.count)]
return args
| Cursor |
python | jazzband__django-redis | tests/conftest.py | {
"start": 254,
"end": 1750
} | class ____(LoadScopeScheduling):
"""Split by [] value. This is very hackish and might blow up any time!"""
def _split_scope(self, nodeid):
if "[sqlite" in nodeid:
return nodeid.rsplit("[")[-1].replace("]", "")
return None
def pytest_xdist_make_scheduler(log, config):
return FixtureScheduling(config, log)
def pytest_configure(config):
sys.path.insert(0, str(Path(__file__).absolute().parent))
@pytest.fixture()
def settings():
"""A Django settings object which restores changes after the testrun"""
wrapper = SettingsWrapper()
yield wrapper
wrapper.finalize()
@pytest.fixture()
def cache(cache_settings: str) -> Iterable[BaseCache]:
from django import setup
environ["DJANGO_SETTINGS_MODULE"] = f"settings.{cache_settings}"
setup()
from django.core.cache import cache as default_cache
yield default_cache
default_cache.clear()
def pytest_generate_tests(metafunc):
if "cache" in metafunc.fixturenames or "session" in metafunc.fixturenames:
# Mark
settings = [
"sqlite",
"sqlite_gzip",
"sqlite_herd",
"sqlite_json",
"sqlite_lz4",
"sqlite_msgpack",
"sqlite_sentinel",
"sqlite_sentinel_opts",
"sqlite_sharding",
"sqlite_usock",
"sqlite_zlib",
"sqlite_zstd",
]
metafunc.parametrize("cache_settings", settings)
| FixtureScheduling |
python | getsentry__sentry | src/sentry/auth/services/auth/service.py | {
"start": 503,
"end": 3227
} | class ____(RpcService):
key = "auth"
local_mode = SiloMode.CONTROL
@classmethod
def get_local_implementation(cls) -> RpcService:
from sentry.auth.services.auth.impl import DatabaseBackedAuthService
return DatabaseBackedAuthService()
@rpc_method
@abc.abstractmethod
def get_org_auth_config(
self, *, organization_ids: list[int]
) -> list[RpcOrganizationAuthConfig]:
pass
# TODO: Denormalize this scim enabled flag onto organizations?
# This is potentially a large list
@rpc_method
@abc.abstractmethod
def get_org_ids_with_scim(self) -> list[int]:
"""
This method returns a list of org ids that have scim enabled
:return:
"""
@rpc_method
@abc.abstractmethod
def get_auth_provider(self, *, organization_id: int) -> RpcAuthProvider | None:
"""
This method returns the auth provider for an org, if one exists
"""
@rpc_method
@abc.abstractmethod
def disable_provider(self, *, provider_id: int) -> None:
pass
@rpc_method
@abc.abstractmethod
def change_scim(
self, *, user_id: int, provider_id: int, enabled: bool, allow_unlinked: bool
) -> None:
pass
@rpc_method
@abc.abstractmethod
def update_provider_config(
self, organization_id: int, auth_provider_id: int, config: Mapping[str, Any]
) -> None:
pass
@rpc_method
@abc.abstractmethod
def update_provider(self, organization_id: int, auth_provider_id: int, provider: str) -> None:
pass
@rpc_method
@abc.abstractmethod
def get_organization_api_keys(self, *, organization_id: int) -> list[RpcApiKey]:
pass
@rpc_method
@abc.abstractmethod
def get_organization_key(self, *, key: str) -> RpcApiKey | None:
pass
@rpc_method
@abc.abstractmethod
def enable_partner_sso(
self,
*,
organization_id: int,
provider_key: str,
provider_config: Mapping[str, Any],
user_id: int | None = None,
sender: str | None = None,
equivalent_providers: list[str] | None = None,
) -> None:
pass
@rpc_method
@abc.abstractmethod
def create_auth_identity(
self,
*,
provider: str,
config: Mapping[str, Any],
user_id: int,
ident: str,
equivalent_providers: list[str] | None = None,
) -> None:
pass
@rpc_method
@abc.abstractmethod
def get_auth_provider_with_config(
self, *, provider: str, config: Mapping[str, Any]
) -> RpcAuthProvider | None:
pass
auth_service = AuthService.create_delegation()
| AuthService |
python | pydata__xarray | asv_bench/benchmarks/dataset_io.py | {
"start": 18628,
"end": 19246
} | class ____(IONestedDataTree):
def setup(self):
# TODO: Lazily skipped in CI as it is very demanding and slow.
# Improve times and remove errors.
_skip_slow()
requires_dask()
self.make_datatree()
self.format = "NETCDF4"
self.filepath = "datatree.nc4.nc"
dtree = self.dtree
dtree.to_netcdf(filepath=self.filepath)
def time_load_datatree_netcdf4(self):
xr.open_datatree(self.filepath, engine="netcdf4").load()
def time_open_datatree_netcdf4(self):
xr.open_datatree(self.filepath, engine="netcdf4")
| IOReadDataTreeNetCDF4 |
python | charliermarsh__ruff | crates/ruff_python_parser/resources/valid/statement/class.py | {
"start": 22,
"end": 83
} | class ____():
def __init__(self):
pass
| Test |
python | getsentry__sentry | tests/sentry/snuba/test_metrics_performance.py | {
"start": 540,
"end": 5067
} | class ____(MetricsEnhancedPerformanceTestCase):
def setUp(self) -> None:
super().setUp()
# We want to always consider 7 days for simplicity.
self.start = datetime.datetime.now(tz=timezone.utc).replace(
hour=10, minute=0, second=0, microsecond=0
) - datetime.timedelta(days=1)
self.end = datetime.datetime.now(tz=timezone.utc).replace(
hour=10, minute=0, second=0, microsecond=0
)
self.default_interval = 3600
self.projects = [self.project]
self.snuba_params = SnubaParams(
organization=self.organization,
projects=self.projects,
start=self.start,
end=self.end,
)
indexer.record(
use_case_id=UseCaseID.TRANSACTIONS, org_id=self.organization.id, string="transaction"
)
for week in range(2):
for hour in range(24):
for j in range(2):
self.store_transaction_metric(
metric="transaction.duration",
tags={"transaction": "foo_transaction"},
# This formula gives us a different entry per hour, per insertion and per week.
value=(hour + j) * (week + 1),
timestamp=self.end
- datetime.timedelta(hours=hour)
- datetime.timedelta(weeks=week),
)
def test_timeseries_query(self) -> None:
results = timeseries_query(
selected_columns=["avg(transaction.duration)"],
query="",
snuba_params=self.snuba_params,
rollup=self.default_interval,
referrer="test_query",
)
expected = [
None,
23.5,
22.5,
21.5,
20.5,
19.5,
18.5,
17.5,
16.5,
15.5,
14.5,
13.5,
12.5,
11.5,
10.5,
9.5,
8.5,
7.5,
6.5,
5.5,
4.5,
3.5,
2.5,
1.5,
None,
]
for index, data in enumerate(results.data["data"]):
assert data.get("avg_transaction_duration") == expected[index]
def test_timeseries_query_with_comparison(self) -> None:
results = timeseries_query(
selected_columns=["avg(transaction.duration)"],
query="",
snuba_params=self.snuba_params,
rollup=self.default_interval,
comparison_delta=datetime.timedelta(weeks=1),
referrer="test_query",
)
expected = [
None,
23.5,
22.5,
21.5,
20.5,
19.5,
18.5,
17.5,
16.5,
15.5,
14.5,
13.5,
12.5,
11.5,
10.5,
9.5,
8.5,
7.5,
6.5,
5.5,
4.5,
3.5,
2.5,
1.5,
None,
]
expected_comparison = [
None,
47.0,
45.0,
43.0,
41.0,
39.0,
37.0,
35.0,
33.0,
31.0,
29.0,
27.0,
25.0,
23.0,
21.0,
19.0,
17.0,
15.0,
13.0,
11.0,
9.0,
7.0,
5.0,
3.0,
None,
]
for index, data in enumerate(results.data["data"]):
assert data.get("avg_transaction_duration") == expected[index]
assert data.get("comparisonCount") == expected_comparison[index]
def test_timeseries_query_with_comparison_and_multiple_aggregates(self) -> None:
with pytest.raises(
IncompatibleMetricsQuery,
match="The comparison query for metrics supports only one aggregate.",
):
timeseries_query(
selected_columns=["avg(transaction.duration)", "sum(transaction.duration)"],
query="",
snuba_params=self.snuba_params,
rollup=self.default_interval,
comparison_delta=datetime.timedelta(weeks=1),
referrer="test_query",
)
| TimeseriesQueryTest |
python | h5py__h5py | h5py/tests/test_dataset.py | {
"start": 10935,
"end": 12576
} | class ____:
"""
Feature: Write Numpy array directly into Dataset
"""
@pytest.mark.parametrize(
'source_shape,dest_shape,source_sel,dest_sel',
[
((100,), (100,), np.s_[0:10], np.s_[50:60]),
((70,), (100,), np.s_[50:60], np.s_[90:]),
((30, 10), (20, 20), np.s_[:20, :], np.s_[:, :10]),
((5, 7, 9), (6,), np.s_[2, :6, 3], np.s_[:]),
])
def test_write_direct(self, writable_file, source_shape, dest_shape, source_sel, dest_sel):
dset = writable_file.create_dataset(make_name(), dest_shape, dtype='int32', fillvalue=-1)
arr = np.arange(product(source_shape)).reshape(source_shape)
expected = np.full(dest_shape, -1, dtype='int32')
expected[dest_sel] = arr[source_sel]
dset.write_direct(arr, source_sel, dest_sel)
np.testing.assert_array_equal(dset[:], expected)
def test_empty(self, writable_file):
empty_dset = writable_file.create_dataset(make_name(), dtype='int64')
with pytest.raises(TypeError):
empty_dset.write_direct(np.ones((100,)), np.s_[0:10], np.s_[50:60])
def test_wrong_shape(self, writable_file):
dset = writable_file.create_dataset(make_name(), (100,), dtype='int64')
arr = np.ones((200,))
with pytest.raises(TypeError):
dset.write_direct(arr)
def test_not_c_contiguous(self, writable_file):
dset = writable_file.create_dataset(make_name(), (10, 10), dtype='int64')
arr = np.ones((10, 10), order='F')
with pytest.raises(TypeError):
dset.write_direct(arr)
| TestWriteDirectly |
python | PrefectHQ__prefect | tests/test_task_worker.py | {
"start": 17066,
"end": 18884
} | class ____:
async def test_task_run_via_task_worker_runs_on_completion_hook(
self, async_foo_task, prefect_client, events_pipeline, capsys
):
async_foo_task_with_on_completion_hook = async_foo_task.with_options(
on_completion=[
lambda task, task_run, state: print("Running on_completion hook")
]
)
task_worker = TaskWorker(async_foo_task_with_on_completion_hook)
task_run_future = async_foo_task_with_on_completion_hook.apply_async((42,))
task_run = await prefect_client.read_task_run(task_run_future.task_run_id)
await task_worker.execute_task_run(task_run)
await events_pipeline.process_events()
updated_task_run = await prefect_client.read_task_run(
task_run_future.task_run_id
)
assert updated_task_run.state.is_completed()
assert "Running on_completion hook" in capsys.readouterr().out
async def test_task_run_via_task_worker_runs_on_failure_hook(
self, prefect_client, events_pipeline, capsys
):
@task(
on_failure=[lambda task, task_run, state: print("Running on_failure hook")]
)
def task_that_fails():
raise ValueError("I failed")
task_worker = TaskWorker(task_that_fails)
task_run_future = task_that_fails.apply_async()
task_run = await prefect_client.read_task_run(task_run_future.task_run_id)
await task_worker.execute_task_run(task_run)
await events_pipeline.process_events()
updated_task_run = await prefect_client.read_task_run(
task_run_future.task_run_id
)
assert updated_task_run.state.is_failed()
assert "Running on_failure hook" in capsys.readouterr().out
| TestTaskWorkerTaskStateHooks |
python | huggingface__transformers | src/transformers/models/altclip/modeling_altclip.py | {
"start": 29098,
"end": 32945
} | class ____(nn.Module):
def __init__(self, config: AltCLIPVisionConfig):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.image_size = config.image_size
self.patch_size = config.patch_size
self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
self.patch_embedding = nn.Conv2d(
in_channels=config.num_channels,
out_channels=self.embed_dim,
kernel_size=self.patch_size,
stride=self.patch_size,
bias=False,
)
self.num_patches = (self.image_size // self.patch_size) ** 2
self.num_positions = self.num_patches + 1
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
"""
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
images. This method is also adapted to support torch.jit tracing.
Adapted from:
- https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
- https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
"""
num_patches = embeddings.shape[1] - 1
position_embedding = self.position_embedding.weight.unsqueeze(0)
num_positions = position_embedding.shape[1] - 1
# always interpolate when tracing to ensure the exported model works for dynamic input shapes
if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
return self.position_embedding(self.position_ids)
class_pos_embed = position_embedding[:, :1]
patch_pos_embed = position_embedding[:, 1:]
dim = embeddings.shape[-1]
new_height = height // self.patch_size
new_width = width // self.patch_size
sqrt_num_positions = torch_int(num_positions**0.5)
patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
patch_pos_embed = nn.functional.interpolate(
patch_pos_embed,
size=(new_height, new_width),
mode="bicubic",
align_corners=False,
)
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding=False) -> torch.Tensor:
batch_size, _, height, width = pixel_values.shape
if not interpolate_pos_encoding and (height != self.image_size or width != self.image_size):
raise ValueError(
f"Input image size ({height}*{width}) doesn't match model ({self.image_size}*{self.image_size})."
)
target_dtype = self.patch_embedding.weight.dtype
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
class_embeds = self.class_embedding.expand(batch_size, 1, -1)
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
if interpolate_pos_encoding:
embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
else:
embeddings = embeddings + self.position_embedding(self.position_ids)
return embeddings
@auto_docstring
| AltCLIPVisionEmbeddings |
python | scipy__scipy | scipy/signal/tests/test_bsplines.py | {
"start": 12820,
"end": 19116
} | class ____:
def test_sepfir2d_invalid_filter(self, xp):
filt = xp.asarray([1.0, 2.0, 4.0, 2.0, 1.0])
image = np.random.rand(7, 9)
image = xp.asarray(image)
# No error for odd lengths
signal.sepfir2d(image, filt, filt[2:])
# Row or column filter must be odd
with pytest.raises(ValueError, match="odd length"):
signal.sepfir2d(image, filt, filt[1:])
with pytest.raises(ValueError, match="odd length"):
signal.sepfir2d(image, filt[1:], filt)
# Filters must be 1-dimensional
with pytest.raises(ValueError, match="object too deep"):
signal.sepfir2d(image, xp.reshape(filt, (1, -1)), filt)
with pytest.raises(ValueError, match="object too deep"):
signal.sepfir2d(image, filt, xp.reshape(filt, (1, -1)))
def test_sepfir2d_invalid_image(self, xp):
filt = xp.asarray([1.0, 2.0, 4.0, 2.0, 1.0])
image = np.random.rand(8, 8)
image = xp.asarray(image)
# Image must be 2 dimensional
with pytest.raises(ValueError, match="object too deep"):
signal.sepfir2d(xp.reshape(image, (4, 4, 4)), filt, filt)
with pytest.raises(ValueError, match="object of too small depth"):
signal.sepfir2d(image[0, :], filt, filt)
@pytest.mark.parametrize('dtyp',
[np.uint8, int, np.float32, float, np.complex64, complex]
)
def test_simple(self, dtyp, xp):
# test values on a paper-and-pencil example
a = np.array([[1, 2, 3, 3, 2, 1],
[1, 2, 3, 3, 2, 1],
[1, 2, 3, 3, 2, 1],
[1, 2, 3, 3, 2, 1]], dtype=dtyp)
h1 = [0.5, 1, 0.5]
h2 = [1]
result = signal.sepfir2d(a, h1, h2)
dt = sepfir_dtype_map[dtyp]
expected = np.asarray([[2.5, 4. , 5.5, 5.5, 4. , 2.5],
[2.5, 4. , 5.5, 5.5, 4. , 2.5],
[2.5, 4. , 5.5, 5.5, 4. , 2.5],
[2.5, 4. , 5.5, 5.5, 4. , 2.5]], dtype=dt)
xp_assert_close(result, expected, atol=1e-16)
result = signal.sepfir2d(a, h2, h1)
expected = np.asarray([[2., 4., 6., 6., 4., 2.],
[2., 4., 6., 6., 4., 2.],
[2., 4., 6., 6., 4., 2.],
[2., 4., 6., 6., 4., 2.]], dtype=dt)
xp_assert_close(result, expected, atol=1e-16)
@skip_xp_backends(np_only=True, reason="TODO: convert this test")
@pytest.mark.parametrize('dtyp',
[np.uint8, int, np.float32, float, np.complex64, complex]
)
def test_strided(self, dtyp, xp):
a = np.array([[1, 2, 3, 3, 2, 1, 1, 2, 3],
[1, 2, 3, 3, 2, 1, 1, 2, 3],
[1, 2, 3, 3, 2, 1, 1, 2, 3],
[1, 2, 3, 3, 2, 1, 1, 2, 3]])
h1, h2 = [0.5, 1, 0.5], [1]
result_strided = signal.sepfir2d(a[:, ::2], h1, h2)
result_contig = signal.sepfir2d(a[:, ::2].copy(), h1, h2)
xp_assert_close(result_strided, result_contig, atol=1e-15)
assert result_strided.dtype == result_contig.dtype
@skip_xp_backends(np_only=True, reason="TODO: convert this test")
@pytest.mark.xfail(reason="XXX: filt.size > image.shape: flaky")
def test_sepfir2d_strided_2(self, xp):
# XXX: this test is flaky: fails on some reruns, with
# result[0, 1] and result[1, 1] being ~1e+224.
filt = np.array([1.0, 2.0, 4.0, 2.0, 1.0, 3.0, 2.0])
image = np.random.rand(4, 4)
expected = np.asarray([[36.018162, 30.239061, 38.71187 , 43.878183],
[38.180999, 35.824583, 43.525247, 43.874945],
[43.269533, 40.834018, 46.757772, 44.276423],
[49.120928, 39.681844, 43.596067, 45.085854]])
xp_assert_close(signal.sepfir2d(image, filt, filt[::3]), expected)
@skip_xp_backends(np_only=True, reason="TODO: convert this test")
@pytest.mark.xfail(reason="XXX: flaky. pointers OOB on some platforms")
@pytest.mark.fail_asan
@pytest.mark.parametrize('dtyp',
[np.uint8, int, np.float32, float, np.complex64, complex]
)
def test_sepfir2d_strided_3(self, dtyp, xp):
# NB: 'image' and 'filt' dtypes match here. Otherwise we can run into
# unsafe casting errors for many combinations. Historically, dtype handling
# in `sepfir2d` is a tad baroque; fixing it is an enhancement.
filt = np.array([1, 2, 4, 2, 1, 3, 2], dtype=dtyp)
image = np.asarray([[0, 3, 0, 1, 2],
[2, 2, 3, 3, 3],
[0, 1, 3, 0, 3],
[2, 3, 0, 1, 3],
[3, 3, 2, 1, 2]], dtype=dtyp)
expected = [[123., 101., 91., 136., 127.],
[133., 125., 126., 152., 160.],
[136., 137., 150., 162., 177.],
[133., 124., 132., 148., 147.],
[173., 158., 152., 164., 141.]]
expected = np.asarray(expected)
result = signal.sepfir2d(image, filt, filt[::3])
xp_assert_close(result, expected, atol=1e-15)
assert result.dtype == sepfir_dtype_map[dtyp]
expected = [[22., 35., 41., 31., 47.],
[27., 39., 48., 47., 55.],
[33., 42., 49., 53., 59.],
[39., 44., 41., 36., 48.],
[67., 62., 47., 34., 46.]]
expected = np.asarray(expected)
result = signal.sepfir2d(image, filt[::3], filt[::3])
xp_assert_close(result, expected, atol=1e-15)
assert result.dtype == sepfir_dtype_map[dtyp]
@make_xp_test_case(signal.cspline2d)
def test_cspline2d(xp):
rng = np.random.RandomState(181819142)
image = rng.rand(71, 73)
image = xp.asarray(image, dtype=xp_default_dtype(xp))
result = signal.cspline2d(image, 8.0)
assert array_namespace(result) == xp
@make_xp_test_case(signal.qspline2d)
def test_qspline2d(xp):
rng = np.random.RandomState(181819143)
image = rng.rand(71, 73)
image = xp.asarray(image, dtype=xp_default_dtype(xp))
result = signal.qspline2d(image)
assert array_namespace(result) == xp
| TestSepfir2d |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 3940,
"end": 4052
} | class ____(PydanticTypeError):
code = 'none.allowed'
msg_template = 'value is not none'
| NoneIsAllowedError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/initsubclass1.py | {
"start": 1459,
"end": 1574
} | class ____(ClassJ):
def __init__(self):
reveal_type(self.custom_attribute, expected_text="int")
| ClassJChild |
python | openai__openai-python | src/openai/lib/streaming/responses/_events.py | {
"start": 2713,
"end": 2847
} | class ____(RawResponseTextDoneEvent, GenericModel, Generic[TextFormatT]):
parsed: Optional[TextFormatT] = None
| ResponseTextDoneEvent |
python | tiangolo__fastapi | docs_src/security/tutorial004.py | {
"start": 897,
"end": 965
} | class ____(BaseModel):
username: Union[str, None] = None
| TokenData |
python | matplotlib__matplotlib | lib/mpl_toolkits/axisartist/angle_helper.py | {
"start": 4103,
"end": 4348
} | class ____:
def __init__(self, nbins, include_last=True):
self.nbins = nbins
self._include_last = include_last
def set_params(self, nbins=None):
if nbins is not None:
self.nbins = int(nbins)
| LocatorBase |
python | mlflow__mlflow | mlflow/utils/timeout.py | {
"start": 197,
"end": 1214
} | class ____(Exception):
pass
@contextmanager
def run_with_timeout(seconds):
"""
Context manager to runs a block of code with a timeout. If the block of code takes longer
than `seconds` to execute, a `TimeoutError` is raised.
NB: This function uses Unix signals to implement the timeout, so it is not thread-safe.
Also it does not work on non-Unix platforms such as Windows.
E.g.
```
with run_with_timeout(5):
model.predict(data)
```
"""
if is_windows():
raise MlflowException(
"Timeouts are not implemented yet for non-Unix platforms",
error_code=NOT_IMPLEMENTED,
)
def signal_handler(signum, frame):
raise MlflowTimeoutError(f"Operation timed out after {seconds} seconds")
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(seconds)
try:
yield
finally:
signal.alarm(0) # Disable the alarm after the operation completes or times out
| MlflowTimeoutError |
python | lepture__authlib | authlib/jose/errors.py | {
"start": 1654,
"end": 1780
} | class ____(JoseError):
error = "key_mismatch_error"
description = "Key does not match to any recipient"
| KeyMismatchError |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/io_management/input_managers.py | {
"start": 4264,
"end": 4573
} | class ____(TableIOManager):
def load_input(self, context: dg.InputContext):
return read_dataframe_from_table(name="table_1")
@dg.job(resource_defs={"load_input_manager": Table1IOManager()})
def io_load_table_job():
my_op()
# end_load_unconnected_io
# start_load_input_subset
| Table1IOManager |
python | jupyterlab__jupyterlab | jupyterlab/labextensions.py | {
"start": 17020,
"end": 18331
} | class ____(BaseExtensionApp):
description = "Check labextension(s) by name"
flags = check_flags
should_check_installed_only = Bool(
False,
config=True,
help="Whether it should check only if the extensions is installed",
)
def run_task(self):
app_options = AppOptions(
app_dir=self.app_dir,
logger=self.log,
core_config=self.core_config,
labextensions_path=self.labextensions_path,
)
all_enabled = all(
check_extension(
arg, installed=self.should_check_installed_only, app_options=app_options
)
for arg in self.extra_args
)
if not all_enabled:
self.exit(1)
_EXAMPLES = """
jupyter labextension list # list all configured labextensions
jupyter labextension install <extension name> # install a labextension
jupyter labextension uninstall <extension name> # uninstall a labextension
jupyter labextension develop # (developer) develop a prebuilt labextension
jupyter labextension build # (developer) build a prebuilt labextension
jupyter labextension watch # (developer) watch a prebuilt labextension
"""
| CheckLabExtensionsApp |
python | redis__redis-py | redis/commands/core.py | {
"start": 131723,
"end": 157146
} | class ____(CommandsProtocol):
"""
Redis commands for Stream data type.
see: https://redis.io/topics/streams-intro
"""
def xack(self, name: KeyT, groupname: GroupT, *ids: StreamIdT) -> ResponseT:
"""
Acknowledges the successful processing of one or more messages.
Args:
name: name of the stream.
groupname: name of the consumer group.
*ids: message ids to acknowledge.
For more information, see https://redis.io/commands/xack
"""
return self.execute_command("XACK", name, groupname, *ids)
def xackdel(
self,
name: KeyT,
groupname: GroupT,
*ids: StreamIdT,
ref_policy: Literal["KEEPREF", "DELREF", "ACKED"] = "KEEPREF",
) -> ResponseT:
"""
Combines the functionality of XACK and XDEL. Acknowledges the specified
message IDs in the given consumer group and simultaneously attempts to
delete the corresponding entries from the stream.
"""
if not ids:
raise DataError("XACKDEL requires at least one message ID")
if ref_policy not in {"KEEPREF", "DELREF", "ACKED"}:
raise DataError("XACKDEL ref_policy must be one of: KEEPREF, DELREF, ACKED")
pieces = [name, groupname, ref_policy, "IDS", len(ids)]
pieces.extend(ids)
return self.execute_command("XACKDEL", *pieces)
def xadd(
self,
name: KeyT,
fields: Dict[FieldT, EncodableT],
id: StreamIdT = "*",
maxlen: Optional[int] = None,
approximate: bool = True,
nomkstream: bool = False,
minid: Union[StreamIdT, None] = None,
limit: Optional[int] = None,
ref_policy: Optional[Literal["KEEPREF", "DELREF", "ACKED"]] = None,
) -> ResponseT:
"""
Add to a stream.
name: name of the stream
fields: dict of field/value pairs to insert into the stream
id: Location to insert this record. By default it is appended.
maxlen: truncate old stream members beyond this size.
Can't be specified with minid.
approximate: actual stream length may be slightly more than maxlen
nomkstream: When set to true, do not make a stream
minid: the minimum id in the stream to query.
Can't be specified with maxlen.
limit: specifies the maximum number of entries to retrieve
ref_policy: optional reference policy for consumer groups when trimming:
- KEEPREF (default): When trimming, preserves references in consumer groups' PEL
- DELREF: When trimming, removes all references from consumer groups' PEL
- ACKED: When trimming, only removes entries acknowledged by all consumer groups
For more information, see https://redis.io/commands/xadd
"""
pieces: list[EncodableT] = []
if maxlen is not None and minid is not None:
raise DataError("Only one of ```maxlen``` or ```minid``` may be specified")
if ref_policy is not None and ref_policy not in {"KEEPREF", "DELREF", "ACKED"}:
raise DataError("XADD ref_policy must be one of: KEEPREF, DELREF, ACKED")
if maxlen is not None:
if not isinstance(maxlen, int) or maxlen < 0:
raise DataError("XADD maxlen must be non-negative integer")
pieces.append(b"MAXLEN")
if approximate:
pieces.append(b"~")
pieces.append(str(maxlen))
if minid is not None:
pieces.append(b"MINID")
if approximate:
pieces.append(b"~")
pieces.append(minid)
if limit is not None:
pieces.extend([b"LIMIT", limit])
if nomkstream:
pieces.append(b"NOMKSTREAM")
if ref_policy is not None:
pieces.append(ref_policy)
pieces.append(id)
if not isinstance(fields, dict) or len(fields) == 0:
raise DataError("XADD fields must be a non-empty dict")
for pair in fields.items():
pieces.extend(pair)
return self.execute_command("XADD", name, *pieces)
def xautoclaim(
self,
name: KeyT,
groupname: GroupT,
consumername: ConsumerT,
min_idle_time: int,
start_id: StreamIdT = "0-0",
count: Optional[int] = None,
justid: bool = False,
) -> ResponseT:
"""
Transfers ownership of pending stream entries that match the specified
criteria. Conceptually, equivalent to calling XPENDING and then XCLAIM,
but provides a more straightforward way to deal with message delivery
failures via SCAN-like semantics.
name: name of the stream.
groupname: name of the consumer group.
consumername: name of a consumer that claims the message.
min_idle_time: filter messages that were idle less than this amount of
milliseconds.
start_id: filter messages with equal or greater ID.
count: optional integer, upper limit of the number of entries that the
command attempts to claim. Set to 100 by default.
justid: optional boolean, false by default. Return just an array of IDs
of messages successfully claimed, without returning the actual message
For more information, see https://redis.io/commands/xautoclaim
"""
try:
if int(min_idle_time) < 0:
raise DataError(
"XAUTOCLAIM min_idle_time must be a nonnegative integer"
)
except TypeError:
pass
kwargs = {}
pieces = [name, groupname, consumername, min_idle_time, start_id]
try:
if int(count) < 0:
raise DataError("XPENDING count must be a integer >= 0")
pieces.extend([b"COUNT", count])
except TypeError:
pass
if justid:
pieces.append(b"JUSTID")
kwargs["parse_justid"] = True
return self.execute_command("XAUTOCLAIM", *pieces, **kwargs)
def xclaim(
self,
name: KeyT,
groupname: GroupT,
consumername: ConsumerT,
min_idle_time: int,
message_ids: Union[List[StreamIdT], Tuple[StreamIdT]],
idle: Optional[int] = None,
time: Optional[int] = None,
retrycount: Optional[int] = None,
force: bool = False,
justid: bool = False,
) -> ResponseT:
"""
Changes the ownership of a pending message.
name: name of the stream.
groupname: name of the consumer group.
consumername: name of a consumer that claims the message.
min_idle_time: filter messages that were idle less than this amount of
milliseconds
message_ids: non-empty list or tuple of message IDs to claim
idle: optional. Set the idle time (last time it was delivered) of the
message in ms
time: optional integer. This is the same as idle but instead of a
relative amount of milliseconds, it sets the idle time to a specific
Unix time (in milliseconds).
retrycount: optional integer. set the retry counter to the specified
value. This counter is incremented every time a message is delivered
again.
force: optional boolean, false by default. Creates the pending message
entry in the PEL even if certain specified IDs are not already in the
PEL assigned to a different client.
justid: optional boolean, false by default. Return just an array of IDs
of messages successfully claimed, without returning the actual message
For more information, see https://redis.io/commands/xclaim
"""
if not isinstance(min_idle_time, int) or min_idle_time < 0:
raise DataError("XCLAIM min_idle_time must be a non negative integer")
if not isinstance(message_ids, (list, tuple)) or not message_ids:
raise DataError(
"XCLAIM message_ids must be a non empty list or "
"tuple of message IDs to claim"
)
kwargs = {}
pieces: list[EncodableT] = [name, groupname, consumername, str(min_idle_time)]
pieces.extend(list(message_ids))
if idle is not None:
if not isinstance(idle, int):
raise DataError("XCLAIM idle must be an integer")
pieces.extend((b"IDLE", str(idle)))
if time is not None:
if not isinstance(time, int):
raise DataError("XCLAIM time must be an integer")
pieces.extend((b"TIME", str(time)))
if retrycount is not None:
if not isinstance(retrycount, int):
raise DataError("XCLAIM retrycount must be an integer")
pieces.extend((b"RETRYCOUNT", str(retrycount)))
if force:
if not isinstance(force, bool):
raise DataError("XCLAIM force must be a boolean")
pieces.append(b"FORCE")
if justid:
if not isinstance(justid, bool):
raise DataError("XCLAIM justid must be a boolean")
pieces.append(b"JUSTID")
kwargs["parse_justid"] = True
return self.execute_command("XCLAIM", *pieces, **kwargs)
def xdel(self, name: KeyT, *ids: StreamIdT) -> ResponseT:
"""
Deletes one or more messages from a stream.
Args:
name: name of the stream.
*ids: message ids to delete.
For more information, see https://redis.io/commands/xdel
"""
return self.execute_command("XDEL", name, *ids)
def xdelex(
self,
name: KeyT,
*ids: StreamIdT,
ref_policy: Literal["KEEPREF", "DELREF", "ACKED"] = "KEEPREF",
) -> ResponseT:
"""
Extended version of XDEL that provides more control over how message entries
are deleted concerning consumer groups.
"""
if not ids:
raise DataError("XDELEX requires at least one message ID")
if ref_policy not in {"KEEPREF", "DELREF", "ACKED"}:
raise DataError("XDELEX ref_policy must be one of: KEEPREF, DELREF, ACKED")
pieces = [name, ref_policy, "IDS", len(ids)]
pieces.extend(ids)
return self.execute_command("XDELEX", *pieces)
def xgroup_create(
self,
name: KeyT,
groupname: GroupT,
id: StreamIdT = "$",
mkstream: bool = False,
entries_read: Optional[int] = None,
) -> ResponseT:
"""
Create a new consumer group associated with a stream.
name: name of the stream.
groupname: name of the consumer group.
id: ID of the last item in the stream to consider already delivered.
For more information, see https://redis.io/commands/xgroup-create
"""
pieces: list[EncodableT] = ["XGROUP CREATE", name, groupname, id]
if mkstream:
pieces.append(b"MKSTREAM")
if entries_read is not None:
pieces.extend(["ENTRIESREAD", entries_read])
return self.execute_command(*pieces)
def xgroup_delconsumer(
self, name: KeyT, groupname: GroupT, consumername: ConsumerT
) -> ResponseT:
"""
Remove a specific consumer from a consumer group.
Returns the number of pending messages that the consumer had before it
was deleted.
name: name of the stream.
groupname: name of the consumer group.
consumername: name of consumer to delete
For more information, see https://redis.io/commands/xgroup-delconsumer
"""
return self.execute_command("XGROUP DELCONSUMER", name, groupname, consumername)
def xgroup_destroy(self, name: KeyT, groupname: GroupT) -> ResponseT:
"""
Destroy a consumer group.
name: name of the stream.
groupname: name of the consumer group.
For more information, see https://redis.io/commands/xgroup-destroy
"""
return self.execute_command("XGROUP DESTROY", name, groupname)
def xgroup_createconsumer(
self, name: KeyT, groupname: GroupT, consumername: ConsumerT
) -> ResponseT:
"""
Consumers in a consumer group are auto-created every time a new
consumer name is mentioned by some command.
They can be explicitly created by using this command.
name: name of the stream.
groupname: name of the consumer group.
consumername: name of consumer to create.
See: https://redis.io/commands/xgroup-createconsumer
"""
return self.execute_command(
"XGROUP CREATECONSUMER", name, groupname, consumername
)
def xgroup_setid(
self,
name: KeyT,
groupname: GroupT,
id: StreamIdT,
entries_read: Optional[int] = None,
) -> ResponseT:
"""
Set the consumer group last delivered ID to something else.
name: name of the stream.
groupname: name of the consumer group.
id: ID of the last item in the stream to consider already delivered.
For more information, see https://redis.io/commands/xgroup-setid
"""
pieces = [name, groupname, id]
if entries_read is not None:
pieces.extend(["ENTRIESREAD", entries_read])
return self.execute_command("XGROUP SETID", *pieces)
def xinfo_consumers(self, name: KeyT, groupname: GroupT) -> ResponseT:
"""
Returns general information about the consumers in the group.
name: name of the stream.
groupname: name of the consumer group.
For more information, see https://redis.io/commands/xinfo-consumers
"""
return self.execute_command("XINFO CONSUMERS", name, groupname)
def xinfo_groups(self, name: KeyT) -> ResponseT:
"""
Returns general information about the consumer groups of the stream.
name: name of the stream.
For more information, see https://redis.io/commands/xinfo-groups
"""
return self.execute_command("XINFO GROUPS", name)
def xinfo_stream(self, name: KeyT, full: bool = False) -> ResponseT:
"""
Returns general information about the stream.
name: name of the stream.
full: optional boolean, false by default. Return full summary
For more information, see https://redis.io/commands/xinfo-stream
"""
pieces = [name]
options = {}
if full:
pieces.append(b"FULL")
options = {"full": full}
return self.execute_command("XINFO STREAM", *pieces, **options)
def xlen(self, name: KeyT) -> ResponseT:
"""
Returns the number of elements in a given stream.
For more information, see https://redis.io/commands/xlen
"""
return self.execute_command("XLEN", name, keys=[name])
def xpending(self, name: KeyT, groupname: GroupT) -> ResponseT:
"""
Returns information about pending messages of a group.
name: name of the stream.
groupname: name of the consumer group.
For more information, see https://redis.io/commands/xpending
"""
return self.execute_command("XPENDING", name, groupname, keys=[name])
def xpending_range(
self,
name: KeyT,
groupname: GroupT,
min: StreamIdT,
max: StreamIdT,
count: int,
consumername: Union[ConsumerT, None] = None,
idle: Optional[int] = None,
) -> ResponseT:
"""
Returns information about pending messages, in a range.
name: name of the stream.
groupname: name of the consumer group.
idle: available from version 6.2. filter entries by their
idle-time, given in milliseconds (optional).
min: minimum stream ID.
max: maximum stream ID.
count: number of messages to return
consumername: name of a consumer to filter by (optional).
"""
if {min, max, count} == {None}:
if idle is not None or consumername is not None:
raise DataError(
"if XPENDING is provided with idle time"
" or consumername, it must be provided"
" with min, max and count parameters"
)
return self.xpending(name, groupname)
pieces = [name, groupname]
if min is None or max is None or count is None:
raise DataError(
"XPENDING must be provided with min, max "
"and count parameters, or none of them."
)
# idle
try:
if int(idle) < 0:
raise DataError("XPENDING idle must be a integer >= 0")
pieces.extend(["IDLE", idle])
except TypeError:
pass
# count
try:
if int(count) < 0:
raise DataError("XPENDING count must be a integer >= 0")
pieces.extend([min, max, count])
except TypeError:
pass
# consumername
if consumername:
pieces.append(consumername)
return self.execute_command("XPENDING", *pieces, parse_detail=True)
def xrange(
self,
name: KeyT,
min: StreamIdT = "-",
max: StreamIdT = "+",
count: Optional[int] = None,
) -> ResponseT:
"""
Read stream values within an interval.
name: name of the stream.
start: first stream ID. defaults to '-',
meaning the earliest available.
finish: last stream ID. defaults to '+',
meaning the latest available.
count: if set, only return this many items, beginning with the
earliest available.
For more information, see https://redis.io/commands/xrange
"""
pieces = [min, max]
if count is not None:
if not isinstance(count, int) or count < 1:
raise DataError("XRANGE count must be a positive integer")
pieces.append(b"COUNT")
pieces.append(str(count))
return self.execute_command("XRANGE", name, *pieces, keys=[name])
def xread(
self,
streams: Dict[KeyT, StreamIdT],
count: Optional[int] = None,
block: Optional[int] = None,
) -> ResponseT:
"""
Block and monitor multiple streams for new data.
streams: a dict of stream names to stream IDs, where
IDs indicate the last ID already seen.
count: if set, only return this many items, beginning with the
earliest available.
block: number of milliseconds to wait, if nothing already present.
For more information, see https://redis.io/commands/xread
"""
pieces = []
if block is not None:
if not isinstance(block, int) or block < 0:
raise DataError("XREAD block must be a non-negative integer")
pieces.append(b"BLOCK")
pieces.append(str(block))
if count is not None:
if not isinstance(count, int) or count < 1:
raise DataError("XREAD count must be a positive integer")
pieces.append(b"COUNT")
pieces.append(str(count))
if not isinstance(streams, dict) or len(streams) == 0:
raise DataError("XREAD streams must be a non empty dict")
pieces.append(b"STREAMS")
keys, values = zip(*streams.items())
pieces.extend(keys)
pieces.extend(values)
return self.execute_command("XREAD", *pieces, keys=keys)
def xreadgroup(
self,
groupname: str,
consumername: str,
streams: Dict[KeyT, StreamIdT],
count: Optional[int] = None,
block: Optional[int] = None,
noack: bool = False,
claim_min_idle_time: Optional[int] = None,
) -> ResponseT:
"""
Read from a stream via a consumer group.
groupname: name of the consumer group.
consumername: name of the requesting consumer.
streams: a dict of stream names to stream IDs, where
IDs indicate the last ID already seen.
count: if set, only return this many items, beginning with the
earliest available.
block: number of milliseconds to wait, if nothing already present.
noack: do not add messages to the PEL
claim_min_idle_time: accepts an integer type and represents a
time interval in milliseconds
For more information, see https://redis.io/commands/xreadgroup
"""
options = {}
pieces: list[EncodableT] = [b"GROUP", groupname, consumername]
if count is not None:
if not isinstance(count, int) or count < 1:
raise DataError("XREADGROUP count must be a positive integer")
pieces.append(b"COUNT")
pieces.append(str(count))
if block is not None:
if not isinstance(block, int) or block < 0:
raise DataError("XREADGROUP block must be a non-negative integer")
pieces.append(b"BLOCK")
pieces.append(str(block))
if noack:
pieces.append(b"NOACK")
if claim_min_idle_time is not None:
if not isinstance(claim_min_idle_time, int) or claim_min_idle_time < 0:
raise DataError(
"XREADGROUP claim_min_idle_time must be a non-negative integer"
)
pieces.append(b"CLAIM")
pieces.append(claim_min_idle_time)
options["claim_min_idle_time"] = claim_min_idle_time
if not isinstance(streams, dict) or len(streams) == 0:
raise DataError("XREADGROUP streams must be a non empty dict")
pieces.append(b"STREAMS")
pieces.extend(streams.keys())
pieces.extend(streams.values())
return self.execute_command("XREADGROUP", *pieces, **options)
def xrevrange(
self,
name: KeyT,
max: StreamIdT = "+",
min: StreamIdT = "-",
count: Optional[int] = None,
) -> ResponseT:
"""
Read stream values within an interval, in reverse order.
name: name of the stream
start: first stream ID. defaults to '+',
meaning the latest available.
finish: last stream ID. defaults to '-',
meaning the earliest available.
count: if set, only return this many items, beginning with the
latest available.
For more information, see https://redis.io/commands/xrevrange
"""
pieces: list[EncodableT] = [max, min]
if count is not None:
if not isinstance(count, int) or count < 1:
raise DataError("XREVRANGE count must be a positive integer")
pieces.append(b"COUNT")
pieces.append(str(count))
return self.execute_command("XREVRANGE", name, *pieces, keys=[name])
def xtrim(
self,
name: KeyT,
maxlen: Optional[int] = None,
approximate: bool = True,
minid: Union[StreamIdT, None] = None,
limit: Optional[int] = None,
ref_policy: Optional[Literal["KEEPREF", "DELREF", "ACKED"]] = None,
) -> ResponseT:
"""
Trims old messages from a stream.
name: name of the stream.
maxlen: truncate old stream messages beyond this size
Can't be specified with minid.
approximate: actual stream length may be slightly more than maxlen
minid: the minimum id in the stream to query
Can't be specified with maxlen.
limit: specifies the maximum number of entries to retrieve
ref_policy: optional reference policy for consumer groups:
- KEEPREF (default): Trims entries but preserves references in consumer groups' PEL
- DELREF: Trims entries and removes all references from consumer groups' PEL
- ACKED: Only trims entries that were read and acknowledged by all consumer groups
For more information, see https://redis.io/commands/xtrim
"""
pieces: list[EncodableT] = []
if maxlen is not None and minid is not None:
raise DataError("Only one of ``maxlen`` or ``minid`` may be specified")
if maxlen is None and minid is None:
raise DataError("One of ``maxlen`` or ``minid`` must be specified")
if ref_policy is not None and ref_policy not in {"KEEPREF", "DELREF", "ACKED"}:
raise DataError("XTRIM ref_policy must be one of: KEEPREF, DELREF, ACKED")
if maxlen is not None:
pieces.append(b"MAXLEN")
if minid is not None:
pieces.append(b"MINID")
if approximate:
pieces.append(b"~")
if maxlen is not None:
pieces.append(maxlen)
if minid is not None:
pieces.append(minid)
if limit is not None:
pieces.append(b"LIMIT")
pieces.append(limit)
if ref_policy is not None:
pieces.append(ref_policy)
return self.execute_command("XTRIM", name, *pieces)
AsyncStreamCommands = StreamCommands
| StreamCommands |
python | getsentry__sentry | src/sentry/releases/endpoints/project_release_repositories.py | {
"start": 544,
"end": 2004
} | class ____(ProjectEndpoint):
publish_status = {
"GET": ApiPublishStatus.UNKNOWN,
}
permission_classes = (ProjectReleasePermission,)
def get(self, request: Request, project, version) -> Response:
"""
Retrieve Project Repositories from a Release
````````````````````````````
This endpoint is used in the commits and changed files tab of the release details page
:pparam string organization_id_or_slug: the id or slug of the organization the
release belongs to.
:pparam string project_id_or_slug: the id or slug of the project to retrieve the
release of.
:pparam string version: the version identifier of the release.
:auth: required
"""
try:
release = Release.objects.get(
organization_id=project.organization_id, projects=project, version=version
)
except Release.DoesNotExist:
raise ResourceDoesNotExist
release_commits = ReleaseCommit.objects.filter(release=release).select_related("commit")
repository_ids = {c.commit.repository_id for c in release_commits}
repositories = Repository.objects.filter(id__in=repository_ids)
return Response(
serialize(
list(repositories),
request.user,
)
)
| ProjectReleaseRepositories |
python | doocs__leetcode | solution/2800-2899/2861.Maximum Number of Alloys/Solution.py | {
"start": 0,
"end": 610
} | class ____:
def maxNumberOfAlloys(
self,
n: int,
k: int,
budget: int,
composition: List[List[int]],
stock: List[int],
cost: List[int],
) -> int:
ans = 0
for c in composition:
l, r = 0, budget + stock[0]
while l < r:
mid = (l + r + 1) >> 1
s = sum(max(0, mid * x - y) * z for x, y, z in zip(c, stock, cost))
if s <= budget:
l = mid
else:
r = mid - 1
ans = max(ans, l)
return ans
| Solution |
python | pallets__werkzeug | src/werkzeug/exceptions.py | {
"start": 11360,
"end": 12662
} | class ____(HTTPException):
"""*405* `Method Not Allowed`
Raise if the server used a method the resource does not handle. For
example `POST` if the resource is view only. Especially useful for REST.
The first argument for this exception should be a list of allowed methods.
Strictly speaking the response would be invalid if you don't provide valid
methods in the header which you can do with that list.
"""
code = 405
description = "The method is not allowed for the requested URL."
def __init__(
self,
valid_methods: t.Iterable[str] | None = None,
description: str | None = None,
response: SansIOResponse | None = None,
) -> None:
"""Takes an optional list of valid http methods
starting with werkzeug 0.3 the list will be mandatory."""
super().__init__(description=description, response=response)
self.valid_methods = valid_methods
def get_headers(
self,
environ: WSGIEnvironment | None = None,
scope: dict[str, t.Any] | None = None,
) -> list[tuple[str, str]]:
headers = super().get_headers(environ, scope)
if self.valid_methods:
headers.append(("Allow", ", ".join(self.valid_methods)))
return headers
| MethodNotAllowed |
python | pyparsing__pyparsing | examples/btpyparse.py | {
"start": 377,
"end": 4129
} | class ____:
"""Class to encapsulate undefined macro references"""
def __init__(self, name):
self.name = name
def __repr__(self):
return f'Macro("{self.name}")'
def __eq__(self, other):
return self.name == other.name
# Character literals
LCURLY, RCURLY, LPAREN, RPAREN, QUOTE, COMMA, AT, EQUALS, HASH = map(
Suppress, '{}()",@=#'
)
def bracketed(expr):
"""Return matcher for `expr` between curly brackets or parentheses"""
return (LPAREN + expr + RPAREN) | (LCURLY + expr + RCURLY)
# Define parser components for strings (the hard bit)
chars_no_curly = Regex(r"[^{}]+")
chars_no_curly.leave_whitespace()
chars_no_quotecurly = Regex(r'[^"{}]+')
chars_no_quotecurly.leave_whitespace()
# Curly string is some stuff without curlies, or nested curly sequences
curly_string = Forward()
curly_item = Group(curly_string) | chars_no_curly
curly_string << LCURLY + ZeroOrMore(curly_item) + RCURLY
# quoted string is either just stuff within quotes, or stuff within quotes, within
# which there is nested curliness
quoted_item = Group(curly_string) | chars_no_quotecurly
quoted_string = QUOTE + ZeroOrMore(quoted_item) + QUOTE
# Numbers can just be numbers. Only integers though.
number = Regex("[0-9]+")
# Basis characters (by exclusion) for variable / field names. The following
# list of characters is from the btparse documentation
any_name = Regex("[^\\s\"#%'(),={}]+")
# btparse says, and the test bibs show by experiment, that macro and field names
# cannot start with a digit. In fact entry type names cannot start with a digit
# either (see tests/bibs). Cite keys can start with a digit
not_digname = Regex("[^\\d\\s\"#%'(),={}][^\\s\"#%'(),={}]*")
# Comment comments out to end of line
comment = AT + CaselessLiteral("comment") + Regex(r"[\s{(].*").leave_whitespace()
# The name types with their digiteyness
not_dig_lower = not_digname.copy().set_parse_action(lambda t: t[0].lower())
macro_def = not_dig_lower.copy()
macro_ref = not_dig_lower.copy().set_parse_action(lambda t: Macro(t[0].lower()))
field_name = not_dig_lower.copy()
# Spaces in names mean they cannot clash with field names
entry_type = not_dig_lower("entry_type")
cite_key = any_name("cite_key")
# Number has to be before macro name
string = number | macro_ref | quoted_string | curly_string
# There can be hash concatenation
field_value = string + ZeroOrMore(HASH + string)
field_def = Group(field_name + EQUALS + field_value)
entry_contents = Dict(ZeroOrMore(field_def + COMMA) + Optional(field_def))
# Entry is surrounded either by parentheses or curlies
entry = AT + entry_type + bracketed(cite_key + COMMA + entry_contents)
# Preamble is a macro-like thing with no name
preamble = AT + CaselessLiteral("preamble") + bracketed(field_value)
# Macros (aka strings)
macro_contents = macro_def + EQUALS + field_value
macro = AT + CaselessLiteral("string") + bracketed(macro_contents)
# Implicit comments
icomment = SkipTo("@").set_parse_action(lambda t: t.insert(0, "icomment"))
# entries are last in the list (other than the fallback) because they have
# arbitrary start patterns that would match comments, preamble or macro
definitions = Group(comment | preamble | macro | entry | icomment)
# Start symbol
bibfile = ZeroOrMore(definitions)
def parse_str(str):
return bibfile.parse_string(str)
if __name__ == "__main__":
# Run basic test
txt = """
Some introductory text
(implicit comment)
@ARTICLE{Authors2011,
author = {First Author and Second Author and Third Author},
title = {An article about {S}omething},
journal = "Journal of Articles",
year = {2011},
volume = {16},
pages = {1140--1141},
number = {2}
}
"""
print("\n\n".join(defn.dump() for defn in parse_str(txt)))
| Macro |
python | plotly__plotly.py | plotly/io/_base_renderers.py | {
"start": 1420,
"end": 1595
} | class ____(BaseRenderer):
"""
Base class for all mime type renderers
"""
def to_mimebundle(self, fig_dict):
raise NotImplementedError()
| MimetypeRenderer |
python | pytorch__pytorch | test/test_serialization.py | {
"start": 4738,
"end": 39405
} | class ____:
def _test_serialization_data(self):
a = [torch.randn(5, 5).float() for i in range(2)]
b = [a[i % 2] for i in range(4)] # 0-3
b += [a[0].storage()] # 4
b += [a[0].reshape(-1)[1:4].storage()] # 5
b += [torch.arange(1, 11).int()] # 6
t1 = torch.FloatTensor().set_(a[0].reshape(-1)[1:4].clone().storage(), 0, (3,), (1,))
t2 = torch.FloatTensor().set_(a[0].reshape(-1)[1:4].clone().storage(), 0, (3,), (1,))
b += [(t1.storage(), t1.storage(), t2.storage())] # 7
b += [a[0].reshape(-1)[0:2].storage()] # 8
return b
def _test_serialization_assert(self, b, c):
self.assertEqual(b, c, atol=0, rtol=0)
self.assertTrue(isinstance(c[0], torch.FloatTensor))
self.assertTrue(isinstance(c[1], torch.FloatTensor))
self.assertTrue(isinstance(c[2], torch.FloatTensor))
self.assertTrue(isinstance(c[3], torch.FloatTensor))
self.assertTrue(isinstance(c[4], torch.storage.TypedStorage))
self.assertEqual(c[4].dtype, torch.float)
c[0].fill_(10)
self.assertEqual(c[0], c[2], atol=0, rtol=0)
self.assertEqual(c[4], torch.FloatStorage(25).fill_(10), atol=0, rtol=0)
c[1].fill_(20)
self.assertEqual(c[1], c[3], atol=0, rtol=0)
# I have to do it in this roundabout fashion, because there's no
# way to slice storages
for i in range(4):
self.assertEqual(c[4][i + 1], c[5][i])
# check that serializing the same storage view object unpickles
# it as one object not two (and vice versa)
views = c[7]
self.assertEqual(views[0]._cdata, views[1]._cdata)
self.assertEqual(views[0], views[2])
self.assertNotEqual(views[0]._cdata, views[2]._cdata)
rootview = c[8]
self.assertEqual(rootview.data_ptr(), c[0].data_ptr())
def test_serialization_zipfile_utils(self):
data = {
'a': b'12039810948234589',
'b': b'1239081209484958',
'c/d': b'94589480984058'
}
def test(name_or_buffer):
with torch.serialization._open_zipfile_writer(name_or_buffer) as zip_file:
for key in data:
zip_file.write_record(key, data[key], len(data[key]))
if hasattr(name_or_buffer, 'seek'):
name_or_buffer.seek(0)
with torch.serialization._open_zipfile_reader(name_or_buffer) as zip_file:
for key in data:
actual = zip_file.get_record(key)
expected = data[key]
self.assertEqual(expected, actual)
with tempfile.NamedTemporaryFile() as f:
test(f)
with TemporaryFileName() as fname:
test(fname)
test(io.BytesIO())
def _test_serialization(self, weights_only):
# Test serialization with a real file
b = self._test_serialization_data()
with tempfile.NamedTemporaryFile() as f:
torch.save(b, f)
f.seek(0)
c = torch.load(f, weights_only=weights_only)
self._test_serialization_assert(b, c)
with TemporaryFileName() as fname:
torch.save(b, fname)
c = torch.load(fname, weights_only=weights_only)
self._test_serialization_assert(b, c)
# test non-ascii encoding of bytes arrays/strings
# The following bytes are produced by serializing
# [b'\xc5\xbc\xc4\x85\xc4\x85\xc3\xb3\xc5\xbc\xc4\x85\xc5\xbc', torch.zeros(1, dtype=torch.float), 2]
# in Python 2.7.12 and PyTorch 0.4.1, where the first element contains
# bytes of some utf-8 characters (i.e., `utf8_str.encode('utf-8')`).
serialized = (
b'\x80\x02\x8a\nl\xfc\x9cF\xf9 j\xa8P\x19.\x80\x02M\xe9\x03.'
b'\x80\x02}q\x01(U\x10protocol_versionq\x02M\xe9\x03U\n'
b'type_sizesq\x03}q\x04(U\x03intq\x05K\x04U\x05shortq\x06K\x02U'
b'\x04longq\x07K\x04uU\rlittle_endianq\x08\x88u.\x80\x02]q'
b'\x01(U\x0e\xc5\xbc\xc4\x85\xc4\x85\xc3\xb3\xc5\xbc\xc4\x85'
b'\xc5\xbcq\x02ctorch._utils\n_rebuild_tensor_v2\nq\x03((U'
b'\x07storageq\x04ctorch\nFloatStorage\nq\x05U\x0845640624q'
b'\x06U\x03cpuq\x07\x8a\x01\x01NtQK\x00K\x01\x85K\x01\x85'
b'\x89NtRq\x08K\x02e.\x80\x02]q\x01U\x0845640624q\x02a.\x01\x00'
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
)
buf = io.BytesIO(serialized)
utf8_bytes = b'\xc5\xbc\xc4\x85\xc4\x85\xc3\xb3\xc5\xbc\xc4\x85\xc5\xbc'
utf8_str = utf8_bytes.decode('utf-8')
loaded_utf8 = torch.load(buf, weights_only=weights_only, encoding='utf-8')
self.assertEqual(loaded_utf8, [utf8_str, torch.zeros(1, dtype=torch.float), 2])
buf.seek(0)
loaded_bytes = torch.load(buf, weights_only=weights_only, encoding='bytes')
self.assertEqual(loaded_bytes, [utf8_bytes, torch.zeros(1, dtype=torch.float), 2])
def test_serialization(self):
self._test_serialization(False)
def test_serialization_safe(self):
self._test_serialization(True)
def test_serialization_filelike(self):
# Test serialization (load and save) with a filelike object
b = self._test_serialization_data()
with BytesIOContext() as f:
torch.save(b, f)
f.seek(0)
c = torch.load(f)
self._test_serialization_assert(b, c)
def test_serialization_fake_zip(self):
data = [
ord('P'),
ord('K'),
5,
6
]
for _ in range(100):
data.append(0)
t = torch.tensor(data, dtype=torch.uint8)
with tempfile.NamedTemporaryFile() as f:
torch.save(t, f)
# If this check is False for all Python versions (i.e. the fix
# has been backported), this test and torch.serialization._is_zipfile
# can be deleted
self.assertTrue(zipfile.is_zipfile(f))
self.assertFalse(torch.serialization._is_zipfile(f))
f.seek(0)
self.assertEqual(torch.load(f), t)
def test_serialization_gzip(self):
# Test serialization with gzip file
b = self._test_serialization_data()
with tempfile.NamedTemporaryFile() as f1, tempfile.NamedTemporaryFile(delete=False) as f2:
torch.save(b, f1)
f1.seek(0)
with gzip.open(f2.name, 'wb') as f_out:
shutil.copyfileobj(f1, f_out)
with gzip.open(f2.name, 'rb') as f:
c = torch.load(f)
self._test_serialization_assert(b, c)
f2.close()
os.unlink(f2.name)
@unittest.skipIf(
not TEST_DILL or HAS_DILL_AT_LEAST_0_3_1,
'"dill" not found or is correct version'
)
def test_serialization_dill_version_not_supported(self):
x = torch.randn(5, 5)
with tempfile.NamedTemporaryFile() as f:
with self.assertRaisesRegex(ValueError, 'supports dill >='):
torch.save(x, f, pickle_module=dill)
f.seek(0)
with self.assertRaisesRegex(ValueError, 'supports dill >='):
# weights_only=False as this is legacy code that saves the model
x2 = torch.load(f, pickle_module=dill, encoding='utf-8', weights_only=False)
def test_pickle_module(self):
class ThrowingUnpickler(pickle.Unpickler):
def load(self, *args, **kwargs):
raise RuntimeError("rumpelstiltskin")
class ThrowingModule:
Unpickler = ThrowingUnpickler
load = ThrowingUnpickler.load
x = torch.eye(3)
with tempfile.NamedTemporaryFile() as f:
torch.save(x, f)
f.seek(0)
with self.assertRaisesRegex(RuntimeError, "rumpelstiltskin"):
# weights_only=False as True does not support custom pickle module
torch.load(f, pickle_module=ThrowingModule, weights_only=False)
f.seek(0)
z = torch.load(f)
self.assertEqual(x, z)
@unittest.skipIf(
not TEST_DILL or not HAS_DILL_AT_LEAST_0_3_1,
'"dill" not found or not correct version'
)
@skipIfTorchDynamo("Different behavior between 3.11 and 3.13, causing CI issues")
def test_serialization_dill(self):
x = torch.randn(5, 5)
with tempfile.NamedTemporaryFile() as f:
torch.save(x, f, pickle_module=dill)
f.seek(0)
# weights_only=False as True does not support custom pickle_module
x2 = torch.load(f, pickle_module=dill, encoding='utf-8', weights_only=False)
self.assertIsInstance(x2, type(x))
self.assertEqual(x, x2)
f.seek(0)
# weights_only=False as True does not support custom pickle_module
x3 = torch.load(f, pickle_module=dill, weights_only=False)
self.assertIsInstance(x3, type(x))
self.assertEqual(x, x3)
def test_serialization_offset_gzip(self):
a = torch.randn(5, 5)
i = 41
f2 = tempfile.NamedTemporaryFile(delete=False)
with tempfile.NamedTemporaryFile() as f1:
pickle.dump(i, f1)
torch.save(a, f1)
f1.seek(0)
with gzip.open(f2.name, 'wb') as f_out:
shutil.copyfileobj(f1, f_out)
with gzip.open(f2.name, 'rb') as f:
j = pickle.load(f)
b = torch.load(f)
self.assertTrue(torch.equal(a, b))
self.assertEqual(i, j)
def _test_serialization_sparse(self, weights_only):
def _test_serialization(conversion):
x = torch.zeros(3, 3)
x[1][1] = 1
x = conversion(x)
with tempfile.NamedTemporaryFile() as f:
torch.save({"tensor": x}, f)
f.seek(0)
y = torch.load(f, weights_only=weights_only)
self.assertEqual(x, y["tensor"], exact_is_coalesced=True)
_test_serialization(lambda x: x.to_sparse())
_test_serialization(lambda x: x.to_sparse_csr())
_test_serialization(lambda x: x.to_sparse_csc())
_test_serialization(lambda x: x.to_sparse_bsr((1, 1)))
_test_serialization(lambda x: x.to_sparse_bsc((1, 1)))
def test_serialization_sparse(self):
self._test_serialization(False)
def test_serialization_sparse_safe(self):
self._test_serialization(True)
@unittest.skipIf(True, "Temporary skip due to gh-153143")
def test_serialization_sparse_invalid(self):
x = torch.zeros(3, 3)
x[1][1] = 1
x = x.to_sparse()
class TensorSerializationSpoofer:
def __init__(self, tensor):
self.tensor = tensor
def __reduce_ex__(self, proto):
invalid_indices = self.tensor._indices().clone()
invalid_indices[0][0] = 3
return (
torch._utils._rebuild_sparse_tensor,
(
self.tensor.layout,
(
invalid_indices,
self.tensor._values(),
self.tensor.size())))
with tempfile.NamedTemporaryFile() as f:
torch.save({"spoofed": TensorSerializationSpoofer(x)}, f)
for weights_only in (False, True):
f.seek(0)
with torch.sparse.check_sparse_tensor_invariants(), self.assertRaisesRegex(
RuntimeError,
"size is inconsistent with indices"):
y = torch.load(f, weights_only=weights_only)
@unittest.skipIf(True, "Temporary skip due to gh-153143")
def test_serialization_sparse_invalid_legacy_ctor(self):
# This is set in test class setup but would not be check when running user code
prev_invariant_check_enabled = torch.sparse.check_sparse_tensor_invariants.is_enabled()
try:
torch.sparse.check_sparse_tensor_invariants.disable()
x = torch.zeros(3, 3)
x[1][1] = 1
x = x.to_sparse()
x_legacy_ctor = torch.sparse.FloatTensor(x.indices(), x.values())
# technically legacy ctor will still always be rebuilt with _rebuild_sparse_tensor
# this is to test that legacy ctor in data.pkl will be validated by weights_only unpickler
class LegacyCtorSerializationSpoofer:
def __init__(self, tensor):
self.tensor = tensor
def __reduce_ex__(self, proto):
indices = self.tensor._indices()
indices[0][0] = 3
return (torch.sparse.FloatTensor, (indices, self.tensor._values(), self.tensor.size()))
with tempfile.NamedTemporaryFile() as f:
sd = {"spoofed_legacy_ctor": LegacyCtorSerializationSpoofer(x_legacy_ctor)}
torch.save(sd, f)
for weights_only in (True,):
f.seek(0)
with torch.sparse.check_sparse_tensor_invariants(), self.assertRaisesRegex(
RuntimeError,
"size is inconsistent with indices|found negative index"):
y = torch.load(f, weights_only=weights_only)
finally:
if prev_invariant_check_enabled:
torch.sparse.check_sparse_tensor_invariants.enable()
@torch.sparse.check_sparse_tensor_invariants(enable=True)
def _test_serialization_sparse_compressed_invalid(self,
conversion,
get_compressed_indices,
get_plain_indices):
x = torch.zeros(3, 3)
x[1][1] = 1
x = conversion(x)
class TensorSerializationSpoofer:
def __init__(self, tensor):
self.tensor = tensor
def __reduce_ex__(self, proto):
invalid_compressed_indices = get_compressed_indices(self.tensor).clone()
invalid_compressed_indices[0] = 3
return (
torch._utils._rebuild_sparse_tensor,
(
self.tensor.layout,
(
invalid_compressed_indices,
get_plain_indices(self.tensor),
self.tensor.values(),
self.tensor.size())))
if x.layout in {torch.sparse_csr, torch.sparse_bsr}:
compressed_indices_name = 'crow_indices'
else:
compressed_indices_name = 'ccol_indices'
with tempfile.NamedTemporaryFile() as f:
torch.save({"spoofed": TensorSerializationSpoofer(x)}, f)
f.seek(0)
with self.assertRaisesRegex(
RuntimeError,
f"`{compressed_indices_name}[[]..., 0[]] == 0` is not satisfied."):
y = torch.load(f)
@unittest.skipIf(True, "Temporary skip due to gh-153143")
def test_serialization_sparse_csr_invalid(self):
self._test_serialization_sparse_compressed_invalid(
torch.Tensor.to_sparse_csr, torch.Tensor.crow_indices, torch.Tensor.col_indices)
@unittest.skipIf(True, "Temporary skip due to gh-153143")
def test_serialization_sparse_csc_invalid(self):
self._test_serialization_sparse_compressed_invalid(
torch.Tensor.to_sparse_csc, torch.Tensor.ccol_indices, torch.Tensor.row_indices)
@unittest.skipIf(True, "Temporary skip due to gh-153143")
def test_serialization_sparse_bsr_invalid(self):
self._test_serialization_sparse_compressed_invalid(
lambda x: x.to_sparse_bsr((1, 1)), torch.Tensor.crow_indices, torch.Tensor.col_indices)
@unittest.skipIf(True, "Temporary skip due to gh-153143")
def test_serialization_sparse_bsc_invalid(self):
self._test_serialization_sparse_compressed_invalid(
lambda x: x.to_sparse_bsc((1, 1)), torch.Tensor.ccol_indices, torch.Tensor.row_indices)
def test_serialize_device(self):
device_str = ['cpu', 'cpu:0', 'cuda', 'cuda:0']
device_obj = [torch.device(d) for d in device_str]
for device in device_obj:
device_copied = copy.deepcopy(device)
self.assertEqual(device, device_copied)
def _test_serialization_backwards_compat(self, weights_only):
a = [torch.arange(1 + i, 26 + i).view(5, 5).float() for i in range(2)]
b = [a[i % 2] for i in range(4)]
b += [a[0].storage()]
b += [a[0].reshape(-1)[1:4].clone().storage()]
path = download_file('https://download.pytorch.org/test_data/legacy_serialized.pt')
if weights_only:
with self.assertRaisesRegex(RuntimeError,
"Cannot use ``weights_only=True`` with files saved in the legacy .tar format."):
c = torch.load(path, weights_only=weights_only)
c = torch.load(path, weights_only=False)
self.assertEqual(b, c, atol=0, rtol=0)
self.assertTrue(isinstance(c[0], torch.FloatTensor))
self.assertTrue(isinstance(c[1], torch.FloatTensor))
self.assertTrue(isinstance(c[2], torch.FloatTensor))
self.assertTrue(isinstance(c[3], torch.FloatTensor))
self.assertTrue(isinstance(c[4], torch.storage.TypedStorage))
self.assertEqual(c[4].dtype, torch.float32)
c[0].fill_(10)
self.assertEqual(c[0], c[2], atol=0, rtol=0)
self.assertEqual(c[4], torch.FloatStorage(25).fill_(10), atol=0, rtol=0)
c[1].fill_(20)
self.assertEqual(c[1], c[3], atol=0, rtol=0)
# test some old tensor serialization mechanism
class OldTensorBase:
def __init__(self, new_tensor):
self.new_tensor = new_tensor
def __getstate__(self):
return (self.new_tensor.storage(),
self.new_tensor.storage_offset(),
tuple(self.new_tensor.size()),
self.new_tensor.stride())
class OldTensorV1(OldTensorBase):
def __reduce__(self):
return (torch.Tensor, (), self.__getstate__())
class OldTensorV2(OldTensorBase):
def __reduce__(self):
return (_rebuild_tensor, self.__getstate__())
x = torch.randn(30).as_strided([2, 3], [9, 3], 2)
for old_cls in [OldTensorV1, OldTensorV2]:
with tempfile.NamedTemporaryFile() as f:
old_x = old_cls(x)
torch.save(old_x, f)
f.seek(0)
load_x = torch.load(f, weights_only=weights_only)
self.assertEqual(x.storage(), load_x.storage())
self.assertEqual(x.storage_offset(), load_x.storage_offset())
self.assertEqual(x.size(), load_x.size())
self.assertEqual(x.stride(), load_x.stride())
def test_serialization_backwards_compat(self):
self._test_serialization_backwards_compat(False)
def test_serialization_backwards_compat_safe(self):
self._test_serialization_backwards_compat(True)
@skipIfTorchDynamo("graph breaks messages collide with warnings")
def test_serialization_save_warnings(self):
with warnings.catch_warnings(record=True) as warns:
with tempfile.NamedTemporaryFile() as checkpoint:
x = torch.save(torch.nn.Linear(2, 3), checkpoint)
self.assertEqual(len(warns), 0)
def test_serialization_map_location(self):
test_file_path = download_file('https://download.pytorch.org/test_data/gpu_tensors.pt')
def map_location(storage, loc):
return storage
def generate_map_locations(device_type):
return [
{'cuda:0': device_type + ':0'},
device_type,
device_type + ':0',
torch.device(device_type),
torch.device(device_type, 0)
]
def load_bytes():
with open(test_file_path, 'rb') as f:
return io.BytesIO(f.read())
fileobject_lambdas = [lambda: test_file_path, load_bytes]
cpu_map_locations = [
map_location,
{'cuda:0': 'cpu'},
'cpu',
torch.device('cpu'),
]
gpu_0_map_locations = generate_map_locations('cuda')
gpu_last_map_locations = [
f'cuda:{torch.cuda.device_count() - 1}',
]
xpu_0_map_locations = generate_map_locations('xpu')
xpu_last_map_locations = [
f'xpu:{torch.xpu.device_count() - 1}',
]
mtia_0_map_locations = generate_map_locations('mtia')
mtia_last_map_locations = [
f'mtia:{torch.mtia.device_count() - 1}',
]
def check_map_locations(map_locations, dtype, intended_device):
for fileobject_lambda in fileobject_lambdas:
for map_location in map_locations:
tensor = torch.load(fileobject_lambda(), map_location=map_location)
self.assertEqual(tensor.device, intended_device)
self.assertEqual(tensor.dtype, dtype)
self.assertEqual(tensor, torch.tensor([[1.0, 2.0], [3.0, 4.0]], dtype=dtype, device=intended_device))
check_map_locations(cpu_map_locations, torch.float, torch.device('cpu'))
if torch.cuda.is_available():
check_map_locations(gpu_0_map_locations, torch.float, torch.device('cuda', 0))
check_map_locations(
gpu_last_map_locations,
torch.float,
torch.device('cuda', torch.cuda.device_count() - 1)
)
if torch.xpu.is_available():
check_map_locations(xpu_0_map_locations, torch.float, torch.device('xpu', 0))
check_map_locations(
xpu_last_map_locations,
torch.float,
torch.device('xpu', torch.xpu.device_count() - 1)
)
if torch.mtia.is_available():
check_map_locations(mtia_0_map_locations, torch.float, torch.device('mtia', 0))
check_map_locations(
mtia_last_map_locations,
torch.float,
torch.device('mtia', torch.mtia.device_count() - 1)
)
@unittest.skipIf(torch.cuda.is_available(), "Testing torch.load on CPU-only machine")
def test_load_nonexistent_device(self):
# Setup: create a serialized file object with a 'cuda:0' restore location
# The following was generated by saving a torch.randn(2, device='cuda') tensor.
serialized = (b'\x80\x02\x8a\nl\xfc\x9cF\xf9 j\xa8P\x19.\x80\x02M\xe9'
b'\x03.\x80\x02}q\x00(X\x10\x00\x00\x00protocol_versionq'
b'\x01M\xe9\x03X\r\x00\x00\x00little_endianq\x02\x88X\n'
b'\x00\x00\x00type_sizesq\x03}q\x04(X\x05\x00\x00\x00shortq'
b'\x05K\x02X\x03\x00\x00\x00intq\x06K\x04X\x04\x00\x00\x00'
b'longq\x07K\x04uu.\x80\x02ctorch._utils\n_rebuild_tensor_v2'
b'\nq\x00((X\x07\x00\x00\x00storageq\x01ctorch\nFloatStorage'
b'\nq\x02X\x0e\x00\x00\x0094919395964320q\x03X\x06\x00\x00'
b'\x00cuda:0q\x04K\x02Ntq\x05QK\x00K\x02\x85q\x06K\x01\x85q'
b'\x07\x89Ntq\x08Rq\t.\x80\x02]q\x00X\x0e\x00\x00\x00'
b'94919395964320q\x01a.\x02\x00\x00\x00\x00\x00\x00\x00\xbb'
b'\x1f\x82\xbe\xea\x81\xd1>')
buf = io.BytesIO(serialized)
error_msg = r'Attempting to deserialize object on a CUDA device'
with self.assertRaisesRegex(RuntimeError, error_msg):
_ = torch.load(buf)
def test_serialization_filelike_api_requirements(self):
filemock = FilelikeMock(b'', has_readinto=False)
tensor = torch.randn(3, 5)
torch.save(tensor, filemock)
expected_superset = {'write', 'flush'}
self.assertTrue(expected_superset.issuperset(filemock.calls))
# Reset between save and load
filemock.seek(0)
filemock.calls.clear()
_ = torch.load(filemock)
expected_superset = {'read', 'readline', 'seek', 'tell'}
self.assertTrue(expected_superset.issuperset(filemock.calls))
def _test_serialization_filelike(self, tensor, mock, desc):
f = mock(b'')
torch.save(tensor, f)
f.seek(0)
data = mock(f.read())
msg = 'filelike serialization with {}'
b = torch.load(data)
self.assertTrue(torch.equal(tensor, b), msg.format(desc))
def test_serialization_filelike_missing_attrs(self):
# Test edge cases where filelike objects are missing attributes.
# The Python io docs suggests that these attributes should really exist
# and throw io.UnsupportedOperation, but that isn't always the case.
mocks = [
('no readinto', lambda x: FilelikeMock(x)),
('has readinto', lambda x: FilelikeMock(x, has_readinto=True)),
('no fileno', lambda x: FilelikeMock(x, has_fileno=False)),
]
to_serialize = torch.randn(3, 10)
for desc, mock in mocks:
self._test_serialization_filelike(to_serialize, mock, desc)
def test_serialization_filelike_stress(self):
a = torch.randn(11 * (2 ** 9) + 1, 5 * (2 ** 9))
# This one should call python read multiple times
self._test_serialization_filelike(a, lambda x: FilelikeMock(x, has_readinto=False),
'read() stress test')
self._test_serialization_filelike(a, lambda x: FilelikeMock(x, has_readinto=True),
'readinto() stress test')
def test_serialization_filelike_uses_readinto(self):
# For maximum efficiency, when reading a file-like object,
# ensure the C API calls readinto instead of read.
a = torch.randn(5, 4)
f = io.BytesIO()
torch.save(a, f)
f.seek(0)
data = FilelikeMock(f.read(), has_readinto=True)
b = torch.load(data)
self.assertTrue(data.was_called('readinto'))
def test_serialization_filelike_exceptions(self):
# Try to serialize to buffers that does not have write method
# Or have a malfrormed one, and make sure it does not cause an abort
# See https://github.com/pytorch/pytorch/issues/87997
x = torch.rand(10)
with self.assertRaises(AttributeError):
# Tries to serialize str into tensor
torch.save('foo', x)
x.write = "bar"
x.flush = "baz"
with self.assertRaises(TypeError):
# Tries to serialize str into tensor with write property
torch.save('foo', x)
x.write = str.__add__
x.flush = str.__mul__
with self.assertRaises(TypeError):
# Tries to serialize str into tensor with wrong callable write property
torch.save('foo', x)
s_data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
s = torch.CharStorage(s_data)
with self.assertRaises(AttributeError):
# Tries to serialize list into CharStorage
torch.save(s_data, s)
x = torch.randint(10, (3, 3), dtype=torch.float).cpu().numpy()
with self.assertRaises(AttributeError):
# Tries to serialize ndarray into ndarray
torch.save(x, x)
def test_serialization_storage_slice(self):
# Generated using:
#
# t = torch.zeros(2);
# s1 = t.storage()[:1]
# s2 = t.storage()[1:]
# torch.save((s1, s2), 'foo.ser')
#
# with PyTorch 0.3.1
serialized = (b'\x80\x02\x8a\nl\xfc\x9cF\xf9 j\xa8P\x19.\x80\x02M\xe9\x03'
b'.\x80\x02}q\x00(X\n\x00\x00\x00type_sizesq\x01}q\x02(X\x03'
b'\x00\x00\x00intq\x03K\x04X\x05\x00\x00\x00shortq\x04K\x02X'
b'\x04\x00\x00\x00longq\x05K\x04uX\x10\x00\x00\x00protocol_versionq'
b'\x06M\xe9\x03X\r\x00\x00\x00little_endianq\x07\x88u.\x80\x02'
b'(X\x07\x00\x00\x00storageq\x00ctorch\nFloatStorage\nq\x01X\x0e'
b'\x00\x00\x0094279043900432q\x02X\x03\x00\x00\x00cpuq\x03K\x02'
b'X\x0e\x00\x00\x0094279029750368q\x04K\x00K\x01\x87q\x05tq\x06'
b'Q(h\x00h\x01X\x0e\x00\x00\x0094279043900432q\x07h\x03K\x02X'
b'\x0e\x00\x00\x0094279029750432q\x08K\x01K\x01\x87q\ttq\nQ'
b'\x86q\x0b.\x80\x02]q\x00X\x0e\x00\x00\x0094279043900432q'
b'\x01a.\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00\x00\x00\x00')
buf = io.BytesIO(serialized)
(s1, s2) = torch.load(buf)
self.assertEqual(s1[0], 0)
self.assertEqual(s2[0], 0)
self.assertEqual(s1.data_ptr() + 4, s2.data_ptr())
def test_load_unicode_error_msg(self):
# This Pickle contains a Python 2 module with Unicode data and the
# loading should fail if the user explicitly specifies ascii encoding!
path = download_file('https://download.pytorch.org/test_data/legacy_conv2d.pt')
# weights_only=False as this is legacy code that saves the model
self.assertRaises(UnicodeDecodeError, lambda: torch.load(path, encoding='ascii', weights_only=False))
def test_load_python2_unicode_module(self):
# This Pickle contains some Unicode data!
path = download_file('https://download.pytorch.org/test_data/legacy_conv2d.pt')
with warnings.catch_warnings(record=True) as w:
# weights_only=False as this is legacy code that saves the model
self.assertIsNotNone(torch.load(path, weights_only=False))
def test_load_error_msg(self):
expected_err_msg = (".*You can only torch.load from a file that is seekable. " +
"Please pre-load the data into a buffer like io.BytesIO and " +
"try to load from it instead.")
resource = FilelikeMock(data=b"data")
delattr(resource, "tell")
delattr(resource, "seek")
with self.assertRaisesRegex(AttributeError, expected_err_msg):
# weights_only=False as this is legacy code that saves the model
torch.load(resource, weights_only=False)
def test_save_different_dtype_unallocated(self):
devices = ['cpu']
if torch.cuda.is_available():
devices.append('cuda')
def save_load_check(a, b):
with io.BytesIO() as f:
torch.save([a, b], f)
f.seek(0)
a_loaded, b_loaded = torch.load(f)
self.assertEqual(a, a_loaded)
self.assertEqual(b, b_loaded)
for device, dtype in product(devices, all_types_and_complex_and(torch.half,
torch.bfloat16, torch.bool)):
a = torch.tensor([], dtype=dtype, device=device)
for other_dtype in all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool):
s = torch.TypedStorage(
wrap_storage=a.storage().untyped(),
dtype=other_dtype)
save_load_check(a, s)
save_load_check(a.storage(), s)
b = torch.tensor([], dtype=other_dtype, device=device)
save_load_check(a, b)
def test_save_different_dtype_error(self):
error_msg = r"Cannot save multiple tensors or storages that view the same data as different types"
devices = ['cpu']
if torch.cuda.is_available():
devices.append('cuda')
for device in devices:
a = torch.randn(10, dtype=torch.complex128, device=device)
f = io.BytesIO()
with self.assertRaisesRegex(RuntimeError, error_msg):
torch.save([a, a.imag], f)
with self.assertRaisesRegex(RuntimeError, error_msg):
torch.save([a.storage(), a.imag], f)
with self.assertRaisesRegex(RuntimeError, error_msg):
torch.save([a, a.imag.storage()], f)
with self.assertRaisesRegex(RuntimeError, error_msg):
torch.save([a.storage(), a.imag.storage()], f)
a = torch.randn(10, device=device)
s_bytes = torch.TypedStorage(
wrap_storage=a.storage().untyped(),
dtype=torch.uint8)
with self.assertRaisesRegex(RuntimeError, error_msg):
torch.save([a, s_bytes], f)
with self.assertRaisesRegex(RuntimeError, error_msg):
torch.save([a.storage(), s_bytes], f)
def test_safe_load_basic_types(self):
with tempfile.NamedTemporaryFile() as f:
data = {"int": 123, "str": "world", "float": 3.14, "bool": False}
torch.save(data, f)
f.seek(0)
loaded_data = torch.load(f, weights_only=True)
self.assertEqual(data, loaded_data)
@unittest.skipIf(not IS_CI, "only check debug var is set in CI")
def test_debug_set_in_ci(self):
# This test is to make sure that the serialization debug flag is set in CI
self.assertTrue(os.environ.get("TORCH_SERIALIZATION_DEBUG", "0") == "1")
def test_skip_data_load(self):
t_device = "cuda" if torch.cuda.is_available() else "cpu"
t_v2 = torch.randn(2, 3, device=t_device)
tt = TwoTensor(torch.randn(2, device=t_device), torch.randn(2, device=t_device))
sd = {'t_v2': t_v2, 'tt': tt}
sd_zeroed = {
't_v2': torch.zeros(2, 3, device=t_device),
'tt': TwoTensor(torch.zeros(2, device=t_device), torch.zeros(2, device=t_device)),
}
with BytesIOContext() as f:
torch.save(sd, f)
f.seek(0)
with safe_globals([TwoTensor]), skip_data():
sd_loaded = torch.load(f)
self.assertNotEqual(sd_loaded, sd)
for k in sd_loaded:
sd_loaded[k] = sd_loaded[k].zero_()
self.assertEqual(sd_loaded, sd_zeroed)
| SerializationMixin |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/type_api.py | {
"start": 55830,
"end": 86057
} | class ____(SchemaEventTarget, ExternalType, TypeEngine[_T]):
'''Allows the creation of types which add additional functionality
to an existing type.
This method is preferred to direct subclassing of SQLAlchemy's
built-in types as it ensures that all required functionality of
the underlying type is kept in place.
Typical usage::
import sqlalchemy.types as types
class MyType(types.TypeDecorator):
"""Prefixes Unicode values with "PREFIX:" on the way in and
strips it off on the way out.
"""
impl = types.Unicode
cache_ok = True
def process_bind_param(self, value, dialect):
return "PREFIX:" + value
def process_result_value(self, value, dialect):
return value[7:]
def copy(self, **kw):
return MyType(self.impl.length)
The class-level ``impl`` attribute is required, and can reference any
:class:`.TypeEngine` class. Alternatively, the :meth:`load_dialect_impl`
method can be used to provide different type classes based on the dialect
given; in this case, the ``impl`` variable can reference
``TypeEngine`` as a placeholder.
The :attr:`.TypeDecorator.cache_ok` class-level flag indicates if this
custom :class:`.TypeDecorator` is safe to be used as part of a cache key.
This flag defaults to ``None`` which will initially generate a warning
when the SQL compiler attempts to generate a cache key for a statement
that uses this type. If the :class:`.TypeDecorator` is not guaranteed
to produce the same bind/result behavior and SQL generation
every time, this flag should be set to ``False``; otherwise if the
class produces the same behavior each time, it may be set to ``True``.
See :attr:`.TypeDecorator.cache_ok` for further notes on how this works.
Types that receive a Python type that isn't similar to the ultimate type
used may want to define the :meth:`TypeDecorator.coerce_compared_value`
method. This is used to give the expression system a hint when coercing
Python objects into bind parameters within expressions. Consider this
expression::
mytable.c.somecol + datetime.date(2009, 5, 15)
Above, if "somecol" is an ``Integer`` variant, it makes sense that
we're doing date arithmetic, where above is usually interpreted
by databases as adding a number of days to the given date.
The expression system does the right thing by not attempting to
coerce the "date()" value into an integer-oriented bind parameter.
However, in the case of ``TypeDecorator``, we are usually changing an
incoming Python type to something new - ``TypeDecorator`` by default will
"coerce" the non-typed side to be the same type as itself. Such as below,
we define an "epoch" type that stores a date value as an integer::
class MyEpochType(types.TypeDecorator):
impl = types.Integer
cache_ok = True
epoch = datetime.date(1970, 1, 1)
def process_bind_param(self, value, dialect):
return (value - self.epoch).days
def process_result_value(self, value, dialect):
return self.epoch + timedelta(days=value)
Our expression of ``somecol + date`` with the above type will coerce the
"date" on the right side to also be treated as ``MyEpochType``.
This behavior can be overridden via the
:meth:`~TypeDecorator.coerce_compared_value` method, which returns a type
that should be used for the value of the expression. Below we set it such
that an integer value will be treated as an ``Integer``, and any other
value is assumed to be a date and will be treated as a ``MyEpochType``::
def coerce_compared_value(self, op, value):
if isinstance(value, int):
return Integer()
else:
return self
.. warning::
Note that the **behavior of coerce_compared_value is not inherited
by default from that of the base type**.
If the :class:`.TypeDecorator` is augmenting a
type that requires special logic for certain types of operators,
this method **must** be overridden. A key example is when decorating
the :class:`_postgresql.JSON` and :class:`_postgresql.JSONB` types;
the default rules of :meth:`.TypeEngine.coerce_compared_value` should
be used in order to deal with operators like index operations::
from sqlalchemy import JSON
from sqlalchemy import TypeDecorator
class MyJsonType(TypeDecorator):
impl = JSON
cache_ok = True
def coerce_compared_value(self, op, value):
return self.impl.coerce_compared_value(op, value)
Without the above step, index operations such as ``mycol['foo']``
will cause the index value ``'foo'`` to be JSON encoded.
Similarly, when working with the :class:`.ARRAY` datatype, the
type coercion for index operations (e.g. ``mycol[5]``) is also
handled by :meth:`.TypeDecorator.coerce_compared_value`, where
again a simple override is sufficient unless special rules are needed
for particular operators::
from sqlalchemy import ARRAY
from sqlalchemy import TypeDecorator
class MyArrayType(TypeDecorator):
impl = ARRAY
cache_ok = True
def coerce_compared_value(self, op, value):
return self.impl.coerce_compared_value(op, value)
'''
__visit_name__ = "type_decorator"
_is_type_decorator = True
# this is that pattern I've used in a few places (Dialect.dbapi,
# Dialect.type_compiler) where the "cls.attr" is a class to make something,
# and "instance.attr" is an instance of that thing. It's such a nifty,
# great pattern, and there is zero chance Python typing tools will ever be
# OK with it. For TypeDecorator.impl, this is a highly public attribute so
# we really can't change its behavior without a major deprecation routine.
impl: Union[TypeEngine[Any], Type[TypeEngine[Any]]]
# we are changing its behavior *slightly*, which is that we now consume
# the instance level version from this memoized property instead, so you
# can't reassign "impl" on an existing TypeDecorator that's already been
# used (something one shouldn't do anyway) without also updating
# impl_instance.
@util.memoized_property
def impl_instance(self) -> TypeEngine[Any]:
return self.impl # type: ignore
def __init__(self, *args: Any, **kwargs: Any):
"""Construct a :class:`.TypeDecorator`.
Arguments sent here are passed to the constructor
of the class assigned to the ``impl`` class level attribute,
assuming the ``impl`` is a callable, and the resulting
object is assigned to the ``self.impl`` instance attribute
(thus overriding the class attribute of the same name).
If the class level ``impl`` is not a callable (the unusual case),
it will be assigned to the same instance attribute 'as-is',
ignoring those arguments passed to the constructor.
Subclasses can override this to customize the generation
of ``self.impl`` entirely.
"""
if not hasattr(self.__class__, "impl"):
raise AssertionError(
"TypeDecorator implementations "
"require a class-level variable "
"'impl' which refers to the class of "
"type being decorated"
)
self.impl = to_instance(self.__class__.impl, *args, **kwargs)
coerce_to_is_types: Sequence[Type[Any]] = (type(None),)
"""Specify those Python types which should be coerced at the expression
level to "IS <constant>" when compared using ``==`` (and same for
``IS NOT`` in conjunction with ``!=``).
For most SQLAlchemy types, this includes ``NoneType``, as well as
``bool``.
:class:`.TypeDecorator` modifies this list to only include ``NoneType``,
as typedecorator implementations that deal with boolean types are common.
Custom :class:`.TypeDecorator` classes can override this attribute to
return an empty tuple, in which case no values will be coerced to
constants.
"""
if not TYPE_CHECKING:
@property
def operator_classes(self) -> OperatorClass:
return self.impl_instance.operator_classes
class Comparator(TypeEngine.Comparator[_CT]):
"""A :class:`.TypeEngine.Comparator` that is specific to
:class:`.TypeDecorator`.
User-defined :class:`.TypeDecorator` classes should not typically
need to modify this.
"""
__slots__ = ()
def operate(
self, op: OperatorType, *other: Any, **kwargs: Any
) -> ColumnElement[_CT]:
if TYPE_CHECKING:
assert isinstance(self.expr.type, TypeDecorator)
kwargs["_python_is_types"] = self.expr.type.coerce_to_is_types
return super().operate(op, *other, **kwargs)
def reverse_operate(
self, op: OperatorType, other: Any, **kwargs: Any
) -> ColumnElement[_CT]:
if TYPE_CHECKING:
assert isinstance(self.expr.type, TypeDecorator)
kwargs["_python_is_types"] = self.expr.type.coerce_to_is_types
return super().reverse_operate(op, other, **kwargs)
@staticmethod
def _reduce_td_comparator(
impl: TypeEngine[Any], expr: ColumnElement[_T]
) -> Any:
return TypeDecorator._create_td_comparator_type(impl)(expr)
@staticmethod
def _create_td_comparator_type(
impl: TypeEngine[Any],
) -> _ComparatorFactory[Any]:
def __reduce__(self: TypeDecorator.Comparator[Any]) -> Any:
return (TypeDecorator._reduce_td_comparator, (impl, self.expr))
return type(
"TDComparator",
(TypeDecorator.Comparator, impl.comparator_factory), # type: ignore # noqa: E501
{"__reduce__": __reduce__},
)
@property
def comparator_factory( # type: ignore # mypy properties bug
self,
) -> _ComparatorFactory[Any]:
if TypeDecorator.Comparator in self.impl.comparator_factory.__mro__: # type: ignore # noqa: E501
return self.impl_instance.comparator_factory
else:
# reconcile the Comparator class on the impl with that
# of TypeDecorator.
# the use of multiple staticmethods is to support repeated
# pickling of the Comparator itself
return TypeDecorator._create_td_comparator_type(self.impl_instance)
def _copy_with_check(self) -> Self:
tt = self.copy()
if not isinstance(tt, self.__class__):
raise AssertionError(
"Type object %s does not properly "
"implement the copy() method, it must "
"return an object of type %s" % (self, self.__class__)
)
return tt
def _gen_dialect_impl(self, dialect: Dialect) -> TypeEngine[_T]:
if dialect.name in self._variant_mapping:
adapted = dialect.type_descriptor(
self._variant_mapping[dialect.name]
)
else:
adapted = dialect.type_descriptor(self)
if adapted is not self:
return adapted
# otherwise adapt the impl type, link
# to a copy of this TypeDecorator and return
# that.
typedesc = self.load_dialect_impl(dialect).dialect_impl(dialect)
tt = self._copy_with_check()
tt.impl = tt.impl_instance = typedesc
return tt
def _with_collation(self, collation: str) -> Self:
tt = self._copy_with_check()
tt.impl = tt.impl_instance = self.impl_instance._with_collation(
collation
)
return tt
@util.ro_non_memoized_property
def _type_affinity(self) -> Optional[Type[TypeEngine[Any]]]:
return self.impl_instance._type_affinity
def _set_parent(
self, parent: SchemaEventTarget, outer: bool = False, **kw: Any
) -> None:
"""Support SchemaEventTarget"""
super()._set_parent(parent)
if not outer and isinstance(self.impl_instance, SchemaEventTarget):
self.impl_instance._set_parent(parent, outer=False, **kw)
def _set_parent_with_dispatch(
self, parent: SchemaEventTarget, **kw: Any
) -> None:
"""Support SchemaEventTarget"""
super()._set_parent_with_dispatch(parent, outer=True, **kw)
if isinstance(self.impl_instance, SchemaEventTarget):
self.impl_instance._set_parent_with_dispatch(parent)
def type_engine(self, dialect: Dialect) -> TypeEngine[Any]:
"""Return a dialect-specific :class:`.TypeEngine` instance
for this :class:`.TypeDecorator`.
In most cases this returns a dialect-adapted form of
the :class:`.TypeEngine` type represented by ``self.impl``.
Makes usage of :meth:`dialect_impl`.
Behavior can be customized here by overriding
:meth:`load_dialect_impl`.
"""
adapted = dialect.type_descriptor(self)
if not isinstance(adapted, type(self)):
return adapted
else:
return self.load_dialect_impl(dialect)
def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
"""Return a :class:`.TypeEngine` object corresponding to a dialect.
This is an end-user override hook that can be used to provide
differing types depending on the given dialect. It is used
by the :class:`.TypeDecorator` implementation of :meth:`type_engine`
to help determine what type should ultimately be returned
for a given :class:`.TypeDecorator`.
By default returns ``self.impl``.
"""
return self.impl_instance
def _unwrapped_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
"""Return the 'unwrapped' dialect impl for this type.
This is used by the :meth:`.DefaultDialect.set_input_sizes`
method.
"""
# some dialects have a lookup for a TypeDecorator subclass directly.
# postgresql.INTERVAL being the main example
typ = self.dialect_impl(dialect)
# if we are still a type decorator, load the per-dialect switch
# (such as what Variant uses), then get the dialect impl for that.
if isinstance(typ, self.__class__):
return typ.load_dialect_impl(dialect).dialect_impl(dialect)
else:
return typ
def __getattr__(self, key: str) -> Any:
"""Proxy all other undefined accessors to the underlying
implementation."""
return getattr(self.impl_instance, key)
def process_literal_param(
self, value: Optional[_T], dialect: Dialect
) -> str:
"""Receive a literal parameter value to be rendered inline within
a statement.
.. note::
This method is called during the **SQL compilation** phase of a
statement, when rendering a SQL string. Unlike other SQL
compilation methods, it is passed a specific Python value to be
rendered as a string. However it should not be confused with the
:meth:`_types.TypeDecorator.process_bind_param` method, which is
the more typical method that processes the actual value passed to a
particular parameter at statement execution time.
Custom subclasses of :class:`_types.TypeDecorator` should override
this method to provide custom behaviors for incoming data values
that are in the special case of being rendered as literals.
The returned string will be rendered into the output string.
"""
raise NotImplementedError()
def process_bind_param(self, value: Optional[_T], dialect: Dialect) -> Any:
"""Receive a bound parameter value to be converted.
Custom subclasses of :class:`_types.TypeDecorator` should override
this method to provide custom behaviors for incoming data values.
This method is called at **statement execution time** and is passed
the literal Python data value which is to be associated with a bound
parameter in the statement.
The operation could be anything desired to perform custom
behavior, such as transforming or serializing data.
This could also be used as a hook for validating logic.
:param value: Data to operate upon, of any type expected by
this method in the subclass. Can be ``None``.
:param dialect: the :class:`.Dialect` in use.
.. seealso::
:ref:`types_typedecorator`
:meth:`_types.TypeDecorator.process_result_value`
"""
raise NotImplementedError()
def process_result_value(
self, value: Optional[Any], dialect: Dialect
) -> Optional[_T]:
"""Receive a result-row column value to be converted.
Custom subclasses of :class:`_types.TypeDecorator` should override
this method to provide custom behaviors for data values
being received in result rows coming from the database.
This method is called at **result fetching time** and is passed
the literal Python data value that's extracted from a database result
row.
The operation could be anything desired to perform custom
behavior, such as transforming or deserializing data.
:param value: Data to operate upon, of any type expected by
this method in the subclass. Can be ``None``.
:param dialect: the :class:`.Dialect` in use.
.. seealso::
:ref:`types_typedecorator`
:meth:`_types.TypeDecorator.process_bind_param`
"""
raise NotImplementedError()
@util.memoized_property
def _has_bind_processor(self) -> bool:
"""memoized boolean, check if process_bind_param is implemented.
Allows the base process_bind_param to raise
NotImplementedError without needing to test an expensive
exception throw.
"""
return util.method_is_overridden(
self, TypeDecorator.process_bind_param
)
@util.memoized_property
def _has_literal_processor(self) -> bool:
"""memoized boolean, check if process_literal_param is implemented."""
return util.method_is_overridden(
self, TypeDecorator.process_literal_param
)
def literal_processor(
self, dialect: Dialect
) -> Optional[_LiteralProcessorType[_T]]:
"""Provide a literal processing function for the given
:class:`.Dialect`.
This is the method that fulfills the :class:`.TypeEngine`
contract for literal value conversion which normally occurs via
the :meth:`_types.TypeEngine.literal_processor` method.
.. note::
User-defined subclasses of :class:`_types.TypeDecorator` should
**not** implement this method, and should instead implement
:meth:`_types.TypeDecorator.process_literal_param` so that the
"inner" processing provided by the implementing type is maintained.
"""
if self._has_literal_processor:
process_literal_param = self.process_literal_param
process_bind_param = None
elif self._has_bind_processor:
# use the bind processor if dont have a literal processor,
# but we have an impl literal processor
process_literal_param = None
process_bind_param = self.process_bind_param
else:
process_literal_param = None
process_bind_param = None
if process_literal_param is not None:
impl_processor = self.impl_instance.literal_processor(dialect)
if impl_processor:
fixed_impl_processor = impl_processor
fixed_process_literal_param = process_literal_param
def process(value: Any) -> str:
return fixed_impl_processor(
fixed_process_literal_param(value, dialect)
)
else:
fixed_process_literal_param = process_literal_param
def process(value: Any) -> str:
return fixed_process_literal_param(value, dialect)
return process
elif process_bind_param is not None:
impl_processor = self.impl_instance.literal_processor(dialect)
if not impl_processor:
return None
else:
fixed_impl_processor = impl_processor
fixed_process_bind_param = process_bind_param
def process(value: Any) -> str:
return fixed_impl_processor(
fixed_process_bind_param(value, dialect)
)
return process
else:
return self.impl_instance.literal_processor(dialect)
def bind_processor(
self, dialect: Dialect
) -> Optional[_BindProcessorType[_T]]:
"""Provide a bound value processing function for the
given :class:`.Dialect`.
This is the method that fulfills the :class:`.TypeEngine`
contract for bound value conversion which normally occurs via
the :meth:`_types.TypeEngine.bind_processor` method.
.. note::
User-defined subclasses of :class:`_types.TypeDecorator` should
**not** implement this method, and should instead implement
:meth:`_types.TypeDecorator.process_bind_param` so that the "inner"
processing provided by the implementing type is maintained.
:param dialect: Dialect instance in use.
"""
if self._has_bind_processor:
process_param = self.process_bind_param
impl_processor = self.impl_instance.bind_processor(dialect)
if impl_processor:
fixed_impl_processor = impl_processor
fixed_process_param = process_param
def process(value: Optional[_T]) -> Any:
return fixed_impl_processor(
fixed_process_param(value, dialect)
)
else:
fixed_process_param = process_param
def process(value: Optional[_T]) -> Any:
return fixed_process_param(value, dialect)
return process
else:
return self.impl_instance.bind_processor(dialect)
@util.memoized_property
def _has_result_processor(self) -> bool:
"""memoized boolean, check if process_result_value is implemented.
Allows the base process_result_value to raise
NotImplementedError without needing to test an expensive
exception throw.
"""
return util.method_is_overridden(
self, TypeDecorator.process_result_value
)
def result_processor(
self, dialect: Dialect, coltype: Any
) -> Optional[_ResultProcessorType[_T]]:
"""Provide a result value processing function for the given
:class:`.Dialect`.
This is the method that fulfills the :class:`.TypeEngine`
contract for bound value conversion which normally occurs via
the :meth:`_types.TypeEngine.result_processor` method.
.. note::
User-defined subclasses of :class:`_types.TypeDecorator` should
**not** implement this method, and should instead implement
:meth:`_types.TypeDecorator.process_result_value` so that the
"inner" processing provided by the implementing type is maintained.
:param dialect: Dialect instance in use.
:param coltype: A SQLAlchemy data type
"""
if self._has_result_processor:
process_value = self.process_result_value
impl_processor = self.impl_instance.result_processor(
dialect, coltype
)
if impl_processor:
fixed_process_value = process_value
fixed_impl_processor = impl_processor
def process(value: Any) -> Optional[_T]:
return fixed_process_value(
fixed_impl_processor(value), dialect
)
else:
fixed_process_value = process_value
def process(value: Any) -> Optional[_T]:
return fixed_process_value(value, dialect)
return process
else:
return self.impl_instance.result_processor(dialect, coltype)
@util.memoized_property
def _has_bind_expression(self) -> bool:
return (
util.method_is_overridden(self, TypeDecorator.bind_expression)
or self.impl_instance._has_bind_expression
)
def bind_expression(
self, bindparam: BindParameter[_T]
) -> Optional[ColumnElement[_T]]:
"""Given a bind value (i.e. a :class:`.BindParameter` instance),
return a SQL expression which will typically wrap the given parameter.
.. note::
This method is called during the **SQL compilation** phase of a
statement, when rendering a SQL string. It is **not** necessarily
called against specific values, and should not be confused with the
:meth:`_types.TypeDecorator.process_bind_param` method, which is
the more typical method that processes the actual value passed to a
particular parameter at statement execution time.
Subclasses of :class:`_types.TypeDecorator` can override this method
to provide custom bind expression behavior for the type. This
implementation will **replace** that of the underlying implementation
type.
"""
return self.impl_instance.bind_expression(bindparam)
@util.memoized_property
def _has_column_expression(self) -> bool:
"""memoized boolean, check if column_expression is implemented.
Allows the method to be skipped for the vast majority of expression
types that don't use this feature.
"""
return (
util.method_is_overridden(self, TypeDecorator.column_expression)
or self.impl_instance._has_column_expression
)
def column_expression(
self, column: ColumnElement[_T]
) -> Optional[ColumnElement[_T]]:
"""Given a SELECT column expression, return a wrapping SQL expression.
.. note::
This method is called during the **SQL compilation** phase of a
statement, when rendering a SQL string. It is **not** called
against specific values, and should not be confused with the
:meth:`_types.TypeDecorator.process_result_value` method, which is
the more typical method that processes the actual value returned
in a result row subsequent to statement execution time.
Subclasses of :class:`_types.TypeDecorator` can override this method
to provide custom column expression behavior for the type. This
implementation will **replace** that of the underlying implementation
type.
See the description of :meth:`_types.TypeEngine.column_expression`
for a complete description of the method's use.
"""
return self.impl_instance.column_expression(column)
def coerce_compared_value(
self, op: Optional[OperatorType], value: Any
) -> Any:
"""Suggest a type for a 'coerced' Python value in an expression.
By default, returns self. This method is called by
the expression system when an object using this type is
on the left or right side of an expression against a plain Python
object which does not yet have a SQLAlchemy type assigned::
expr = table.c.somecolumn + 35
Where above, if ``somecolumn`` uses this type, this method will
be called with the value ``operator.add``
and ``35``. The return value is whatever SQLAlchemy type should
be used for ``35`` for this particular operation.
"""
return self
def copy(self, **kw: Any) -> Self:
"""Produce a copy of this :class:`.TypeDecorator` instance.
This is a shallow copy and is provided to fulfill part of
the :class:`.TypeEngine` contract. It usually does not
need to be overridden unless the user-defined :class:`.TypeDecorator`
has local state that should be deep-copied.
"""
instance = self.__class__.__new__(self.__class__)
instance.__dict__.update(self.__dict__)
return instance
def get_dbapi_type(self, dbapi: DBAPIModule) -> Optional[Any]:
"""Return the DBAPI type object represented by this
:class:`.TypeDecorator`.
By default this calls upon :meth:`.TypeEngine.get_dbapi_type` of the
underlying "impl".
"""
return self.impl_instance.get_dbapi_type(dbapi)
def compare_values(self, x: Any, y: Any) -> bool:
"""Given two values, compare them for equality.
By default this calls upon :meth:`.TypeEngine.compare_values`
of the underlying "impl", which in turn usually
uses the Python equals operator ``==``.
This function is used by the ORM to compare
an original-loaded value with an intercepted
"changed" value, to determine if a net change
has occurred.
"""
return self.impl_instance.compare_values(x, y)
# mypy property bug
@property
def sort_key_function(self) -> Optional[Callable[[Any], Any]]: # type: ignore # noqa: E501
return self.impl_instance.sort_key_function
def __repr__(self) -> str:
return util.generic_repr(self, to_inspect=self.impl_instance)
| TypeDecorator |
python | ray-project__ray | doc/source/ray-core/doc_code/pattern_tree_of_actors.py | {
"start": 317,
"end": 899
} | class ____:
def __init__(self, hyperparameter, data):
self.trainers = [Trainer.remote(hyperparameter, d) for d in data]
def fit(self):
# Train with different data shard in parallel.
return ray.get([trainer.fit.remote() for trainer in self.trainers])
data = [1, 2, 3]
supervisor1 = Supervisor.remote(1, data)
supervisor2 = Supervisor.remote(2, data)
# Train with different hyperparameters in parallel.
model1 = supervisor1.fit.remote()
model2 = supervisor2.fit.remote()
assert ray.get(model1) == [1, 2, 3]
assert ray.get(model2) == [2, 4, 6]
| Supervisor |
python | tensorflow__tensorflow | tensorflow/dtensor/python/tests/collective_test.py | {
"start": 1654,
"end": 13481
} | class ____(test_util.DTensorBaseTest):
def setUp(self):
super(CollectiveTest, self).setUp()
global_ids = test_util.create_device_ids_array((2, 1))
local_ids = np.ravel(global_ids).tolist()
mesh_dict = {
device: layout_lib.Mesh(_MESH_DIMS, global_ids, local_ids,
test_util.create_device_list((2, 1), device))
for device in ('CPU', 'GPU', 'TPU')
}
self.mesh = self.configTestMesh(mesh_dict)
self.fully_replicated_layout_2d = Layout.replicated(self.mesh, rank=2)
self.first_dimension_sharded_layout_2d = Layout.batch_sharded(
self.mesh, _MESH_DIM_X, 2)
self.scalar_layout = Layout.replicated(self.mesh, rank=0)
def testReduceOnBfloat16(self):
self.skipForDeviceType(['GPU'],
'GPUs do not support bfloat16 collective reduce')
self.skipForDeviceType(['TPU'],
'This test only needs to run on 2 cores.',
unless_device_count_equals_to=2)
a = constant_op.constant(
np.array([[1, 2, 3, 4], [5.0, 6.0, 7.0, 8.0]]), dtype=dtypes.bfloat16)
expected_result = math_ops.reduce_sum(a)
sharded_a = api.relayout(a, self.first_dimension_sharded_layout_2d)
dtensor_result = math_ops.reduce_sum(sharded_a)
self.assertDTensorEqual(expected_result, self.scalar_layout, dtensor_result)
def testReduceOnInt32(self):
a = constant_op.constant(
np.array([[1, 2, 3, 4], [5, 6, 7, 8]]), dtype=dtypes.int32)
expected_result = math_ops.reduce_sum(a)
sharded_a = api.relayout(a, self.first_dimension_sharded_layout_2d)
dtensor_result = math_ops.reduce_sum(sharded_a)
self.assertDTensorEqual(expected_result, self.scalar_layout, dtensor_result)
def testReduceOnInt8(self):
a = constant_op.constant(
np.array([[1, 2, 3, 4], [5, 6, 7, 8]]), dtype=dtypes.int8
)
expected_result = math_ops.reduce_sum(a)
sharded_a = api.relayout(a, self.first_dimension_sharded_layout_2d)
dtensor_result = math_ops.reduce_sum(sharded_a)
self.assertDTensorEqual(expected_result, self.scalar_layout, dtensor_result)
def testTwoReducesWithAssign(self):
# FIXME(b/238384852): The purpose of this test is to validate the control
# dependency added by DTensor.
# However, as we have no way of testing the per-device graph
# produced by the DTensor SPMD expansion, we have to use manual logging
# to verify if the results are correct.
# For example, this test is used to check cl/459358521.
# Uses dtypes.float32 to avoid int32 problem with VarHandleOp on GPUs.
a = constant_op.constant(
np.array([[1, 2, 3, 4], [5, 6, 7, 8]]), dtype=dtypes.float32)
b = constant_op.constant(
np.array([[11, 12, 13, 4], [15, 16, 17, 18]]), dtype=dtypes.float32)
expected_result = math_ops.reduce_sum(a) * math_ops.reduce_sum(b)
sharded_a = api.relayout(a, self.first_dimension_sharded_layout_2d)
sharded_b = api.relayout(b, self.first_dimension_sharded_layout_2d)
sharded_v = d_variable.DVariable(sharded_b)
@polymorphic_function.function
def func(a, b):
a1 = math_ops.reduce_sum(a, name='reducea')
sharded_v.assign(a)
b1 = math_ops.reduce_sum(b, name='reduceb')
return a1 * b1
with api.default_mesh(self.mesh):
dtensor_result = func(sharded_a, sharded_b)
self.assertDTensorEqual(expected_result, self.scalar_layout, dtensor_result)
@parameterized.named_parameters(
('_all', math_ops.reduce_all),
('_any', math_ops.reduce_any),
)
def testReduceOnBool(self, reduction):
# TODO(b/193531363): Track the work to support int32 reduce.
self.skipForDeviceType(['GPU'],
'GPUs do not support int32 collective reduce')
self.skipForDeviceType(['TPU'],
'This test only needs to run on 2 cores.',
unless_device_count_equals_to=2)
a = constant_op.constant(
np.array([[True, False, False, True], [False, False, False, True]]),
dtype=dtypes.bool)
expected_result = reduction(a)
sharded_a = api.relayout(a, self.first_dimension_sharded_layout_2d)
dtensor_result = reduction(sharded_a)
self.assertDTensorEqual(expected_result, self.scalar_layout, dtensor_result)
def testAllToAllOnBool(self):
# TODO(b/193531363): Track the work to support int32 reduce.
self.skipForDeviceType(['GPU'],
'GPUs do not support int32 collective reduce')
self.skipForDeviceType(['TPU'],
'This test only needs to run on 2 cores.',
unless_device_count_equals_to=2)
a = constant_op.constant(
np.array([[True, False, False, True], [False, False, False, True]]),
dtype=dtypes.bool)
sharded_a = api.relayout(a, self.first_dimension_sharded_layout_2d)
unsharded_a = api.relayout(sharded_a, self.fully_replicated_layout_2d)
self.assertDTensorEqual(a, self.fully_replicated_layout_2d, unsharded_a)
def testAllToAllOnInt32(self):
# TODO(b/193471732): Tracking the work to do int32 all-concat.
#
# Currently, the test will fail with segfault.
self.skipForDeviceType(['GPU'],
'GPUs do not support int32 StridedSliceXXX Ops')
self.skipForDeviceType(['TPU'],
'This test only needs to run on 2 cores.',
unless_device_count_equals_to=2)
a = constant_op.constant(np.array([[1, 2], [3, 4]]), dtype=dtypes.int32)
sharded_a = api.relayout(a, self.first_dimension_sharded_layout_2d)
unsharded_a = api.relayout(sharded_a, self.fully_replicated_layout_2d)
self.assertDTensorEqual(a, self.fully_replicated_layout_2d, unsharded_a)
def testCollectiveOpsOnComplex64(self):
# This functions tests for AllScatter, AllGather, and AllReduce.
a = constant_op.constant(
np.array([[1, 2 + 2j], [3 + 1j, 4 + 5j]]), dtype=dtypes.complex64
)
# Tests AllScatter
sharded_a = api.relayout(a, self.first_dimension_sharded_layout_2d)
# Tests AllGather / AllReduce
unsharded_a = api.relayout(sharded_a, self.fully_replicated_layout_2d)
self.assertDTensorEqual(a, self.fully_replicated_layout_2d, unsharded_a)
def testCollectiveOpsOnComplex128(self):
# This function tests for AllScattering, AllReduce, and AllToAll.
self.skipForDeviceType(['TPU'], 'TPU does not support comolex128')
expected_layout = Layout.inner_sharded(self.mesh, 'x', rank=2)
initial_layout = Layout.batch_sharded(self.mesh, 'x', rank=2)
a = constant_op.constant(
np.array([[1, 2 + 2j], [3 + 1j, 4 + 5j]]), dtype=dtypes.complex128)
# Tests AllScatter
sharded_a_initial = api.relayout(a, initial_layout)
# Tests AllToAll / AllReduce
sharded_a = api.relayout(sharded_a_initial, expected_layout)
api.check_layout(sharded_a, expected_layout)
def testNoOpAllToAll(self):
self.skipForDeviceType(['TPU'],
'This test only needs to run on 2 cores.',
unless_device_count_equals_to=2)
a = constant_op.constant(
np.array([[1., 2., 3., 4.], [5.0, 6.0, 7.0, 8.0]]),
dtype=dtypes.float32)
expected_result = a
sharded_a = api.relayout(a, self.first_dimension_sharded_layout_2d)
dtensor_result = api.relayout(sharded_a, self.fully_replicated_layout_2d)
self.assertDTensorEqual(expected_result, self.fully_replicated_layout_2d,
dtensor_result)
# Regression test for b/184401449.
def testDeviceIdTensorOnSplitHost(self):
if not test_util.is_tpu_present():
self.skipTest('This test only runs on TPUs.')
self.skipForDeviceType(['TPU'],
'This test requires 8 TPU cores.',
unless_device_count_equals_to=8)
global_ids = test_util.create_device_ids_array((2, 4))
local_ids = [0, 1, 4, 5, 2, 3, 6, 7] # not sequentially increasing
mesh = layout_lib.Mesh(_MESH_DIMS, global_ids, local_ids,
test_util.create_device_list((2, 4), 'TPU'),
'tpu_mesh')
# This works because on 2x2, global device IDs are equal to physical TPU
# core IDs: both are range(8). So local device IDs happen to be usable here.
# TODO(b/180046115): Add a device.get_tpu_core_ids method and translate
# device IDs to core IDs before setting the list here.
device = dtensor_device.DTensorDevice(meshes=[mesh])
device.set_tpu_core_ids('tpu_mesh', local_ids)
layout_x = Layout.batch_sharded(mesh, _MESH_DIM_X, 2)
layout_y = Layout.batch_sharded(mesh, _MESH_DIM_Y, 2)
# Create a 2x4 batch-sharded d-tensor, with batch IDs in its first column
# and zeros in other columns.
replica_ids = constant_op.constant(
np.array([[0, 0, 0, 0], [1, 0, 0, 0]]), dtype=dtypes.int32
)
replica_ids = api.relayout(replica_ids, layout_x)
# Create a 4x4 y-sharded d-tensor filled with ones.
ones = constant_op.constant(
np.array([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]),
dtype=dtypes.int32,
)
ones = api.relayout(ones, layout_y)
# If `a` has a layout of [x, unsharded], and `b` has a layout of
# [y, unsharded], the matmul will slice `a` to [x, y], do a local matmul,
# and all-reduce to produce a final result with a layout of [x, unsharded].
#
# Because `a` only has non-zero values in its first column, local devices
# must be given a correct device ID tensor (as the first argument of every
# function) to produce correct `begin` values for slicing `a`.
#
# Although this function only contains a single op, running it in op-by-op
# mode doesn't produce the intended effect because the output of
# math_ops.matmul would have a layout of [y, unsharded] instead of
# [x, unsharded].
@polymorphic_function.function
def func(a, b):
return math_ops.matmul(a, b)
dtensor_result = func(replica_ids, ones)
# The correct result is a 2x4 batch-sharded d-tensor, with rows filled with
# batch IDs.
expected_result = [
constant_op.constant(
[loc[_MESH_DIM_X]] * 4, dtype=dtypes.int32, shape=[1, 4])
for loc in mesh.local_device_locations()
]
self.assertEqual(api.fetch_layout(dtensor_result), layout_x)
dtensor_result = [t.numpy() for t in api.unpack(dtensor_result)]
self.assertAllEqual(expected_result, dtensor_result)
def testDifferentShapesBetweenCalls(self):
self.skipForTfrt(
'b/269333905, TFRT cpu fails due to step_id not propagated.'
)
self.skipForDeviceType(
['TPU'],
'Known failure under TPU for legalization requires a static shape.',
)
# The error only happens across the batch, where the value of
# tf.unique are differnet.
def produce_data(inputs, label):
inputs = api.relayout(
inputs, Layout.batch_sharded(self.mesh, _MESH_DIM_X, 1)
)
label = api.relayout(
label, Layout.batch_sharded(self.mesh, _MESH_DIM_X, 1)
)
return inputs, label
@polymorphic_function.function
def train_fn(inputs, label):
inputs, indices = array_ops.unique(inputs)
return math_ops.unsorted_segment_sum(label, indices, len(inputs))
input1, label1 = produce_data([6, 0, 6, 0], [1, 2, 3, 4])
input2, label2 = produce_data([2, 1, 2, 0], [1, 2, 3, 4])
result1 = train_fn(input1, label1)
result2 = train_fn(input2, label2)
self.assertAllEqual(
result1.numpy(),
[
4,
6,
],
)
self.assertAllEqual(
result2.numpy(),
[
4,
2,
4,
],
)
| CollectiveTest |
python | pyparsing__pyparsing | pyparsing/core.py | {
"start": 215999,
"end": 222278
} | class ____(ParseElementEnhance):
"""
Token for skipping over all undefined text until the matched
expression is found.
:param expr: target expression marking the end of the data to be skipped
:param include: if ``True``, the target expression is also parsed
(the skipped text and target expression are returned
as a 2-element list) (default= ``False``).
:param ignore: (default= ``None``) used to define grammars
(typically quoted strings and comments)
that might contain false matches to the target expression
:param fail_on: (default= ``None``) define expressions that
are not allowed to be included in the skipped test;
if found before the target expression is found,
the :class:`SkipTo` is not a match
Example:
.. testcode::
report = '''
Outstanding Issues Report - 1 Jan 2000
# | Severity | Description | Days Open
-----+----------+-------------------------------------------+-----------
101 | Critical | Intermittent system crash | 6
94 | Cosmetic | Spelling error on Login ('log|n') | 14
79 | Minor | System slow when running too many reports | 47
'''
integer = Word(nums)
SEP = Suppress('|')
# use SkipTo to simply match everything up until the next SEP
# - ignore quoted strings, so that a '|' character inside a quoted string does not match
# - parse action will call token.strip() for each matched token, i.e., the description body
string_data = SkipTo(SEP, ignore=quoted_string)
string_data.set_parse_action(token_map(str.strip))
ticket_expr = (integer("issue_num") + SEP
+ string_data("sev") + SEP
+ string_data("desc") + SEP
+ integer("days_open"))
for tkt in ticket_expr.search_string(report):
print(tkt.dump())
prints:
.. testoutput::
['101', 'Critical', 'Intermittent system crash', '6']
- days_open: '6'
- desc: 'Intermittent system crash'
- issue_num: '101'
- sev: 'Critical'
['94', 'Cosmetic', "Spelling error on Login ('log|n')", '14']
- days_open: '14'
- desc: "Spelling error on Login ('log|n')"
- issue_num: '94'
- sev: 'Cosmetic'
['79', 'Minor', 'System slow when running too many reports', '47']
- days_open: '47'
- desc: 'System slow when running too many reports'
- issue_num: '79'
- sev: 'Minor'
"""
def __init__(
self,
other: Union[ParserElement, str],
include: bool = False,
ignore: typing.Optional[Union[ParserElement, str]] = None,
fail_on: typing.Optional[Union[ParserElement, str]] = None,
**kwargs,
) -> None:
failOn: typing.Optional[Union[ParserElement, str]] = deprecate_argument(
kwargs, "failOn", None
)
super().__init__(other)
failOn = failOn or fail_on
self.ignoreExpr = ignore
self._may_return_empty = True
self.mayIndexError = False
self.includeMatch = include
self.saveAsList = False
if isinstance(failOn, str_type):
self.failOn = self._literalStringClass(failOn)
else:
self.failOn = failOn
self.errmsg = f"No match found for {self.expr}"
self.ignorer = Empty().leave_whitespace()
self._update_ignorer()
def _update_ignorer(self):
# rebuild internal ignore expr from current ignore exprs and assigned ignoreExpr
self.ignorer.ignoreExprs.clear()
for e in self.expr.ignoreExprs:
self.ignorer.ignore(e)
if self.ignoreExpr:
self.ignorer.ignore(self.ignoreExpr)
def ignore(self, expr):
"""
Define expression to be ignored (e.g., comments) while doing pattern
matching; may be called repeatedly, to define multiple comment or other
ignorable patterns.
"""
super().ignore(expr)
self._update_ignorer()
def parseImpl(self, instring, loc, do_actions=True):
startloc = loc
instrlen = len(instring)
self_expr_parse = self.expr._parse
self_failOn_canParseNext = (
self.failOn.can_parse_next if self.failOn is not None else None
)
ignorer_try_parse = self.ignorer.try_parse if self.ignorer.ignoreExprs else None
tmploc = loc
while tmploc <= instrlen:
if self_failOn_canParseNext is not None:
# break if failOn expression matches
if self_failOn_canParseNext(instring, tmploc):
break
if ignorer_try_parse is not None:
# advance past ignore expressions
prev_tmploc = tmploc
while 1:
try:
tmploc = ignorer_try_parse(instring, tmploc)
except ParseBaseException:
break
# see if all ignorers matched, but didn't actually ignore anything
if tmploc == prev_tmploc:
break
prev_tmploc = tmploc
try:
self_expr_parse(instring, tmploc, do_actions=False, callPreParse=False)
except (ParseException, IndexError):
# no match, advance loc in string
tmploc += 1
else:
# matched skipto expr, done
break
else:
# ran off the end of the input string without matching skipto expr, fail
raise ParseException(instring, loc, self.errmsg, self)
# build up return values
loc = tmploc
skiptext = instring[startloc:loc]
skipresult = ParseResults(skiptext)
if self.includeMatch:
loc, mat = self_expr_parse(instring, loc, do_actions, callPreParse=False)
skipresult += mat
return loc, skipresult
| SkipTo |
python | gabrielfalcao__HTTPretty | httpretty/core.py | {
"start": 14323,
"end": 30862
} | class ____(object):
"""
fake :py:mod:`socket`
"""
class socket(object):
"""drop-in replacement for :py:class:`socket.socket`
"""
_entry = None
_read_buf = None
debuglevel = 0
_sent_data = []
is_secure = False
def __init__(
self,
family=socket.AF_INET,
type=socket.SOCK_STREAM,
proto=0,
fileno=None
):
self.socket_family = family
self.socket_type = type
self.socket_proto = proto
if httpretty.allow_net_connect:
self.truesock = self.create_socket()
else:
self.truesock = None
self._address = FakeAddressTuple(self)
self.__truesock_is_connected__ = False
self.fd = FakeSockFile()
self.fd.socket = fileno or self
self.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
self._sock = fileno or self
self.is_http = False
self._bufsize = 32 * 1024
def __repr__(self):
return '{self.__class__.__module__}.{self.__class__.__name__}("{self.host}")'.format(**locals())
@property
def host(self):
return ":".join(map(str, self._address))
def create_socket(self, address=None):
return old_socket(self.socket_family, self.socket_type, self.socket_proto)
def getpeercert(self, *a, **kw):
now = datetime.now()
shift = now + timedelta(days=30 * 12)
return {
'notAfter': shift.strftime('%b %d %H:%M:%S GMT'),
'subjectAltName': (
('DNS', '*.%s' % self._host),
('DNS', self._host),
('DNS', '*'),
),
'subject': (
(
('organizationName', '*.%s' % self._host),
),
(
('organizationalUnitName',
'Domain Control Validated'),
),
(
('commonName', '*.%s' % self._host),
),
),
}
def ssl(self, sock, *args, **kw):
return sock
def setsockopt(self, level, optname, value):
if httpretty.allow_net_connect and not self.truesock:
self.truesock = self.create_socket()
elif not self.truesock:
logger.debug('setsockopt(%s, %s, %s) failed', level, optname, value)
return
return self.truesock.setsockopt(level, optname, value)
def connect(self, address):
try:
self._address = (self._host, self._port) = address
except ValueError:
# We get here when the address is just a string pointing to a
# unix socket path/file
#
# See issue #206
self.is_http = False
else:
ports_to_check = (
POTENTIAL_HTTP_PORTS.union(POTENTIAL_HTTPS_PORTS))
self.is_http = self._port in ports_to_check
self.is_secure = self._port in POTENTIAL_HTTPS_PORTS
if not self.is_http:
self.connect_truesock(address=address)
elif self.truesock and not self.real_socket_is_connected():
# TODO: remove nested if
matcher = httpretty.match_http_address(self._host, self._port)
if matcher is None:
self.connect_truesock(address=address)
def bind(self, address):
self._address = (self._host, self._port) = address
if self.truesock:
self.bind_truesock(address)
def bind_truesock(self, address):
if httpretty.allow_net_connect and not self.truesock:
self.truesock = self.create_socket()
elif not self.truesock:
raise UnmockedError('Failed to socket.bind() because because a real socket was never created.', address=address)
return self.truesock.bind(address)
def connect_truesock(self, request=None, address=None):
address = address or self._address
if self.__truesock_is_connected__:
return self.truesock
if request:
logger.warning('real call to socket.connect() for {request}'.format(**locals()))
elif address:
logger.warning('real call to socket.connect() for {address}'.format(**locals()))
else:
logger.warning('real call to socket.connect()')
if httpretty.allow_net_connect and not self.truesock:
self.truesock = self.create_socket(address)
elif not self.truesock:
raise UnmockedError('Failed to socket.connect() because because a real socket was never created.', request=request, address=address)
undo_patch_socket()
try:
hostname = self._address[0]
port = 80
if len(self._address) == 2:
port = self._address[1]
if port == 443 and old_sslsocket:
self.truesock = old_ssl_wrap_socket(self.truesock, server_hostname=hostname)
sock = self.truesock
sock.connect(self._address)
self.__truesock_is_connected__ = True
self.truesock = sock
finally:
apply_patch_socket()
return self.truesock
def real_socket_is_connected(self):
return self.__truesock_is_connected__
def fileno(self):
if self.truesock:
return self.truesock.fileno()
return self.fd.fileno()
def close(self):
if self.truesock:
self.truesock.close()
self.truesock = None
self.__truesock_is_connected__ = False
def makefile(self, mode='r', bufsize=-1):
"""Returns this fake socket's own tempfile buffer.
If there is an entry associated with the socket, the file
descriptor gets filled in with the entry data before being
returned.
"""
self._mode = mode
self._bufsize = bufsize
if self._entry:
t = __internals__.create_thread(
target=self._entry.fill_filekind, args=(self.fd,)
)
# execute body callback and send http response in a
# thread, wait for thread to finish within the timeout
# set via socket.settimeout()
t.start()
if self.timeout == SOCKET_GLOBAL_DEFAULT_TIMEOUT:
timeout = get_default_thread_timeout()
else:
timeout = self.timeout
# fake socket timeout error by checking if the thread
# finished in time.
t.join(timeout)
if t.is_alive():
# For more info check issue https://github.com/gabrielfalcao/HTTPretty/issues/430
raise socket.timeout(timeout)
return self.fd
def real_sendall(self, data, *args, **kw):
"""Sends data to the remote server. This method is called
when HTTPretty identifies that someone is trying to send
non-http data.
The received bytes are written in this socket's tempfile
buffer so that HTTPretty can return it accordingly when
necessary.
"""
request = kw.pop('request', None)
if request:
bytecount = len(data)
logger.warning('{self}.real_sendall({bytecount} bytes) to {request.url} via {request.method} at {request.created_at}'.format(**locals()))
if httpretty.allow_net_connect and not self.truesock:
self.connect_truesock(request=request)
elif not self.truesock:
raise UnmockedError(request=request)
if not self.is_http:
self.truesock.setblocking(1)
return self.truesock.sendall(data, *args, **kw)
sock = self.connect_truesock(request=request)
sock.setblocking(1)
sock.sendall(data, *args, **kw)
should_continue = True
while should_continue:
try:
received = sock.recv(self._bufsize)
self.fd.write(received)
should_continue = bool(received.strip())
except socket.error as e:
if e.errno == EAGAIN:
continue
break
self.fd.seek(0)
def sendall(self, data, *args, **kw):
# if self.__truesock_is_connected__:
# return self.truesock.sendall(data, *args, **kw)
self._sent_data.append(data)
self.fd = FakeSockFile()
self.fd.socket = self
if isinstance(data, str):
data = data.encode('utf-8')
elif not isinstance(data, bytes):
logger.debug('cannot sendall({data!r})')
data = bytes(data)
try:
requestline, _ = data.split(b'\r\n', 1)
method, path, version = parse_requestline(
decode_utf8(requestline))
is_parsing_headers = True
except ValueError:
path = ''
is_parsing_headers = False
if self._entry is None:
# If the previous request wasn't mocked, don't
# mock the subsequent sending of data
return self.real_sendall(data, *args, **kw)
else:
method = self._entry.method
path = self._entry.info.path
self.fd.seek(0)
if not is_parsing_headers:
if len(self._sent_data) > 1:
headers = utf8(last_requestline(self._sent_data))
meta = self._entry.request.headers
body = utf8(self._sent_data[-1])
if meta.get('transfer-encoding', '') == 'chunked':
if not body.isdigit() and (body != b'\r\n') and (body != b'0\r\n\r\n'):
self._entry.request.body += body
else:
self._entry.request.body += body
httpretty.historify_request(headers, body, sock=self, append=False)
return
if path[:2] == '//':
path = '//' + path
# path might come with
s = urlsplit(path)
POTENTIAL_HTTP_PORTS.add(int(s.port or 80))
parts = list(map(utf8, data.split(b'\r\n\r\n', 1)))
if len(parts) == 2:
headers, body = parts
else:
headers = ''
body = data
request = httpretty.historify_request(headers, body, sock=self)
info = URIInfo(
hostname=self._host,
port=self._port,
path=s.path,
query=s.query,
last_request=request
)
matcher, entries = httpretty.match_uriinfo(info)
if not entries:
logger.debug('no entries matching {}'.format(request))
self._entry = None
self._read_buf = None
self.real_sendall(data, request=request)
return
self._entry = matcher.get_next_entry(method, info, request)
def forward_and_trace(self, function_name, *a, **kw):
if not self.truesock:
raise UnmockedError('Failed to socket.{}() because because a real socket was never created.'.format(function_name))
callback = getattr(self.truesock, function_name)
return callback(*a, **kw)
def settimeout(self, new_timeout):
self.timeout = new_timeout
if not self.is_http:
if self.truesock:
self.truesock.settimeout(new_timeout)
def send(self, data, *args, **kwargs):
self.sendall(data, *args, **kwargs)
return len(data)
def sendto(self, *args, **kwargs):
return self.forward_and_trace('sendto', *args, **kwargs)
def recvfrom_into(self, *args, **kwargs):
return self.forward_and_trace('recvfrom_into', *args, **kwargs)
def recv_into(self, *args, **kwargs):
return self.forward_and_trace('recv_into', *args, **kwargs)
def recvfrom(self, *args, **kwargs):
return self.forward_and_trace('recvfrom', *args, **kwargs)
def recv(self, buffersize=0, *args, **kwargs):
if not self._read_buf:
self._read_buf = io.BytesIO()
if self._entry:
self._entry.fill_filekind(self._read_buf)
if not self._read_buf:
raise UnmockedError('socket cannot recv(): {!r}'.format(self))
return self._read_buf.read(buffersize)
def __getattr__(self, name):
if name in ('getsockopt', 'selected_alpn_protocol') and not self.truesock:
self.truesock = self.create_socket()
elif httpretty.allow_net_connect and not self.truesock:
# can't call self.connect_truesock() here because we
# don't know if user wants to execute server of client
# calls (or can they?)
self.truesock = self.create_socket()
elif not self.truesock:
# Special case for
# `hasattr(sock, "version")` call added in urllib3>=1.26.
if name == 'version':
raise AttributeError(
"HTTPretty synthesized this error to fix urllib3 compatibility "
"(see issue https://github.com/gabrielfalcao/HTTPretty/issues/409). "
"Please open an issue if this error causes further unexpected issues."
)
raise UnmockedError('Failed to socket.{} because because a real socket does not exist'.format(name))
return getattr(self.truesock, name)
def with_socket_is_secure(sock, kw):
sock.is_secure = True
sock.kwargs = kw
for k, v in kw.items():
setattr(sock, k, v)
return sock
def fake_wrap_socket(orig_wrap_socket_fn, *args, **kw):
"""drop-in replacement for py:func:`ssl.wrap_socket`
"""
if 'sock' in kw:
sock = kw['sock']
else:
sock = args[0]
server_hostname = kw.get('server_hostname')
if server_hostname is not None:
matcher = httpretty.match_https_hostname(server_hostname)
if matcher is None:
logger.debug('no requests registered for hostname: "{}"'.format(server_hostname))
return with_socket_is_secure(sock, kw)
return with_socket_is_secure(sock, kw)
def create_fake_connection(
address,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None):
"""drop-in replacement for :py:func:`socket.create_connection`"""
s = fakesock.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
s.settimeout(timeout)
if isinstance(source_address, tuple) and len(source_address) == 2:
source_address[1] = int(source_address[1])
if source_address:
s.bind(source_address)
s.connect(address)
return s
def fake_gethostbyname(host):
"""drop-in replacement for :py:func:`socket.gethostbyname`"""
return '127.0.0.1'
def fake_gethostname():
"""drop-in replacement for :py:func:`socket.gethostname`"""
return 'localhost'
def fake_getaddrinfo(
host, port, family=None, socktype=None, proto=None, flags=None):
"""drop-in replacement for :py:func:`socket.getaddrinfo`"""
return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP,
'', (host, port)),
(socket.AF_INET6, socket.SOCK_STREAM, socket.IPPROTO_TCP,
'', (host, port))]
| fakesock |
python | PrefectHQ__prefect | src/prefect/server/schemas/actions.py | {
"start": 14837,
"end": 16347
} | class ____(ActionBaseModel):
"""Data used by the Prefect REST API to create a new state."""
type: schemas.states.StateType = Field(
default=..., description="The type of the state to create"
)
name: Optional[str] = Field(
default=None, description="The name of the state to create"
)
message: Optional[str] = Field(
default=None, description="The message of the state to create"
)
data: Optional[Any] = Field(
default=None, description="The data of the state to create"
)
state_details: schemas.states.StateDetails = Field(
default_factory=schemas.states.StateDetails,
description="The details of the state to create",
)
@model_validator(mode="after")
def default_name_from_type(self):
"""If a name is not provided, use the type"""
# if `type` is not in `values` it means the `type` didn't pass its own
# validation check and an error will be raised after this function is called
name = self.name
if name is None and self.type:
self.name = " ".join([v.capitalize() for v in self.type.value.split("_")])
return self
@model_validator(mode="after")
def default_scheduled_start_time(self):
from prefect.server.schemas.states import StateType
if self.type == StateType.SCHEDULED:
if not self.state_details.scheduled_time:
self.state_details.scheduled_time = now("UTC")
return self
| StateCreate |
python | run-llama__llama_index | llama-index-core/llama_index/core/output_parsers/selection.py | {
"start": 740,
"end": 808
} | class ____(DataClassJsonMixin):
choice: int
reason: str
| Answer |
python | altair-viz__altair | altair/vegalite/v6/schema/_config.py | {
"start": 303753,
"end": 310625
} | class ____(TypedDict, total=False):
"""
Top-Level Configuration ``TypedDict`` for creating a consistent theme.
Parameters
----------
align
The alignment to apply to grid rows and columns. The supported string values are
``"all"``, ``"each"``, and ``"none"``.
* For ``"none"``, a flow layout will be used, in which adjacent subviews are simply
placed one after the other.
* For ``"each"``, subviews will be aligned into a clean grid structure, but each row
or column may be of variable size.
* For ``"all"``, subviews will be aligned and each row or column will be sized
identically based on the maximum observed size. String values for this property
will be applied to both grid rows and columns.
Alternatively, an object value of the form ``{"row": string, "column": string}`` can
be used to supply different alignments for rows and columns.
**Default value:** ``"all"``.
autosize
How the visualization size should be determined. If a string, should be one of
``"pad"``, ``"fit"`` or ``"none"``. Object values can additionally specify
parameters for content sizing and automatic resizing.
**Default value**: ``pad``
background
CSS color property to use as the background of the entire view.
**Default value:** ``"white"``
bounds
The bounds calculation method to use for determining the extent of a sub-plot. One
of ``full`` (the default) or ``flush``.
* If set to ``full``, the entire calculated bounds (including axes, title, and
legend) will be used.
* If set to ``flush``, only the specified width and height values for the sub-view
will be used. The ``flush`` setting can be useful when attempting to place
sub-plots without axes or legends into a uniform grid structure.
**Default value:** ``"full"``
center
Boolean flag indicating if subviews should be centered relative to their respective
rows or columns.
An object value of the form ``{"row": boolean, "column": boolean}`` can be used to
supply different centering values for rows and columns.
**Default value:** ``false``
config
Vega-Lite configuration object. This property can only be defined at the top-level
of a specification.
description
Description of this mark for commenting purpose.
height
The height of a visualization.
* For a plot with a continuous y-field, height should be a number.
* For a plot with either a discrete y-field or no y-field, height can be either a
number indicating a fixed height or an object in the form of ``{step: number}``
defining the height per discrete step. (No y-field is equivalent to having one
discrete step.)
* To enable responsive sizing on height, it should be set to ``"container"``.
**Default value:** Based on ``config.view.continuousHeight`` for a plot with a
continuous y-field and ``config.view.discreteHeight`` otherwise.
**Note:** For plots with `row and column channels
<https://vega.github.io/vega-lite/docs/encoding.html#facet>`__, this represents the
height of a single view and the ``"container"`` option cannot be used.
**See also:** `height <https://vega.github.io/vega-lite/docs/size.html>`__
documentation.
name
Name of the visualization for later reference.
padding
The default visualization padding, in pixels, from the edge of the visualization
canvas to the data rectangle. If a number, specifies padding for all sides. If an
object, the value should have the format ``{"left": 5, "top": 5, "right": 5,
"bottom": 5}`` to specify padding for each side of the visualization.
**Default value**: ``5``
params
An array of parameters that may either be simple variables, or more complex
selections that map user input to data queries.
projection
An object defining properties of geographic projection, which will be applied to
``shape`` path for ``"geoshape"`` marks and to ``latitude`` and ``"longitude"``
channels for other marks.
resolve
Scale, axis, and legend resolutions for view composition specifications.
spacing
The spacing in pixels between sub-views of the composition operator. An object of
the form ``{"row": number, "column": number}`` can be used to set different spacing
values for rows and columns.
**Default value**: Depends on ``"spacing"`` property of `the view composition
configuration <https://vega.github.io/vega-lite/docs/config.html#view-config>`__
(``20`` by default)
title
Title for the plot.
usermeta
Optional metadata that will be passed to Vega. This object is completely ignored by
Vega and Vega-Lite and can be used for custom metadata.
view
An object defining the view background's fill and stroke.
**Default value:** none (transparent)
width
The width of a visualization.
* For a plot with a continuous x-field, width should be a number.
* For a plot with either a discrete x-field or no x-field, width can be either a
number indicating a fixed width or an object in the form of ``{step: number}``
defining the width per discrete step. (No x-field is equivalent to having one
discrete step.)
* To enable responsive sizing on width, it should be set to ``"container"``.
**Default value:** Based on ``config.view.continuousWidth`` for a plot with a
continuous x-field and ``config.view.discreteWidth`` otherwise.
**Note:** For plots with `row and column channels
<https://vega.github.io/vega-lite/docs/encoding.html#facet>`__, this represents the
width of a single view and the ``"container"`` option cannot be used.
**See also:** `width <https://vega.github.io/vega-lite/docs/size.html>`__
documentation.
"""
align: RowColKwds[LayoutAlign_T] | LayoutAlign_T
autosize: AutoSizeParamsKwds | AutosizeType_T
background: ColorHex | ColorName_T
bounds: Literal["full", "flush"]
center: bool | RowColKwds[bool]
config: ConfigKwds
description: str
height: float | StepKwds | Literal["container"]
name: str
padding: float | PaddingKwds
params: Sequence[VariableParameterKwds | TopLevelSelectionParameterKwds]
projection: ProjectionKwds
resolve: ResolveKwds
spacing: float | RowColKwds[float]
title: str | Sequence[str] | TitleParamsKwds
usermeta: Map
view: ViewBackgroundKwds
width: float | StepKwds | Literal["container"]
| ThemeConfig |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_image48.py | {
"start": 315,
"end": 955
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("image48.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(self.got_filename)
worksheet1 = workbook.add_worksheet()
worksheet2 = workbook.add_worksheet()
worksheet1.insert_image("E9", self.image_dir + "red.png")
worksheet2.insert_image("E9", self.image_dir + "red.png")
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | walkccc__LeetCode | solutions/782. Transform to Chessboard/782.py | {
"start": 0,
"end": 843
} | class ____:
def movesToChessboard(self, board: list[list[int]]) -> int:
n = len(board)
if any(board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j]
for i in range(n) for j in range(n)):
return -1
rowSum = sum(board[0])
colSum = sum(board[i][0] for i in range(n))
if rowSum != n // 2 and rowSum != (n + 1) // 2:
return -1
if colSum != n // 2 and colSum != (n + 1) // 2:
return -1
rowSwaps = sum(board[i][0] == (i & 1) for i in range(n))
colSwaps = sum(board[0][i] == (i & 1) for i in range(n))
if n % 2 == 1:
if rowSwaps % 2 == 1:
rowSwaps = n - rowSwaps
if colSwaps % 2 == 1:
colSwaps = n - colSwaps
else:
rowSwaps = min(rowSwaps, n - rowSwaps)
colSwaps = min(colSwaps, n - colSwaps)
return (rowSwaps + colSwaps) // 2
| Solution |
python | pytorch__pytorch | torch/fx/graph_module.py | {
"start": 15931,
"end": 45812
} | class ____(torch.nn.Module):
"""
GraphModule is an nn.Module generated from an fx.Graph. Graphmodule has a
``graph`` attribute, as well as ``code`` and ``forward`` attributes generated
from that ``graph``.
.. warning::
When ``graph`` is reassigned, ``code`` and ``forward`` will be automatically
regenerated. However, if you edit the contents of the ``graph`` without reassigning
the ``graph`` attribute itself, you must call ``recompile()`` to update the generated
code.
"""
def __new__(cls: "type[GraphModule]", *args, **kwargs):
# each instance of a graph module needs its own forward method
# so create a new singleton class for each instance.
# it is a subclass of the user-defined class, the only difference
# is an extra layer to install the forward method
# address issue described at https://github.com/pytorch/pytorch/issues/63883
# in other words, traverse class hierarchy to fix the redundant class definition problem
for t in cls.__mro__:
c = t.__qualname__.split(".")[-1]
if c != "GraphModuleImpl":
cls = t
break
class GraphModuleImpl(cls): # type: ignore[misc, valid-type]
pass
return super().__new__(GraphModuleImpl)
@compatibility(is_backward_compatible=True)
def __init__(
self,
root: Union[torch.nn.Module, dict[str, Any]],
graph: Graph,
class_name: str = "GraphModule",
):
"""
Construct a GraphModule.
Args:
root (Union[torch.nn.Module, Dict[str, Any]):
``root`` can either be an nn.Module instance or a Dict mapping strings to any attribute type.
In the case that ``root`` is a Module, any references to Module-based objects (via qualified
name) in the Graph's Nodes' ``target`` field will be copied over from the respective place
within ``root``'s Module hierarchy into the GraphModule's module hierarchy.
In the case that ``root`` is a dict, the qualified name found in a Node's ``target`` will be
looked up directly in the dict's keys. The object mapped to by the Dict will be copied
over into the appropriate place within the GraphModule's module hierarchy.
graph (Graph): ``graph`` contains the nodes this GraphModule should use for code generation
class_name (str): ``name`` denotes the name of this GraphModule for debugging purposes. If it's unset, all
error messages will report as originating from ``GraphModule``. It may be helpful to set this
to ``root``'s original name or a name that makes sense within the context of your transform.
"""
super().__init__()
self.__class__.__name__ = class_name
if isinstance(root, torch.nn.Module):
if hasattr(root, "training"):
self.training = root.training
# When we pickle/unpickle graph module, we don't want to drop any module or attributes.
if isinstance(root, _CodeOnlyModule):
for k, _ in root.named_children():
_copy_attr(root, self, k)
for k, _ in root.named_buffers():
_copy_attr(root, self, k)
for k, _ in root.named_parameters():
_copy_attr(root, self, k)
for node in graph.nodes:
if node.op in ["get_attr", "call_module"]:
assert isinstance(node.target, str)
_copy_attr(root, self, node.target)
elif isinstance(root, dict):
targets_to_copy = []
for node in graph.nodes:
if node.op in ["get_attr", "call_module"]:
assert isinstance(node.target, str)
if node.target not in root:
raise RuntimeError(
"Node "
+ str(node)
+ " referenced target "
+ node.target
+ " but that target was not provided in ``root``!"
)
targets_to_copy.append(node.target)
# Sort targets in ascending order of the # of atoms.
# This will ensure that less deeply nested attributes are assigned
# before more deeply nested attributes. For example, foo.bar
# will be assigned before foo.bar.baz. Otherwise, we might assign
# the user-provided ``foo.bar`` and wipe out the previously-assigned
# ``foo.bar.baz``
targets_to_copy.sort(key=lambda t: t.count("."))
for target_to_copy in targets_to_copy:
_assign_attr(root[target_to_copy], self, target_to_copy)
else:
raise RuntimeError("Unsupported type " + str(root) + " passed for root!")
self.graph = graph
# Store the Tracer class responsible for creating a Graph separately as part of the
# GraphModule state, except when the Tracer is defined in a local namespace.
# Locally defined Tracers are not pickleable. This is needed because torch.package will
# serialize a GraphModule without retaining the Graph, and needs to use the correct Tracer
# to re-create the Graph during deserialization.
self._tracer_cls = None
if (
self.graph._tracer_cls
and "<locals>" not in self.graph._tracer_cls.__qualname__
):
# pyrefly: ignore [bad-assignment]
self._tracer_cls = self.graph._tracer_cls
self._tracer_extras = {}
if self.graph._tracer_extras:
self._tracer_extras = self.graph._tracer_extras
# Dictionary to store metadata
self.meta: dict[str, Any] = {}
self._replace_hooks: list[Callable] = []
self._create_node_hooks: list[Callable] = []
self._erase_node_hooks: list[Callable] = []
# Used to remove hooks from deepcopied graph modules within a context manager.
self._deepcopy_hooks: list[Callable] = []
self.shape_env = None # optional not always set even when dynamic shapes exist.
# TorchScript breaks trying to compile the graph setter because of the
# continued string literal. Issue here: https://github.com/pytorch/pytorch/issues/44842
#
# Shouldn't be an issue since these methods shouldn't be used in TorchScript anyway
__jit_unused_properties__ = ["graph", "_boxed_call"]
@property
def _boxed_call(self) -> bool:
return isinstance(self._graph._codegen, _BoxedCodeGen)
@property
def graph(self) -> Graph:
"""
Return the ``Graph`` underlying this ``GraphModule``
"""
return self._graph
@graph.setter
def graph(self, g: Graph) -> None:
"""
Set the underlying ``Graph`` for this ``GraphModule``. This will internally
recompile the ``GraphModule`` so that the generated ``forward()`` function
corresponds to ``g``
"""
assert isinstance(g, Graph), f"Expected a Graph instance, but got {type(g)}"
self._graph = g
g.owning_module = self
self.recompile()
@compatibility(is_backward_compatible=False)
def to_folder(self, folder: Union[str, os.PathLike], module_name: str = "FxModule"):
"""Dumps out module to ``folder`` with ``module_name`` so that it can be
imported with ``from <folder> import <module_name>``
Args:
folder (Union[str, os.PathLike]): The folder to write the code out to
module_name (str): Top-level name to use for the ``Module`` while
writing out the code
"""
folder = Path(folder)
Path(folder).mkdir(exist_ok=True)
torch.save(self.state_dict(), folder / "state_dict.pt")
tab = " " * 4
custom_builtins = "\n".join([v.import_str for v in _custom_builtins.values()])
model_str = f"""
import torch
{custom_builtins}
from torch.nn import *
class {module_name}(torch.nn.Module):
def __init__(self):
super().__init__()
"""
def _gen_model_repr(module_name: str, module: torch.nn.Module) -> Optional[str]:
safe_reprs = [
nn.Linear,
nn.Conv1d,
nn.Conv2d,
nn.Conv3d,
nn.BatchNorm1d,
nn.BatchNorm2d,
nn.BatchNorm3d,
]
if type(module) in safe_reprs:
return f"{module.__repr__()}"
else:
return None
blobified_modules = []
for module_name, module in self.named_children():
module_str = _gen_model_repr(module_name, module)
if module_str is None:
module_file = folder / f"{module_name}.pt"
torch.save(module, module_file)
blobified_modules.append(module_name)
module_repr = module.__repr__().replace("\r", " ").replace("\n", " ")
# weights_only=False as this is legacy code that saves the model
module_str = (
f"torch.load(r'{module_file}', weights_only=False) # {module_repr}"
)
model_str += f"{tab * 2}self.{module_name} = {module_str}\n"
for buffer_name, buffer in self._buffers.items():
if buffer is None:
continue
model_str += f"{tab * 2}self.register_buffer('{buffer_name}', torch.empty({list(buffer.shape)}, dtype={buffer.dtype}))\n" # noqa: B950
for param_name, param in self._parameters.items():
if param is None:
continue
model_str += f"{tab * 2}self.{param_name} = torch.nn.Parameter(torch.empty({list(param.shape)}, dtype={param.dtype}))\n" # noqa: B950
model_str += (
f"{tab * 2}self.load_state_dict(torch.load(r'{folder}/state_dict.pt'))\n"
)
model_str += f"{_addindent(self.code, 4)}\n"
module_file = folder / "module.py"
module_file.write_text(model_str)
init_file = folder / "__init__.py"
init_file.write_text("from .module import *")
if len(blobified_modules) > 0:
warnings.warn(
"Was not able to save the following children modules as reprs -"
f"saved as pickled files instead: {blobified_modules}"
)
@compatibility(is_backward_compatible=True)
def add_submodule(self, target: str, m: torch.nn.Module) -> bool:
"""
Adds the given submodule to ``self``.
This installs empty Modules where none exist yet if they are
subpaths of ``target``.
Args:
target: The fully-qualified string name of the new submodule
(See example in ``nn.Module.get_submodule`` for how to
specify a fully-qualified string.)
m: The submodule itself; the actual object we want to
install in the current Module
Return:
bool: Whether or not the submodule could be inserted. For
this method to return True, each object in the chain
denoted by ``target`` must either a) not exist yet,
or b) reference an ``nn.Module`` (not a parameter or
other attribute)
"""
*prefix, field = target.split(".")
mod: torch.nn.Module = self
for item in prefix:
submod = getattr(mod, item, None)
if submod is None:
submod = torch.nn.Module()
setattr(mod, item, submod)
if not isinstance(submod, torch.nn.Module):
return False
mod = submod
mod.add_module(field, m)
return True
@compatibility(is_backward_compatible=True)
def delete_submodule(self, target: str) -> bool:
"""
Deletes the given submodule from ``self``.
The module will not be deleted if ``target`` is not a valid
target.
Args:
target: The fully-qualified string name of the new submodule
(See example in ``nn.Module.get_submodule`` for how to
specify a fully-qualified string.)
Returns:
bool: Whether or not the target string referenced a
submodule we want to delete. A return value of ``False``
means that the ``target`` was not a valid reference to
a submodule.
"""
atoms = target.split(".")
path, target_submod = atoms[:-1], atoms[-1]
mod: torch.nn.Module = self
# Get the parent module
for item in path:
if not hasattr(mod, item):
return False
mod = getattr(mod, item)
if not isinstance(mod, torch.nn.Module):
return False
if not hasattr(mod, target_submod):
return False
if not isinstance(getattr(mod, target_submod), torch.nn.Module):
return False
delattr(mod, target_submod)
return True
@compatibility(is_backward_compatible=True)
def delete_all_unused_submodules(self) -> None:
"""
Deletes all unused submodules from ``self``.
A Module is considered "used" if any one of the following is
true:
1. It has children that are used
2. Its forward is called directly via a ``call_module`` node
3. It has a non-Module attribute that is used from a
``get_attr`` node
This method can be called to clean up an ``nn.Module`` without
manually calling ``delete_submodule`` on each unused submodule.
"""
used: list[str] = []
for node in self.graph.nodes:
if node.op == "call_module" or node.op == "get_attr":
# A list of strings representing the different parts
# of the path. For example, `foo.bar.baz` gives us
# ["foo", "bar", "baz"]
fullpath = node.target.split(".")
# If we're looking at multiple parts of a path, join
# join them with a dot. Otherwise, return that single
# element without doing anything to it.
def join_fn(x: str, y: str) -> str:
return ".".join([x, y] if y else [x])
# Progressively collect all the names of intermediate
# modules. For example, if we have the target
# `foo.bar.baz`, we'll add `foo`, `foo.bar`, and
# `foo.bar.baz` to the list.
used.extend(itertools.accumulate(fullpath, join_fn))
# For a `call_module` node, also register all recursive submodules
# as used
if node.op == "call_module":
try:
submod = self.get_submodule(node.target)
for submod_name, _ in submod.named_modules():
if submod_name != "":
used.append(".".join([node.target, submod_name]))
except AttributeError:
# Node referenced nonexistent submodule, don't need to
# worry about GCing anything
pass
to_delete = [name for name, _ in self.named_modules() if name not in used]
for name in to_delete:
self.delete_submodule(name)
@property
def code(self) -> str:
"""
Return the Python code generated from the ``Graph`` underlying this
``GraphModule``.
"""
if not hasattr(self, "_code"):
raise RuntimeError(
"Code has not been generated! Please report a bug to PyTorch"
)
return self._code
@compatibility(is_backward_compatible=True)
def recompile(self) -> PythonCode:
"""
Recompile this GraphModule from its ``graph`` attribute. This should be
called after editing the contained ``graph``, otherwise the generated
code of this ``GraphModule`` will be out of date.
"""
# Do not import anything inside recompile, it might slow down the
# function and cause perf regression. Import outside of the method instead.
if isinstance(self._graph._codegen, _PyTreeCodeGen):
self._in_spec = self._graph._codegen.pytree_info.in_spec
self._out_spec = self._graph._codegen.pytree_info.out_spec
python_code = self._graph.python_code(
root_module="self",
record_func=fx_experimental_config.enrich_profiler_metadata,
)
self._code = python_code.src
self._lineno_map = python_code._lineno_map
self._prologue_start = python_code._prologue_start
cls = type(self)
co_fields = self._graph._co_fields if hasattr(self._graph, "_co_fields") else {}
if fx_experimental_config.enrich_profiler_metadata:
# Generate metadata and register for profiler augmentation
node_metadata: dict[int, dict[str, Any]] = {}
for i, node in enumerate(self._graph.nodes):
node_metadata[i] = {
"name": node.name,
"op": node.op,
"target": str(node.target),
"stack_trace": node.meta.get("stack_trace", None),
}
# Generate a content-addressed filename based on hash of code and metadata
# This ensures the same code+metadata always generates the same filename
hash_value = _metadata_hash(self._code, node_metadata)
file_stem = f"{FX_GRAPH_MODULE_FILE_PREFIX}_{hash_value}"
filename = f"{file_stem}.py"
# Only include co_filename to use it directly as the cache key
co_fields = {
"co_filename": filename,
}
# Store metadata in global in-memory registry
metadata = {
"lineno_map": python_code._lineno_map,
"prologue_start": python_code._prologue_start,
"node_metadata": node_metadata,
}
# Register metadata in the global registry
from torch.fx.traceback import _register_fx_metadata
_register_fx_metadata(filename, metadata)
# Replace the placeholder in generated code with actual filename
# The double hash ## convention is used by post-processing to find the fx markers
self._code = self._code.replace(
"torch._C._profiler._RecordFunctionFast('## ENTER_GRAPH_PLACEHOLDER_KEY ##')",
f"torch._C._profiler._RecordFunctionFast('## {filename} ##')",
)
cls.forward = _forward_from_src(self._code, python_code.globals, co_fields)
# Determine whether this class explicitly defines a __call__ implementation
# to wrap. If it does, save it in order to have wrapped_call invoke it.
# If it does not, wrapped_call can use a dynamic call to super() instead.
# In most cases, super().__call__ should be torch.nn.Module.__call__.
# We do not want to hold a reference to Module.__call__ here; doing so will
# bypass patching of torch.nn.Module.__call__ done while symbolic tracing.
cls_call = cls.__call__ if "__call__" in vars(cls) else None
if "_wrapped_call" not in vars(cls):
cls._wrapped_call = _WrappedCall(cls, cls_call) # type: ignore[attr-defined]
self._recompile_submodules()
def call_wrapped(self, *args, **kwargs):
return self._wrapped_call(self, *args, **kwargs)
cls.__call__ = call_wrapped # type: ignore[method-assign]
return python_code
def _recompile_submodules(self) -> list[tuple[str, PythonCode]]:
"""
Recompile all submodules of this graph module, returning their respective PythonCodes
in a similar format to named_children()
"""
results: list[tuple[str, PythonCode]] = []
for name, mod in self.named_children():
if isinstance(mod, GraphModule):
results.append((name, mod.recompile()))
return results
# Passing Tracer as argument allows subclasses extending fx.GraphModule
# define their own Tracer (extending fx.Tracer).
def __reduce_package__(self, exporter: PackageExporter):
dict_without_graph = self.__dict__.copy()
dict_without_graph["_graphmodule_cls_name"] = self.__class__.__name__
del dict_without_graph["_graph"]
# Store node.meta["stack_trace"] so we can recover them after re-tracing during deserialization
node_meta_stack_trace = {
node.name: node.meta["stack_trace"]
for node in self.graph.nodes
if "stack_trace" in node.meta
}
dict_without_graph["_graphmodule_graph_node_meta_stack_trace"] = (
node_meta_stack_trace
)
generated_module_name = f"fx-generated._{exporter.get_unique_id()}"
python_code = self.recompile()
import_block = _format_import_block(python_code.globals, exporter.importer)
module_code = import_block + self.code
exporter.save_source_string(generated_module_name, module_code)
return (
reduce_package_graph_module,
(dict_without_graph, generated_module_name),
)
def __reduce__(self):
"""
Serialization of GraphModule. We serialize only the generated code, not
the underlying ``Graph``. This is because ``Graph`` does not have on-disk
backward-compatibility guarantees, whereas Python source code does.
On the deserialization side, we symbolically trace through the generated
code to regenerate the underlying ``Graph``
"""
dict_without_graph = self.__dict__.copy()
python_code = self.recompile()
import_block = _format_import_block(python_code.globals, sys_importer)
del dict_without_graph["_graph"]
return (reduce_graph_module, (dict_without_graph, import_block))
def _deepcopy_init(self):
return GraphModule.__init__
# because __reduce__ is defined for serialization,
# we need to define deepcopy otherwise it will call __reduce__
# and cause symbolic tracing to occur every time we try to copy the object
def __deepcopy__(self, memo):
res = type(self).__new__(type(self))
memo[id(self)] = res
fake_mod = _CodeOnlyModule(copy.deepcopy(self.__dict__, memo))
self._deepcopy_init()(res, fake_mod, fake_mod.__dict__["_graph"])
# hooks are lost during `GraphModule.__init__`, so we need to copy over
# them explicitly, note right now we are only copying state_dict related
# hooks, to reduce bc-related issues, we can copy forward/backward related
# hooks in the future as well if needed
extra_preserved_attrs = [
"_state_dict_hooks",
"_load_state_dict_pre_hooks",
"_load_state_dict_post_hooks",
"_replace_hooks",
"_create_node_hooks",
"_erase_node_hooks",
"_deepcopy_hooks",
]
for attr in extra_preserved_attrs:
if attr in self.__dict__:
setattr(res, attr, copy.deepcopy(self.__dict__[attr], memo))
res.meta = copy.deepcopy(getattr(self, "meta", {}), memo)
if _USER_PRESERVED_ATTRIBUTES_KEY in res.meta:
for attr_name, attr in res.meta[_USER_PRESERVED_ATTRIBUTES_KEY].items():
setattr(res, attr_name, attr)
if hasattr(self, "_deepcopy_hooks"):
for hook in self._deepcopy_hooks:
hook(res)
return res
def __copy__(self):
from ._lazy_graph_module import _make_graph_module
res = _make_graph_module(self, self.graph)
res.meta = getattr(self, "meta", {})
return res
@compatibility(is_backward_compatible=False)
def print_readable(
self,
print_output=True,
include_stride=False,
include_device=False,
colored=False,
*,
# If `fast_sympy_print` is True then we use a sympy printer which is faster
# but may result in less-readable output.
fast_sympy_print: bool = False,
expanded_def: bool = False,
):
"""
Return the Python code generated for current GraphModule and its children GraphModules
"""
ctx_mgr = contextlib.ExitStack()
with ctx_mgr:
if fast_sympy_print:
from torch._inductor.utils import sympy_str
def fast_repr(expr: torch.types.PySymType) -> str:
return sympy_str(expr.node.expr)
ctx_mgr.enter_context(_override_sym_repr(fast_repr))
r = _print_readable(
self,
self._get_name(),
print_output,
include_stride,
include_device,
colored,
expanded_def,
)
return r
def __str__(self) -> str:
orig_str = super().__str__()
print_readable_reminder = (
"# To see more debug info, please use `graph_module.print_readable()`"
)
return "\n".join([orig_str, self._code, print_readable_reminder])
def _replicate_for_data_parallel(self):
new_gm = self.__copy__()
new_gm._is_replica = True
return new_gm
@contextlib.contextmanager
def _set_replace_hook(self, f):
"""
Takes a callable which will be called every time when we replace a node
to a new node, or change the node's name. Callable takes three arguments:
the old node we're changing, and NAME of the new node, followed by the
user node which consumes the old node to be replaced.
"""
assert callable(f), "Replace hook must be a callable."
self._register_replace_node_hook(f)
try:
yield
finally:
self._unregister_replace_node_hook(f)
def _register_replace_node_hook(self, f):
"""
Takes a callable which will be called every time when we replace a node
to a new node, or change the node's name. Callable takes three arguments:
the old node we're changing, and NAME of the new node, followed by the
user node which consumes the old node to be replaced.
"""
assert callable(f), "create_node hook must be a callable."
self._replace_hooks.append(f)
def _unregister_replace_node_hook(self, f):
"""
Takes a callable which was previously registered to be called every time when we replace a node.
This function will unregister that callable so it is no longer invoked on node replacement.
"""
assert callable(f), "create_node hook must be a callable."
self._replace_hooks.remove(f)
def _register_create_node_hook(self, f):
"""
Takes a callable which will be called after we create a new node. The
callable takes the newly created node as input and returns None.
"""
assert callable(f), "create_node hook must be a callable."
self._create_node_hooks.append(f)
def _unregister_create_node_hook(self, f):
"""
Takes a callable which was previously registered to be called after we create a node.
This function will unregister that callable so it is no longer invoked on node creation.
"""
assert callable(f), "create_node hook must be a callable."
self._create_node_hooks.remove(f)
def _register_erase_node_hook(self, f):
"""
Takes a callable which will be called after we erase a node. The
callable takes the node that is being erased as input and returns None.
"""
assert callable(f), "erase_node hook must be a callable."
self._erase_node_hooks.append(f)
def _unregister_erase_node_hook(self, f):
"""
Takes a callable which was previously registered to be called after we erase a node.
This function will unregister that callable so it is no longer invoked on node erasure.
"""
assert callable(f), "erase_node hook must be a callable."
self._erase_node_hooks.remove(f)
def _register_deepcopy_hook(self, f):
"""
Takes a callable which will be called when we deepcopy this graph module. The
callable takes the resulting deepcopied graph module.
"""
assert callable(f), "deepcopy hook must be a callable."
self._deepcopy_hooks.append(f)
def _unregister_deepcopy_hook(self, f):
"""
Takes a callable which was previously registered to be called after deepcopy.
This function will unregister that callable so it is no longer invoked on deepcopy.
"""
assert callable(f), "deepcopy hook must be a callable."
self._deepcopy_hooks.remove(f)
# workarounds for issues in __torch_function__
# WAR for __torch_function__ not handling tensor lists,
# fix is in https://github.com/pytorch/pytorch/pull/34725
# orig_cat = torch.cat
# def patched_cat(*args, **kwargs):
# tensors = args[0]
# for t in tensors:
# if isinstance(t, Proxy):
# return t.__torch_function__(patched_cat, (), args, kwargs)
# return orig_cat(*args, **kwargs)
# patched_cat.__module__ = 'torch'
# patched_cat.__name__ = 'cat'
# torch.cat = patched_cat
| GraphModule |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/functions.py | {
"start": 64173,
"end": 64538
} | class ____(GenericFunction[int]):
"""Implement the ``rank`` hypothetical-set aggregate function.
This function must be used with the :meth:`.FunctionElement.within_group`
modifier to supply a sort expression to operate upon.
The return type of this function is :class:`.Integer`.
"""
type = sqltypes.Integer()
inherit_cache = True
| rank |
python | PyCQA__pylint | tests/functional/g/globals.py | {
"start": 376,
"end": 2871
} | class ____:
pass
def fix_contant(value):
"""all this is ok, but try not using global ;)"""
global CONSTANT # [global-statement]
print(CONSTANT)
CONSTANT = value
def other():
"""global behaviour test"""
global HOP # [global-variable-not-assigned]
print(HOP) # [undefined-variable]
def define_constant():
"""ok but somevar is not defined at the module scope"""
global SOMEVAR # [global-variable-undefined]
SOMEVAR = 2
def global_with_import():
"""should only warn for global-statement when using `Import` node"""
global sys # [global-statement]
import sys # [unused-import]
def global_with_import_from():
"""should only warn for global-statement when using `ImportFrom` node"""
global namedtuple # [global-statement]
from collections import namedtuple # [unused-import]
def global_no_assign():
"""Not assigning anything to the global makes 'global' superfluous"""
global CONSTANT # [global-variable-not-assigned]
print(CONSTANT)
def global_del():
"""Deleting the global name prevents `global-variable-not-assigned`"""
global CONSTANT # [global-statement]
print(CONSTANT)
del CONSTANT
def global_operator_assign():
"""Operator assigns should only throw a global statement error"""
global CONSTANT # [global-statement]
print(CONSTANT)
CONSTANT += 1
def global_function_assign():
"""Function assigns should only throw a global statement error"""
global CONSTANT # [global-statement]
def CONSTANT():
pass
CONSTANT()
def override_func():
"""Overriding a function should only throw a global statement error"""
global FUNC # [global-statement]
def FUNC():
pass
FUNC()
def override_class():
"""Overriding a class should only throw a global statement error"""
global CLASS # [global-statement]
class CLASS():
pass
CLASS()
def init_connection_state(alias):
"""Demonstrate that non-assignment modifications to global objects should emit message."""
global RAN_DB_SET # [global-variable-not-assigned]
global RAN_DB_DICT # [global-variable-not-assigned]
RAN_DB_SET.add(alias)
return RAN_DB_DICT.setdefault("color", "Palomino")
# Prevent emitting `invalid-name` for the line on which `global` is declared
# https://github.com/pylint-dev/pylint/issues/8307
_foo: str = "tomato"
def setup_shared_foo():
global _foo # [global-statement]
_foo = "potato"
| CLASS |
python | pypa__hatch | src/hatch/template/files_feature_cli.py | {
"start": 480,
"end": 1092
} | class ____(File):
TEMPLATE = """\
import click
from {package_name}.__about__ import __version__
@click.group(context_settings={{"help_option_names": ["-h", "--help"]}}, invoke_without_command=True)
@click.version_option(version=__version__, prog_name="{project_name}")
def {package_name}():
click.echo("Hello world!")
"""
def __init__(
self,
template_config: dict,
plugin_config: dict, # noqa: ARG002
):
super().__init__(
Path(template_config["package_name"], "cli", "__init__.py"), self.TEMPLATE.format(**template_config)
)
| CommandLinePackage |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/annotation.py | {
"start": 2989,
"end": 4504
} | class ____(SupportsAnnotations):
__slots__ = ()
_constructor: Callable[..., SupportsWrappingAnnotations]
if TYPE_CHECKING:
@util.ro_non_memoized_property
def entity_namespace(self) -> _EntityNamespace: ...
def _annotate(self, values: _AnnotationDict) -> Self:
"""return a copy of this ClauseElement with annotations
updated by the given dictionary.
"""
return Annotated._as_annotated_instance(self, values) # type: ignore
def _with_annotations(self, values: _AnnotationDict) -> Self:
"""return a copy of this ClauseElement with annotations
replaced by the given dictionary.
"""
return Annotated._as_annotated_instance(self, values) # type: ignore
@overload
def _deannotate(
self,
values: Literal[None] = ...,
clone: bool = ...,
) -> Self: ...
@overload
def _deannotate(
self,
values: Sequence[str] = ...,
clone: bool = ...,
) -> SupportsAnnotations: ...
def _deannotate(
self,
values: Optional[Sequence[str]] = None,
clone: bool = False,
) -> SupportsAnnotations:
"""return a copy of this :class:`_expression.ClauseElement`
with annotations
removed.
:param values: optional tuple of individual values
to remove.
"""
if clone:
s = self._clone()
return s
else:
return self
| SupportsWrappingAnnotations |
python | django__django | tests/test_client_regress/tests.py | {
"start": 44174,
"end": 47737
} | class ____(SimpleTestCase):
def test_post(self):
"Request a view with string data via request method POST"
# Regression test for #11371
data = '{"test": "json"}'
response = self.client.post(
"/request_methods/", data=data, content_type="application/json"
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b"request method: POST")
def test_put(self):
"Request a view with string data via request method PUT"
# Regression test for #11371
data = '{"test": "json"}'
response = self.client.put(
"/request_methods/", data=data, content_type="application/json"
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b"request method: PUT")
def test_patch(self):
"Request a view with string data via request method PATCH"
# Regression test for #17797
data = '{"test": "json"}'
response = self.client.patch(
"/request_methods/", data=data, content_type="application/json"
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b"request method: PATCH")
def test_empty_string_data(self):
"""
Request a view with empty string data via request method GET/POST/HEAD
"""
# Regression test for #21740
response = self.client.get("/body/", data="", content_type="application/json")
self.assertEqual(response.content, b"")
response = self.client.post("/body/", data="", content_type="application/json")
self.assertEqual(response.content, b"")
response = self.client.head("/body/", data="", content_type="application/json")
self.assertEqual(response.content, b"")
def test_json_bytes(self):
response = self.client.post(
"/body/", data=b"{'value': 37}", content_type="application/json"
)
self.assertEqual(response.content, b"{'value': 37}")
def test_json(self):
response = self.client.get("/json_response/")
self.assertEqual(response.json(), {"key": "value"})
def test_json_charset(self):
response = self.client.get("/json_response_latin1/")
self.assertEqual(response.charset, "latin1")
self.assertEqual(response.json(), {"a": "Ã…"})
def test_json_structured_suffixes(self):
valid_types = (
"application/vnd.api+json",
"application/vnd.api.foo+json",
"application/json; charset=utf-8",
"application/activity+json",
"application/activity+json; charset=utf-8",
)
for content_type in valid_types:
response = self.client.get(
"/json_response/", {"content_type": content_type}
)
self.assertEqual(response.headers["Content-Type"], content_type)
self.assertEqual(response.json(), {"key": "value"})
def test_json_multiple_access(self):
response = self.client.get("/json_response/")
self.assertIs(response.json(), response.json())
def test_json_wrong_header(self):
response = self.client.get("/body/")
msg = (
'Content-Type header is "text/html; charset=utf-8", not "application/json"'
)
with self.assertRaisesMessage(ValueError, msg):
self.assertEqual(response.json(), {"key": "value"})
@override_settings(
ROOT_URLCONF="test_client_regress.urls",
)
| RequestMethodStringDataTests |
python | tensorflow__tensorflow | tensorflow/python/keras/engine/data_adapter.py | {
"start": 47274,
"end": 59083
} | class ____(DataHandler):
"""A `DataHandler` that is compatible with `ClusterCoordinator`."""
def __init__(self, x, y=None, **kwargs):
if not isinstance(x, dataset_creator.DatasetCreator):
x = self._convert_to_dataset_creator(x, y, **kwargs)
super().__init__(x=x, **kwargs)
def _convert_to_dataset_creator(self, x, y, **kwargs):
"""Converts non-tf.data.Dataset to `DatasetCreator` instances."""
def _dataset_fn(input_context):
del input_context
data_adapter_cls = select_data_adapter(x, y)
return data_adapter_cls(x=x, y=y, **kwargs).get_dataset()
# This check is needed because types like `tf.data.Dataset` don't work with
# PSS yet. So only apply this logic to the types we can support.
if (isinstance(x, _get_tensor_types()) and
isinstance(y, _get_tensor_types())):
return dataset_creator.DatasetCreator(_dataset_fn)
else:
raise NotImplementedError(
"Only `tf.keras.utils.experimental.DatasetCreator`, `tf.Tensor`, "
"numpy arrays and pandas dataframes are supported types at this "
"time.")
def _configure_dataset_and_inferred_steps(self, strategy, x, steps_per_epoch,
class_weight, distribute):
if not isinstance(x, dataset_creator.DatasetCreator):
raise TypeError("When using `ParameterServerStrategy`, `x` must be a "
"`DatasetCreator`.")
def per_worker_dataset_fn():
return strategy.distribute_datasets_from_function(
x, options=x.input_options)
self._dataset = self._model._cluster_coordinator.create_per_worker_dataset( # pylint: disable=protected-access
per_worker_dataset_fn)
if steps_per_epoch == -1:
self._inferred_steps = None
self._log_indefinite_training_warning()
else:
self._inferred_steps = steps_per_epoch
def sync(self):
self._model._cluster_coordinator.join() # pylint: disable=protected-access
def get_data_handler(*args, **kwargs):
if getattr(kwargs["model"], "_cluster_coordinator", None):
return _ClusterCoordinatorDataHandler(*args, **kwargs)
return DataHandler(*args, **kwargs)
def _make_class_weight_map_fn(class_weight):
"""Applies class weighting to a `Dataset`.
The `Dataset` is assumed to be in format `(x, y)` or `(x, y, sw)`, where
`y` must be a single `Tensor`.
Args:
class_weight: A map where the keys are integer class ids and values are
the class weights, e.g. `{0: 0.2, 1: 0.6, 2: 0.3}`
Returns:
A function that can be used with `tf.data.Dataset.map` to apply class
weighting.
"""
class_ids = list(sorted(class_weight.keys()))
expected_class_ids = list(range(len(class_ids)))
if class_ids != expected_class_ids:
error_msg = (
"Expected `class_weight` to be a dict with keys from 0 to one less "
"than the number of classes, found {}").format(class_weight)
raise ValueError(error_msg)
class_weight_tensor = tensor_conversion.convert_to_tensor_v2_with_dispatch(
[class_weight[int(c)] for c in class_ids]
)
def _class_weights_map_fn(*data):
"""Convert `class_weight` to `sample_weight`."""
x, y, sw = unpack_x_y_sample_weight(data)
if nest.is_nested(y):
raise ValueError(
"`class_weight` is only supported for Models with a single output.")
if y.shape.rank > 2:
raise ValueError("`class_weight` not supported for "
"3+ dimensional targets.")
y_classes = smart_cond.smart_cond(
y.shape.rank == 2 and backend.shape(y)[1] > 1,
lambda: backend.argmax(y, axis=1),
lambda: math_ops.cast(backend.reshape(y, (-1,)), dtypes.int64))
cw = array_ops.gather_v2(class_weight_tensor, y_classes)
if sw is not None:
cw = math_ops.cast(cw, sw.dtype)
sw, cw = expand_1d((sw, cw))
# `class_weight` and `sample_weight` are multiplicative.
sw = sw * cw
else:
sw = cw
return x, y, sw
return _class_weights_map_fn
def expand_1d(data):
"""Expands 1-dimensional `Tensor`s into 2-dimensional `Tensor`s."""
def _expand_single_1d_tensor(t):
# Leaves `CompositeTensor`s as-is.
if (isinstance(t, tensor.Tensor) and
isinstance(t.shape, tensor_shape.TensorShape) and t.shape.rank == 1):
return array_ops.expand_dims_v2(t, axis=-1)
return t
return nest.map_structure(_expand_single_1d_tensor, data)
def train_validation_split(arrays, validation_split):
"""Split arrays into train and validation subsets in deterministic order.
The last part of data will become validation data.
Args:
arrays: Tensors to split. Allowed inputs are arbitrarily nested structures
of Tensors and NumPy arrays.
validation_split: Float between 0 and 1. The proportion of the dataset to
include in the validation split. The rest of the dataset will be included
in the training split.
Returns:
`(train_arrays, validation_arrays)`
"""
def _can_split(t):
tensor_types = _get_tensor_types()
return isinstance(t, tensor_types) or t is None
flat_arrays = nest.flatten(arrays)
unsplitable = [type(t) for t in flat_arrays if not _can_split(t)]
if unsplitable:
raise ValueError(
"`validation_split` is only supported for Tensors or NumPy "
"arrays, found following types in the input: {}".format(unsplitable))
if all(t is None for t in flat_arrays):
return arrays, arrays
first_non_none = None
for t in flat_arrays:
if t is not None:
first_non_none = t
break
# Assumes all arrays have the same batch shape or are `None`.
batch_dim = int(first_non_none.shape[0])
split_at = int(math.floor(batch_dim * (1. - validation_split)))
if split_at == 0 or split_at == batch_dim:
raise ValueError(
"Training data contains {batch_dim} samples, which is not sufficient "
"to split it into a validation and training set as specified by "
"`validation_split={validation_split}`. Either provide more data, or a "
"different value for the `validation_split` argument." .format(
batch_dim=batch_dim, validation_split=validation_split))
def _split(t, start, end):
if t is None:
return t
return t[start:end]
train_arrays = nest.map_structure(
functools.partial(_split, start=0, end=split_at), arrays)
val_arrays = nest.map_structure(
functools.partial(_split, start=split_at, end=batch_dim), arrays)
return train_arrays, val_arrays
def unpack_x_y_sample_weight(data):
"""Unpacks user-provided data tuple.
This is a convenience utility to be used when overriding
`Model.train_step`, `Model.test_step`, or `Model.predict_step`.
This utility makes it easy to support data of the form `(x,)`,
`(x, y)`, or `(x, y, sample_weight)`.
Standalone usage:
>>> features_batch = tf.ones((10, 5))
>>> labels_batch = tf.zeros((10, 5))
>>> data = (features_batch, labels_batch)
>>> # `y` and `sample_weight` will default to `None` if not provided.
>>> x, y, sample_weight = tf.keras.utils.unpack_x_y_sample_weight(data)
>>> sample_weight is None
True
Example in overridden `Model.train_step`:
```python
class MyModel(tf.keras.Model):
def train_step(self, data):
# If `sample_weight` is not provided, all samples will be weighted
# equally.
x, y, sample_weight = tf.keras.utils.unpack_x_y_sample_weight(data)
with tf.GradientTape() as tape:
y_pred = self(x, training=True)
loss = self.compiled_loss(
y, y_pred, sample_weight, regularization_losses=self.losses)
trainable_variables = self.trainable_variables
gradients = tape.gradient(loss, trainable_variables)
self.optimizer.apply_gradients(zip(gradients, trainable_variables))
self.compiled_metrics.update_state(y, y_pred, sample_weight)
return {m.name: m.result() for m in self.metrics}
```
Args:
data: A tuple of the form `(x,)`, `(x, y)`, or `(x, y, sample_weight)`.
Returns:
The unpacked tuple, with `None`s for `y` and `sample_weight` if they are not
provided.
"""
if not isinstance(data, tuple):
return (data, None, None)
elif len(data) == 1:
return (data[0], None, None)
elif len(data) == 2:
return (data[0], data[1], None)
elif len(data) == 3:
return (data[0], data[1], data[2])
else:
error_msg = ("Data is expected to be in format `x`, `(x,)`, `(x, y)`, "
"or `(x, y, sample_weight)`, found: {}").format(data)
raise ValueError(error_msg)
def pack_x_y_sample_weight(x, y=None, sample_weight=None):
"""Packs user-provided data into a tuple.
This is a convenience utility for packing data into the tuple formats
that `Model.fit` uses.
Standalone usage:
>>> x = tf.ones((10, 1))
>>> data = tf.keras.utils.pack_x_y_sample_weight(x)
>>> isinstance(data, tf.Tensor)
True
>>> y = tf.ones((10, 1))
>>> data = tf.keras.utils.pack_x_y_sample_weight(x, y)
>>> isinstance(data, tuple)
True
>>> x, y = data
Args:
x: Features to pass to `Model`.
y: Ground-truth targets to pass to `Model`.
sample_weight: Sample weight for each element.
Returns:
Tuple in the format used in `Model.fit`.
"""
if y is None:
# For single x-input, we do no tuple wrapping since in this case
# there is no ambiguity. This also makes NumPy and Dataset
# consistent in that the user does not have to wrap their Dataset
# data in an unnecessary tuple
if not nest.is_nested(x):
return x
else:
return (x,)
elif sample_weight is None:
return (x, y)
else:
return (x, y, sample_weight)
def single_batch_iterator(strategy,
x,
y=None,
sample_weight=None,
class_weight=None):
"""Creates a single-batch dataset."""
x, y, sample_weight = _process_tensorlike((x, y, sample_weight))
if y is None:
data = (x,)
elif sample_weight is None:
data = (x, y)
else:
data = (x, y, sample_weight)
_check_data_cardinality(data)
dataset = dataset_ops.DatasetV2.from_tensors(data)
if class_weight:
dataset = dataset.map(_make_class_weight_map_fn(class_weight))
dataset = strategy.experimental_distribute_dataset(dataset)
return iter(dataset)
def _check_data_cardinality(data):
num_samples = set(int(i.shape[0]) for i in nest.flatten(data))
if len(num_samples) > 1:
msg = "Data cardinality is ambiguous:\n"
for label, single_data in zip(["x", "y", "sample_weight"], data):
msg += " {} sizes: {}\n".format(
label, ", ".join(str(i.shape[0]) for i in nest.flatten(single_data)))
msg += "Make sure all arrays contain the same number of samples."
raise ValueError(msg)
def _get_tensor_types():
try:
import pandas as pd # pylint: disable=g-import-not-at-top
return (tensor.Tensor, np.ndarray, pd.Series, pd.DataFrame)
except ImportError:
return (tensor.Tensor, np.ndarray)
def _is_scipy_sparse(x):
try:
from scipy.sparse import issparse # pylint: disable=g-import-not-at-top
return issparse(x)
except ImportError:
return False
def _scipy_sparse_to_sparse_tensor(t):
"""Converts a SciPy sparse matrix to a SparseTensor."""
sparse_coo = t.tocoo()
row, col = sparse_coo.row, sparse_coo.col
data, shape = sparse_coo.data, sparse_coo.shape
if issubclass(data.dtype.type, np.floating):
data = data.astype(backend.floatx())
indices = np.concatenate(
(np.expand_dims(row, axis=1), np.expand_dims(col, axis=1)), axis=1)
return sparse_tensor.SparseTensor(indices, data, shape)
def _is_distributed_dataset(ds):
return isinstance(ds, input_lib.DistributedDatasetInterface)
| _ClusterCoordinatorDataHandler |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 1231,
"end": 1556
} | class ____(Interface):
"""An event type that is emitted whenever any :app:`Pyramid`
view returns a response. See the
documentation attached to :class:`pyramid.events.NewResponse`
for more information."""
request = Attribute('The request object')
response = Attribute('The response object')
| INewResponse |
python | huggingface__transformers | src/transformers/models/levit/modeling_levit.py | {
"start": 20250,
"end": 22699
} | class ____(LevitPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.config = config
self.num_labels = config.num_labels
self.levit = LevitModel(config)
# Classifier head
self.classifier = (
LevitClassificationLayer(config.hidden_sizes[-1], config.num_labels)
if config.num_labels > 0
else torch.nn.Identity()
)
# Initialize weights and apply final processing
self.post_init()
@auto_docstring
def forward(
self,
pixel_values: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, ImageClassifierOutputWithNoAttention]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.levit(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)
sequence_output = outputs[0]
sequence_output = sequence_output.mean(1)
logits = self.classifier(sequence_output)
loss = None
if labels is not None:
loss = self.loss_function(labels, logits, self.config)
if not return_dict:
output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return ImageClassifierOutputWithNoAttention(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
)
@auto_docstring(
custom_intro="""
LeViT Model transformer with image classification heads on top (a linear layer on top of the final hidden state and
a linear layer on top of the final hidden state of the distillation token) e.g. for ImageNet. .. warning::
This model supports inference-only. Fine-tuning with distillation (i.e. with a teacher) is not yet
supported.
"""
)
| LevitForImageClassification |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_S.py | {
"start": 29712,
"end": 31120
} | class ____(Benchmark):
r"""
SineEnvelope objective function.
This class defines the SineEnvelope [1]_ global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{SineEnvelope}}(x) = -\sum_{i=1}^{n-1}\left[\frac{\sin^2(
\sqrt{x_{i+1}^2+x_{i}^2}-0.5)}
{(0.001(x_{i+1}^2+x_{i}^2)+1)^2}
+ 0.5\right]
Here, :math:`n` represents the number of dimensions and
:math:`x_i \in [-100, 100]` for :math:`i = 1, ..., n`.
*Global optimum*: :math:`f(x) = 0` for :math:`x_i = 0` for
:math:`i = 1, ..., n`
.. [1] Gavana, A. Global Optimization Benchmarks and AMPGO retrieved 2015
TODO: Jamil #136
"""
change_dimensionality = True
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip([-100.0] * self.N,
[100.0] * self.N))
self.custom_bounds = [(-20, 20), (-20, 20)]
self.global_optimum = [[0 for _ in range(self.N)]]
self.fglob = 0.0
def fun(self, x, *args):
self.nfev += 1
X0 = x[:-1]
X1 = x[1:]
X02X12 = X0 ** 2 + X1 ** 2
return sum((sin(sqrt(X02X12)) ** 2 - 0.5) / (1 + 0.001 * X02X12) ** 2
+ 0.5)
| SineEnvelope |
python | sqlalchemy__sqlalchemy | test/sql/test_from_linter.py | {
"start": 14108,
"end": 18077
} | class ____(fixtures.TablesTest):
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"table_a",
metadata,
Column("col_a", Integer, primary_key=True, autoincrement=False),
)
Table(
"table_b",
metadata,
Column("col_b", Integer, primary_key=True, autoincrement=False),
)
@classmethod
def setup_bind(cls):
# from linting is enabled by default
return config.db
@testing.only_on("sqlite")
def test_noop_for_unhandled_objects(self):
with self.bind.connect() as conn:
conn.exec_driver_sql("SELECT 1;").fetchone()
def test_does_not_modify_query(self):
with self.bind.connect() as conn:
[result] = conn.execute(select(1)).fetchone()
assert result == 1
def test_warn_simple(self):
a, b = self.tables("table_a", "table_b")
query = select(a.c.col_a).where(b.c.col_b == 5)
with expect_warnings(
r"SELECT statement has a cartesian product between FROM "
r'element\(s\) "table_[ab]" '
r'and FROM element "table_[ba]"'
):
with self.bind.connect() as conn:
conn.execute(query)
def test_warn_anon_alias(self):
a, b = self.tables("table_a", "table_b")
b_alias = b.alias()
query = select(a.c.col_a).where(b_alias.c.col_b == 5)
with expect_warnings(
r"SELECT statement has a cartesian product between FROM "
r'element\(s\) "table_(?:a|b_1)" '
r'and FROM element "table_(?:a|b_1)"'
):
with self.bind.connect() as conn:
conn.execute(query)
@testing.requires.ctes
def test_warn_anon_cte(self):
a, b = self.tables("table_a", "table_b")
b_cte = select(b).cte()
query = select(a.c.col_a).where(b_cte.c.col_b == 5)
with expect_warnings(
r"SELECT statement has a cartesian product between "
r"FROM element\(s\) "
r'"(?:anon_1|table_a)" '
r'and FROM element "(?:anon_1|table_a)"'
):
with self.bind.connect() as conn:
conn.execute(query)
@testing.variation(
"dml",
[
("update", testing.requires.update_from),
("delete", testing.requires.delete_using),
],
)
@testing.combinations(
(False, False), (True, False), (True, True), argnames="twotable,error"
)
def test_warn_dml(self, dml, twotable, error):
a, b = self.tables("table_a", "table_b")
if dml.update:
stmt = update(a).values(col_a=5)
elif dml.delete:
stmt = delete(a)
else:
dml.fail()
stmt = stmt.where(a.c.col_a == 1)
if twotable:
stmt = stmt.where(b.c.col_b == 1)
if not error:
stmt = stmt.where(b.c.col_b == a.c.col_a)
stmt_type = "UPDATE" if dml.update else "DELETE"
with self.bind.connect() as conn:
if error:
with expect_warnings(
rf"{stmt_type} statement has a cartesian product between "
rf'FROM element\(s\) "table_[ab]" and FROM '
rf'element "table_[ab]"'
):
with self.bind.connect() as conn:
conn.execute(stmt)
else:
conn.execute(stmt)
def test_no_linting(self, metadata, connection):
eng = engines.testing_engine(
options={"enable_from_linting": False, "use_reaper": False}
)
eng.pool = self.bind.pool # needed for SQLite
a, b = self.tables("table_a", "table_b")
query = select(a.c.col_a).where(b.c.col_b == 5)
with eng.connect() as conn:
conn.execute(query)
| TestLinterRoundTrip |
python | pandas-dev__pandas | asv_bench/benchmarks/io/csv.py | {
"start": 9425,
"end": 10146
} | class ____(StringIORewind):
def setup(self):
self.na_values = [2**63 + 500]
arr = np.arange(10000).astype("uint64") + 2**63
self.data1 = StringIO("\n".join(arr.astype(str).tolist()))
arr = arr.astype(object)
arr[500] = -1
self.data2 = StringIO("\n".join(arr.astype(str).tolist()))
def time_read_uint64(self):
read_csv(self.data(self.data1), header=None, names=["foo"])
def time_read_uint64_neg_values(self):
read_csv(self.data(self.data2), header=None, names=["foo"])
def time_read_uint64_na_values(self):
read_csv(
self.data(self.data1), header=None, names=["foo"], na_values=self.na_values
)
| ReadUint64Integers |
python | doocs__leetcode | solution/2500-2599/2542.Maximum Subsequence Score/Solution.py | {
"start": 0,
"end": 370
} | class ____:
def maxScore(self, nums1: List[int], nums2: List[int], k: int) -> int:
nums = sorted(zip(nums2, nums1), reverse=True)
q = []
ans = s = 0
for a, b in nums:
s += b
heappush(q, b)
if len(q) == k:
ans = max(ans, s * a)
s -= heappop(q)
return ans
| Solution |
python | ipython__ipython | IPython/core/magic_arguments.py | {
"start": 4488,
"end": 7066
} | class ____(argparse.ArgumentParser):
""" An ArgumentParser tweaked for use by IPython magics.
"""
def __init__(self,
prog=None,
usage=None,
description=None,
epilog=None,
parents=None,
formatter_class=MagicHelpFormatter,
prefix_chars='-',
argument_default=None,
conflict_handler='error',
add_help=False):
if parents is None:
parents = []
super(MagicArgumentParser, self).__init__(prog=prog, usage=usage,
description=description, epilog=epilog,
parents=parents, formatter_class=formatter_class,
prefix_chars=prefix_chars, argument_default=argument_default,
conflict_handler=conflict_handler, add_help=add_help)
def error(self, message):
""" Raise a catchable error instead of exiting.
"""
raise UsageError(message)
def parse_argstring(self, argstring, *, partial=False):
""" Split a string into an argument list and parse that argument list.
"""
argv = arg_split(argstring, strict=not partial)
if partial:
return self.parse_known_args(argv)
return self.parse_args(argv)
def construct_parser(magic_func):
""" Construct an argument parser using the function decorations.
"""
kwds = getattr(magic_func, 'argcmd_kwds', {})
if 'description' not in kwds:
kwds['description'] = getattr(magic_func, '__doc__', None)
arg_name = real_name(magic_func)
parser = MagicArgumentParser(arg_name, **kwds)
# Reverse the list of decorators in order to apply them in the
# order in which they appear in the source.
group = None
for deco in magic_func.decorators[::-1]:
result = deco.add_to_parser(parser, group)
if result is not None:
group = result
# Replace the magic function's docstring with the full help text.
magic_func.__doc__ = parser.format_help()
return parser
def parse_argstring(magic_func, argstring, *, partial=False):
""" Parse the string of arguments for the given magic function.
"""
return magic_func.parser.parse_argstring(argstring, partial=partial)
def real_name(magic_func):
""" Find the real name of the magic.
"""
magic_name = magic_func.__name__
if magic_name.startswith('magic_'):
magic_name = magic_name[len('magic_'):]
return getattr(magic_func, 'argcmd_name', magic_name)
| MagicArgumentParser |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 612835,
"end": 613481
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("SecurityAdvisoryEdge"), graphql_name="edges"
)
nodes = sgqlc.types.Field(
sgqlc.types.list_of("SecurityAdvisory"), graphql_name="nodes"
)
page_info = sgqlc.types.Field(
sgqlc.types.non_null(PageInfo), graphql_name="pageInfo"
)
total_count = sgqlc.types.Field(
sgqlc.types.non_null(Int), graphql_name="totalCount"
)
| SecurityAdvisoryConnection |
python | pydata__xarray | asv_bench/benchmarks/rolling.py | {
"start": 320,
"end": 2590
} | class ____:
def setup(self, *args, **kwargs):
self.ds = xr.Dataset(
{
"var1": (("x", "y"), randn_xy),
"var2": (("x", "t"), randn_xt),
"var3": (("t",), randn_t),
},
coords={
"x": np.arange(nx),
"y": np.linspace(0, 1, ny),
"t": pd.date_range("1970-01-01", periods=nt, freq="D"),
"x_coords": ("x", np.linspace(1.1, 2.1, nx)),
},
)
self.da_long = xr.DataArray(
randn_long, dims="x", coords={"x": np.arange(long_nx) * 0.1}
)
@parameterized(
["func", "center", "use_bottleneck"],
(["mean", "count"], [True, False], [True, False]),
)
def time_rolling(self, func, center, use_bottleneck):
with xr.set_options(use_bottleneck=use_bottleneck):
getattr(self.ds.rolling(x=window, center=center), func)().load()
@parameterized(
["func", "pandas", "use_bottleneck"],
(["mean", "count"], [True, False], [True, False]),
)
def time_rolling_long(self, func, pandas, use_bottleneck):
if pandas:
se = self.da_long.to_series()
getattr(se.rolling(window=window, min_periods=window), func)()
else:
with xr.set_options(use_bottleneck=use_bottleneck):
getattr(
self.da_long.rolling(x=window, min_periods=window), func
)().load()
@parameterized(
["window_", "min_periods", "use_bottleneck"], ([20, 40], [5, 5], [True, False])
)
def time_rolling_np(self, window_, min_periods, use_bottleneck):
with xr.set_options(use_bottleneck=use_bottleneck):
self.ds.rolling(x=window_, center=False, min_periods=min_periods).reduce(
np.nansum
).load()
@parameterized(
["center", "stride", "use_bottleneck"], ([True, False], [1, 1], [True, False])
)
def time_rolling_construct(self, center, stride, use_bottleneck):
with xr.set_options(use_bottleneck=use_bottleneck):
self.ds.rolling(x=window, center=center).construct(
"window_dim", stride=stride
).sum(dim="window_dim").load()
| Rolling |
python | mlflow__mlflow | tests/tensorflow/test_tensorflow2_autolog.py | {
"start": 14514,
"end": 15247
} | class ____(tf.keras.utils.Sequence):
def __init__(self, batch_size, with_sample_weights=False):
self.batch_size = batch_size
self.with_sample_weights = with_sample_weights
def __len__(self):
return 10
def __getitem__(self, idx):
x = np.array([idx] * self.batch_size)
y = np.array([-idx] * self.batch_size)
if self.with_sample_weights:
w = np.array([1] * self.batch_size)
return x, y, w
return x, y
def __generator(data, target, batch_size):
data_batches = np.split(data, data.shape[0] // batch_size)
target_batches = np.split(target, target.shape[0] // batch_size)
yield from zip(data_batches, target_batches)
| __ExampleSequence |
python | jazzband__django-model-utils | tests/models.py | {
"start": 8598,
"end": 9010
} | class ____(models.Model):
fk = models.ForeignKey('Tracked', on_delete=models.PROTECT)
self_ref = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True)
tracker = LoopDetectionFieldTracker()
custom_tracker = LoopDetectionFieldTracker(fields=['fk_id', 'self_ref_id'])
custom_tracker_without_id = LoopDetectionFieldTracker(fields=['fk', 'self_ref'])
| TrackedProtectedSelfRefFK |
python | dagster-io__dagster | python_modules/dagster-pipes/dagster_pipes/__init__.py | {
"start": 16733,
"end": 18315
} | class ____(ABC, Generic[T_MessageChannel]):
@abstractmethod
@contextmanager
def open(self, params: PipesParams) -> Iterator[T_MessageChannel]:
"""A `@contextmanager` that initializes a channel for writing messages back to Dagster.
This method should takes the params passed by the orchestration-side
:py:class:`PipesMessageReader` and use them to construct and yield a
:py:class:`PipesMessageWriterChannel`.
Args:
params (PipesParams): The params provided by the message reader in the orchestration
process.
Yields:
PipesMessageWriterChannel: Channel for writing messagse back to Dagster.
"""
@final
def get_opened_payload(self) -> PipesOpenedData:
"""Return a payload containing information about the external process to be passed back to
the orchestration process. This should contain information that cannot be known before
the external process is launched.
This method should not be overridden by users. Instead, users should
override `get_opened_extras` to inject custom data.
"""
return {"extras": self.get_opened_extras()}
def get_opened_extras(self) -> PipesExtras:
"""Return arbitary reader-specific information to be passed back to the orchestration
process under the `extras` key of the initialization payload.
Returns:
PipesExtras: A dict of arbitrary data to be passed back to the orchestration process.
"""
return {}
| PipesMessageWriter |
python | ray-project__ray | python/ray/serve/tests/unit/test_config.py | {
"start": 4428,
"end": 9121
} | class ____:
def test_deployment_config_validation(self):
# Test config ignoring unknown keys (required for forward-compatibility)
DeploymentConfig(new_version_key=-1)
# Test num_replicas validation.
DeploymentConfig(num_replicas=1)
with pytest.raises(ValidationError, match="type_error"):
DeploymentConfig(num_replicas="hello")
with pytest.raises(ValidationError, match="value_error"):
DeploymentConfig(num_replicas=-1)
# Test dynamic default for max_ongoing_requests.
assert DeploymentConfig().max_ongoing_requests == 5
def test_max_constructor_retry_count_validation(self):
# Test max_constructor_retry_count validation.
DeploymentConfig(max_constructor_retry_count=1)
DeploymentConfig(max_constructor_retry_count=10)
with pytest.raises(ValidationError, match="type_error"):
DeploymentConfig(max_constructor_retry_count="hello")
with pytest.raises(ValidationError, match="value_error"):
DeploymentConfig(max_constructor_retry_count=-1)
with pytest.raises(ValidationError, match="value_error"):
DeploymentConfig(max_constructor_retry_count=0)
# Test default value
assert DeploymentConfig().max_constructor_retry_count == 20
def test_deployment_config_update(self):
b = DeploymentConfig(num_replicas=1, max_ongoing_requests=1)
# Test updating a key works.
b.num_replicas = 2
assert b.num_replicas == 2
# Check that not specifying a key doesn't update it.
assert b.max_ongoing_requests == 1
# Check that input is validated.
with pytest.raises(ValidationError):
b.num_replicas = "Hello"
with pytest.raises(ValidationError):
b.num_replicas = -1
def test_from_default(self):
"""Check from_default() method behavior."""
# Valid parameters
dc = DeploymentConfig.from_default(num_replicas=5, is_cross_language=True)
assert dc.num_replicas == 5
assert dc.is_cross_language is True
# Invalid parameters should raise TypeError
with pytest.raises(TypeError):
DeploymentConfig.from_default(num_replicas=5, is_xlang=True)
# Validation should still be performed
with pytest.raises(ValidationError):
DeploymentConfig.from_default(num_replicas="hello world")
def test_from_default_ignore_default(self):
"""Check that from_default() ignores DEFAULT.VALUE kwargs."""
# Valid parameter with DEFAULT.VALUE passed in should be ignored
DeploymentConfig.from_default(num_replicas=DEFAULT.VALUE)
def test_setting_and_getting_request_router_class(self):
"""Check that setting and getting request_router_class works."""
request_router_path = (
"python.ray.serve.tests.unit.test_config.FakeRequestRouter"
)
if sys.platform == "win32":
request_router_path = (
"io_ray.python.ray.serve.tests.unit.test_config.FakeRequestRouter"
)
# Passing request_router_class as a class.
deployment_config = DeploymentConfig.from_default(
request_router_config=RequestRouterConfig(
request_router_class=FakeRequestRouter
)
)
assert (
deployment_config.request_router_config.request_router_class
== request_router_path
)
assert (
deployment_config.request_router_config.get_request_router_class()
== FakeRequestRouter
)
# Passing request_router_class as an import path.
deployment_config = DeploymentConfig.from_default(
request_router_config=RequestRouterConfig(
request_router_class=request_router_path
)
)
assert (
deployment_config.request_router_config.request_router_class
== request_router_path
)
assert (
deployment_config.request_router_config.get_request_router_class()
== FakeRequestRouter
)
# Not passing request_router_class should
# default to `PowerOfTwoChoicesRequestRouter`.
deployment_config = DeploymentConfig.from_default()
assert (
deployment_config.request_router_config.request_router_class
== "ray.serve._private.request_router:PowerOfTwoChoicesRequestRouter"
)
assert (
deployment_config.request_router_config.get_request_router_class()
== PowerOfTwoChoicesRequestRouter
)
| TestDeploymentConfig |
python | getsentry__sentry | src/sentry/api/helpers/group_index/types.py | {
"start": 451,
"end": 1005
} | class ____(TypedDict):
assignedTo: NotRequired[ActorSerializerResponse]
discard: NotRequired[bool]
hasSeen: NotRequired[bool]
inbox: NotRequired[bool]
isBookmarked: NotRequired[bool]
isPublic: NotRequired[bool]
isSubscribed: NotRequired[bool]
merge: NotRequired[MergedGroup]
priority: NotRequired[str]
shareId: NotRequired[str]
status: NotRequired[str]
statusDetails: NotRequired[StatusDetailsResult]
subscriptionDetails: NotRequired[SubscriptionDetails]
substatus: NotRequired[str]
| MutateIssueResponse |
python | django__django | tests/queries/tests.py | {
"start": 120477,
"end": 123452
} | class ____(TestCase):
"""Tests whose execution depend on different environment conditions like
Python version or DB backend features"""
@classmethod
def setUpTestData(cls):
generic = NamedCategory.objects.create(name="Generic")
t1 = Tag.objects.create(name="t1", category=generic)
Tag.objects.create(name="t2", parent=t1, category=generic)
t3 = Tag.objects.create(name="t3", parent=t1)
Tag.objects.create(name="t4", parent=t3)
Tag.objects.create(name="t5", parent=t3)
def test_infinite_loop(self):
# If you're not careful, it's possible to introduce infinite loops via
# default ordering on foreign keys in a cycle. We detect that.
with self.assertRaisesMessage(FieldError, "Infinite loop caused by ordering."):
list(LoopX.objects.all()) # Force queryset evaluation with list()
with self.assertRaisesMessage(FieldError, "Infinite loop caused by ordering."):
list(LoopZ.objects.all()) # Force queryset evaluation with list()
# Note that this doesn't cause an infinite loop, since the default
# ordering on the Tag model is empty (and thus defaults to using "id"
# for the related field).
self.assertEqual(len(Tag.objects.order_by("parent")), 5)
# ... but you can still order in a non-recursive fashion among linked
# fields (the previous test failed because the default ordering was
# recursive).
self.assertSequenceEqual(LoopX.objects.order_by("y__x__y__x__id"), [])
# When grouping without specifying ordering, we add an explicit "ORDER BY
# NULL" portion in MySQL to prevent unnecessary sorting.
@skipUnlessDBFeature("requires_explicit_null_ordering_when_grouping")
def test_null_ordering_added(self):
query = Tag.objects.values_list("parent_id", flat=True).order_by().query
query.group_by = ["parent_id"]
sql = query.get_compiler(DEFAULT_DB_ALIAS).as_sql()[0]
fragment = "ORDER BY "
pos = sql.find(fragment)
self.assertEqual(sql.find(fragment, pos + 1), -1)
self.assertEqual(sql.find("NULL", pos + len(fragment)), pos + len(fragment))
def test_in_list_limit(self):
# The "in" lookup works with lists of 1000 items or more.
# The numbers amount is picked to force three different IN batches
# for Oracle, yet to be less than 2100 parameter limit for MSSQL.
numbers = list(range(2050))
max_query_params = connection.features.max_query_params
if max_query_params is None or max_query_params >= len(numbers):
Number.objects.bulk_create(Number(num=num) for num in numbers)
for number in [1000, 1001, 2000, len(numbers)]:
with self.subTest(number=number):
self.assertEqual(
Number.objects.filter(num__in=numbers[:number]).count(), number
)
| ConditionalTests |
python | huggingface__transformers | src/transformers/models/videomae/modeling_videomae.py | {
"start": 12277,
"end": 12940
} | class ____(nn.Module):
def __init__(self, config: VideoMAEConfig):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_fn = config.hidden_act
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.intermediate_act_fn(hidden_states)
return hidden_states
# Copied from transformers.models.vit.modeling_vit.ViTOutput ViT->VideoMAE
| VideoMAEIntermediate |
python | walkccc__LeetCode | solutions/949. Largest Time for Given Digits/949.py | {
"start": 0,
"end": 233
} | class ____:
def largestTimeFromDigits(self, arr: list[int]) -> str:
for time in itertools.permutations(sorted(arr, reverse=True)):
if time[:2] < (2, 4) and time[2] < 6:
return '%d%d:%d%d' % time
return ''
| Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_config/pythonic_config/resource.py | {
"start": 24202,
"end": 27138
} | class ____(ConfigurableResourceFactory[TResValue]):
"""Base class for Dagster resources that utilize structured config.
This class is a subclass of both :py:class:`ResourceDefinition` and :py:class:`Config`.
Example definition:
.. code-block:: python
class WriterResource(ConfigurableResource):
prefix: str
def output(self, text: str) -> None:
print(f"{self.prefix}{text}")
Example usage:
.. code-block:: python
@asset
def asset_that_uses_writer(writer: WriterResource):
writer.output("text")
defs = Definitions(
assets=[asset_that_uses_writer],
resources={"writer": WriterResource(prefix="a_prefix")},
)
You can optionally use this class to model configuration only and vend an object
of a different type for use at runtime. This is useful for those who wish to
have a separate object that manages configuration and a separate object at runtime. Or
where you want to directly use a third-party class that you do not control.
To do this you override the `create_resource` methods to return a different object.
.. code-block:: python
class WriterResource(ConfigurableResource):
prefix: str
def create_resource(self, context: InitResourceContext) -> Writer:
# Writer is pre-existing class defined else
return Writer(self.prefix)
Example usage:
.. code-block:: python
@asset
def use_preexisting_writer_as_resource(writer: ResourceParam[Writer]):
writer.output("text")
defs = Definitions(
assets=[use_preexisting_writer_as_resource],
resources={"writer": WriterResource(prefix="a_prefix")},
)
"""
def create_resource(self, context: InitResourceContext) -> TResValue:
"""Returns the object that this resource hands to user code, accessible by ops or assets
through the context or resource parameters. This works like the function decorated
with @resource when using function-based resources.
For ConfigurableResource, this function will return itself, passing
the actual ConfigurableResource object to user code.
"""
return cast("TResValue", self)
def _is_fully_configured(resource: "CoercibleToResource") -> bool:
from dagster._core.execution.build_resources import wrap_resource_for_execution
actual_resource = wrap_resource_for_execution(resource)
res = (
validate_config(
actual_resource.config_schema.config_type,
(
actual_resource.config_schema.default_value
if actual_resource.config_schema.default_provided
else {}
),
).success
is True
)
return res and not isinstance(resource, PartialResource)
| ConfigurableResource |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 497096,
"end": 497530
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of CloseIssue"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "issue")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
issue = sgqlc.types.Field("Issue", graphql_name="issue")
"""The issue that was closed."""
| CloseIssuePayload |
python | run-llama__llama_index | llama-index-integrations/response_synthesizers/llama-index-response-synthesizers-google/llama_index/response_synthesizers/google/base.py | {
"start": 1639,
"end": 8725
} | class ____(BaseSynthesizer):
"""
Google's Attributed Question and Answering service.
Given a user's query and a list of passages, Google's server will return
a response that is grounded to the provided list of passages. It will not
base the response on parametric memory.
"""
_client: Any
_temperature: float
_answer_style: Any
_safety_setting: List[Any]
def __init__(
self,
*,
temperature: float,
answer_style: Any,
safety_setting: List[Any],
**kwargs: Any,
):
"""
Create a new Google AQA.
Prefer to use the factory `from_defaults` instead for type safety.
See `from_defaults` for more documentation.
"""
try:
import llama_index.vector_stores.google.genai_extension as genaix
except ImportError:
raise ImportError(_import_err_msg)
super().__init__(
llm=MockLLM(),
output_cls=SynthesizedResponse,
**kwargs,
)
self._client = genaix.build_generative_service()
self._temperature = temperature
self._answer_style = answer_style
self._safety_setting = safety_setting
# Type safe factory that is only available if Google is installed.
@classmethod
def from_defaults(
cls,
temperature: float = 0.7,
answer_style: int = 1,
safety_setting: List["genai.SafetySetting"] = [],
) -> "GoogleTextSynthesizer":
"""
Create a new Google AQA.
Example:
responder = GoogleTextSynthesizer.create(
temperature=0.7,
answer_style=AnswerStyle.ABSTRACTIVE,
safety_setting=[
SafetySetting(
category=HARM_CATEGORY_SEXUALLY_EXPLICIT,
threshold=HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
),
]
)
Args:
temperature: 0.0 to 1.0.
answer_style: See `google.ai.generativelanguage.GenerateAnswerRequest.AnswerStyle`
The default is ABSTRACTIVE (1).
safety_setting: See `google.ai.generativelanguage.SafetySetting`.
Returns:
an instance of GoogleTextSynthesizer.
"""
return cls(
temperature=temperature,
answer_style=answer_style,
safety_setting=safety_setting,
)
def get_response(
self,
query_str: str,
text_chunks: Sequence[str],
**response_kwargs: Any,
) -> SynthesizedResponse:
"""
Generate a grounded response on provided passages.
Args:
query_str: The user's question.
text_chunks: A list of passages that should be used to answer the
question.
Returns:
A `SynthesizedResponse` object.
"""
try:
import llama_index.vector_stores.google.genai_extension as genaix
import google.ai.generativelanguage as genai
except ImportError:
raise ImportError(_import_err_msg)
client = cast(genai.GenerativeServiceClient, self._client)
response = genaix.generate_answer(
prompt=query_str,
passages=list(text_chunks),
answer_style=self._answer_style,
safety_settings=self._safety_setting,
temperature=self._temperature,
client=client,
)
return SynthesizedResponse(
answer=response.answer,
attributed_passages=[
passage.text for passage in response.attributed_passages
],
answerable_probability=response.answerable_probability,
)
async def aget_response(
self,
query_str: str,
text_chunks: Sequence[str],
**response_kwargs: Any,
) -> RESPONSE_TEXT_TYPE:
# TODO: Implement a true async version.
return self.get_response(query_str, text_chunks, **response_kwargs)
def synthesize(
self,
query: QueryTextType,
nodes: List[NodeWithScore],
additional_source_nodes: Optional[Sequence[NodeWithScore]] = None,
**response_kwargs: Any,
) -> Response:
"""
Returns a grounded response based on provided passages.
Returns:
Response's `source_nodes` will begin with a list of attributed
passages. These passages are the ones that were used to construct
the grounded response. These passages will always have no score,
the only way to mark them as attributed passages. Then, the list
will follow with the originally provided passages, which will have
a score from the retrieval.
Response's `metadata` may also have have an entry with key
`answerable_probability`, which is the model's estimate of the
probability that its answer is correct and grounded in the input
passages.
"""
if len(nodes) == 0:
return Response("Empty Response")
if isinstance(query, str):
query = QueryBundle(query_str=query)
with self._callback_manager.event(
CBEventType.SYNTHESIZE, payload={EventPayload.QUERY_STR: query.query_str}
) as event:
internal_response = self.get_response(
query_str=query.query_str,
text_chunks=[
n.node.get_content(metadata_mode=MetadataMode.LLM) for n in nodes
],
**response_kwargs,
)
additional_source_nodes = list(additional_source_nodes or [])
external_response = self._prepare_external_response(
internal_response, nodes + additional_source_nodes
)
event.on_end(payload={EventPayload.RESPONSE: external_response})
return external_response
async def asynthesize(
self,
query: QueryTextType,
nodes: List[NodeWithScore],
additional_source_nodes: Optional[Sequence[NodeWithScore]] = None,
**response_kwargs: Any,
) -> Response:
# TODO: Implement a true async version.
return self.synthesize(query, nodes, additional_source_nodes, **response_kwargs)
def _prepare_external_response(
self,
response: SynthesizedResponse,
source_nodes: List[NodeWithScore],
) -> Response:
return Response(
response=response.answer,
source_nodes=[
NodeWithScore(node=TextNode(text=passage))
for passage in response.attributed_passages
]
+ source_nodes,
metadata={
"answerable_probability": response.answerable_probability,
},
)
def _get_prompts(self) -> PromptDictType:
# Not used.
return {}
def _update_prompts(self, prompts_dict: PromptDictType) -> None:
# Not used.
...
| GoogleTextSynthesizer |
python | django__django | django/forms/fields.py | {
"start": 46291,
"end": 46614
} | class ____(CharField):
default_validators = [validators.validate_slug]
def __init__(self, *, allow_unicode=False, **kwargs):
self.allow_unicode = allow_unicode
if self.allow_unicode:
self.default_validators = [validators.validate_unicode_slug]
super().__init__(**kwargs)
| SlugField |
python | google__jax | tests/pallas/pallas_jumble_test.py | {
"start": 2508,
"end": 10803
} | class ____(PallasBaseTest):
def test_vmap_jumble_over_sin_kernel(self):
if not jtu.test_device_matches(["tpu"]):
self.skipTest("Only tested on TPU")
row_count = 8
col_grid_size = 5
ragged_shape = [3, 1, 4]
sizes = lax.convert_element_type(
jnp.array([128 * x for x in ragged_shape]),
core.bint(col_grid_size * 128),
)
x = jax.vmap(
lambda n: jnp.ones((row_count, n)), out_axes=batching.jumble_axis
)(sizes)
def kernel(x_ref, o_ref):
o_ref[...] = jnp.sin(x_ref[...])
def invoke_kernel(x):
return pl.pallas_call(
kernel,
in_specs=[pl.BlockSpec((8, 128), lambda j, k: (j, k))],
out_specs=pl.BlockSpec((8, 128), lambda j, k: (j, k)),
out_shape=jax.ShapeDtypeStruct(
(8, col_grid_size * 128), dtype=jnp.float32
),
grid=(1, col_grid_size),
interpret=self.INTERPRET,
# See note - on zero filling counterfactuals
debug=True,
)(x)
res = jax.vmap(
invoke_kernel,
out_axes=batching.jumble_axis,
in_axes=batching.jumble_axis,
axis_size=3,
)(x)
ref = jax.vmap(
jnp.sin,
out_axes=batching.jumble_axis,
in_axes=batching.jumble_axis,
axis_size=3,
)(x)
_assert_ragged_equal_with_elementwise_mask(
row_count, col_grid_size, ragged_shape, res.data, ref.data
)
def test_vmap_jumble_over_add_kernel(self):
if not jtu.test_device_matches(["tpu"]):
self.skipTest("Only tested on TPU")
row_count = 8
col_grid_size = 5
ragged_shape = [3, 1, 4]
sizes = lax.convert_element_type(
jnp.array([128 * x for x in ragged_shape]),
core.bint(col_grid_size * 128),
)
x = jax.vmap(
lambda n: jnp.ones((row_count, n)), out_axes=batching.jumble_axis
)(sizes)
y = jax.vmap(
lambda n: jnp.ones((row_count, n)), out_axes=batching.jumble_axis
)(sizes)
def kernel(x_ref, y_ref, o_ref):
o_ref[...] = x_ref[...] + y_ref[...]
def invoke_kernel(x, y):
return pl.pallas_call(
kernel,
in_specs=[
pl.BlockSpec((8, 128), lambda j, k: (j, k)),
pl.BlockSpec((8, 128), lambda j, k: (j, k)),
],
out_specs=pl.BlockSpec((8, 128), lambda j, k: (j, k)),
out_shape=jax.ShapeDtypeStruct(
(8, col_grid_size * 128), dtype=jnp.float32
),
grid=(1, col_grid_size),
interpret=self.INTERPRET,
)(x, y)
# We've had this test fail with data corruption due to multiple
# invocations, so we run it k times to make sure it's not setting up
# memory incorrectly for subsequent invocations.
for _ in range(4):
res = jax.vmap(
invoke_kernel,
out_axes=batching.jumble_axis,
in_axes=batching.jumble_axis,
axis_size=3,
)(x, y)
res = res.data
total = len(ragged_shape) * row_count * col_grid_size * 128
res_total = np.prod(res.shape)
self.assertEqual(res_total, total)
ref = jax.vmap(
lambda x, y: x + y,
out_axes=batching.jumble_axis,
in_axes=batching.jumble_axis,
axis_size=3,
)(x, y)
_assert_ragged_equal_with_elementwise_mask(
row_count, col_grid_size, ragged_shape, res, ref.data
)
def test_vmap_jumble_over_sin_kernel_grid_remapping(self):
if not jtu.test_device_matches(["tpu"]):
self.skipTest("Only tested on TPU")
row_count = 8
col_grid_size = 5
ragged_shape = [3, 1, 4]
sizes = lax.convert_element_type(
jnp.array([128 * x for x in ragged_shape]),
core.bint(col_grid_size * 128),
)
x = jax.vmap(
lambda n: jnp.ones((row_count, n)), out_axes=batching.jumble_axis
)(sizes)
def kernel(x_ref, o_ref):
o_ref[...] = jnp.sin(x_ref[...]) * pl.program_id(2)
def invoke_kernel(x):
return pl.pallas_call(
kernel,
in_specs=[pl.BlockSpec((8, 128), lambda j, k: (j, k))],
out_specs=pl.BlockSpec((8, 128), lambda j, k: (j, k)),
out_shape=jax.ShapeDtypeStruct((8, 640), dtype=jnp.float32),
grid=(1, 5),
interpret=self.INTERPRET,
)(x)
with self.assertRaisesRegex(ValueError, "Axis 2 is out of bounds for grid"):
jax.vmap(
invoke_kernel,
out_axes=batching.jumble_axis,
in_axes=batching.jumble_axis,
axis_size=3,
)(x)
def test_vmap_jumble_over_matmul_kernel(self):
if not jtu.test_device_matches(["tpu"]):
self.skipTest("Only tested on TPU")
if jtu.is_device_tpu(version=4):
self.skipTest("Flaky 15% of the time on tpuv4?")
m = 128
k = 640
n = 640
def matmul_kernel(x_ref, y_ref, x_sentinel, z_ref):
# weird little once-only reset
@pl.when(x_sentinel[...][0][0] == 1.0)
def _():
z_ref[...] = jnp.zeros_like(z_ref)
x_sentinel[...] = jnp.zeros_like(x_sentinel)
z_ref[...] += x_ref[...] @ y_ref[...]
def matmul(
x: jax.Array,
y: jax.Array,
x_sentinel: jax.Array,
*,
bm: int = 128,
bk: int = 128,
bn: int = 640,
):
# m, k = x.shape
# _, n = y.shape
# a (1, 5) grid
# TODO(mvoz): parameterize this grid?
grid = (n // bn, k // bk)
return pl.pallas_call(
matmul_kernel,
out_shape=jax.ShapeDtypeStruct((m, n), jnp.float32),
in_specs=[
pl.BlockSpec(
(bm, bk),
lambda j, k: (0, k),
),
pl.BlockSpec(
(bk, bn),
lambda j, k: (k, j),
),
pl.BlockSpec(
(bm, bn),
lambda j, k: (0, j),
),
],
out_specs=pl.BlockSpec(
(bm, bn),
lambda j, k: (0, j),
),
grid=grid,
input_output_aliases={2: 0},
interpret=self.INTERPRET,
)(x, y, x_sentinel)
# TODO(mvoz): parameterize this shape?
ragged_shape = [3, 1, 4]
sizes = lax.convert_element_type(
jnp.array([128 * x for x in ragged_shape]),
core.bint(k),
)
x = jax.vmap(lambda k_: jnp.ones((m, k_)), out_axes=batching.jumble_axis)(
sizes
)
x_sentinel = jax.vmap(
lambda k_: jnp.ones((m, k_)), out_axes=batching.jumble_axis
)(sizes)
y = jax.vmap(lambda k_: jnp.ones((k_, n)), out_axes=batching.jumble_axis)(
sizes
)
res = jax.vmap(
matmul,
out_axes=batching.jumble_axis,
in_axes=batching.jumble_axis,
axis_size=3,
)(x, y, x_sentinel)
ref = jax.vmap(
jnp.dot,
out_axes=batching.jumble_axis,
in_axes=batching.jumble_axis,
axis_size=3,
)(x, y)
ref = ref.data
res = res.data
np.testing.assert_allclose(ref, res)
def test_vmap_jumble_ragged_boundary_unaligned_with_grid(self):
if not jtu.test_device_matches(["tpu"]):
self.skipTest("Only tested on TPU")
self.skipTest("Checkify NYI")
row_count = 8
col_grid_size = 5
ragged_shape = [3, 1, 4]
sizes = lax.convert_element_type(
jnp.array([(128 * x) - 1 for x in ragged_shape]),
core.bint(col_grid_size * 128),
)
x = jax.vmap(
lambda n: jnp.ones((row_count, n)), out_axes=batching.jumble_axis
)(sizes)
def kernel(x_ref, o_ref):
o_ref[...] = jnp.sin(x_ref[...])
def invoke_kernel(x):
return pl.pallas_call(
kernel,
in_specs=[pl.BlockSpec((8, 128), lambda j, k: (j, k))],
out_specs=pl.BlockSpec((8, 128), lambda j, k: (j, k)),
out_shape=jax.ShapeDtypeStruct((8, 640), dtype=jnp.float32),
grid=(1, 5),
interpret=False,
)(x)
with self.assertRaisesRegex(
ValueError,
"Ragged input shape must be evenly divisible by the grid" # noqa: W605
" size at the ragged dimension 2",
):
jax.vmap(
invoke_kernel,
out_axes=batching.jumble_axis,
in_axes=batching.jumble_axis,
axis_size=3,
)(x)
| PallasCallRaggedVmapTest |
python | pytorch__pytorch | test/test_legacy_vmap.py | {
"start": 447,
"end": 770
} | class ____:
def __enter__(self):
self.prev_state = torch._C._debug_only_are_vmap_fallback_warnings_enabled()
torch._C._debug_only_display_vmap_fallback_warnings(True)
def __exit__(self, *ignored):
torch._C._debug_only_display_vmap_fallback_warnings(self.prev_state)
| EnableVmapFallbackWarnings |
python | ray-project__ray | rllib/core/models/configs.py | {
"start": 13019,
"end": 16291
} | class ____(_MLPConfig):
"""Configuration for an MLPHead with a floating second half of outputs.
This model can be useful together with Gaussian Distributions.
This gaussian distribution would be conditioned as follows:
- The first half of outputs from this model can be used as
state-dependent means when conditioning a gaussian distribution
- The second half are floating free biases that can be used as
state-independent standard deviations to condition a gaussian distribution.
The mean values are produced by an MLPHead, while the standard
deviations are added as floating free biases from a single 1D trainable variable
(not dependent on the net's inputs).
The output dimensions of the configured MLPHeadConfig must be even and are
divided by two to gain the output dimensions of each the mean-net and the
free std-variable.
Example:
.. testcode::
:skipif: True
# Configuration:
config = FreeLogStdMLPHeadConfig(
input_dims=[2],
hidden_layer_dims=[16],
hidden_layer_activation=None,
hidden_layer_use_layernorm=False,
hidden_layer_use_bias=True,
output_layer_dim=8, # <- this must be an even size
output_layer_use_bias=True,
)
model = config.build(framework="tf2")
# Resulting stack in pseudocode:
# Linear(2, 16, bias=True)
# Linear(8, 8, bias=True) # 16 / 2 = 8 -> 8 nodes for the mean
# Extra variable:
# Tensor((8,), float32) # for the free (observation independent) std outputs
Example:
.. testcode::
:skipif: True
# Configuration:
config = FreeLogStdMLPHeadConfig(
input_dims=[2],
hidden_layer_dims=[31, 100], # <- last idx must be an even size
hidden_layer_activation="relu",
hidden_layer_use_layernorm=False,
hidden_layer_use_bias=False,
output_layer_dim=None, # use the last hidden layer as output layer
)
model = config.build(framework="torch")
# Resulting stack in pseudocode:
# Linear(2, 31, bias=False)
# ReLu()
# Linear(31, 50, bias=False) # 100 / 2 = 50 -> 50 nodes for the mean
# ReLu()
# Extra variable:
# Tensor((50,), float32) # for the free (observation independent) std outputs
"""
def _validate(self, framework: str = "torch"):
if len(self.output_dims) > 1 or self.output_dims[0] % 2 == 1:
raise ValueError(
f"`output_layer_dim` ({self.ouput_layer_dim}) or the last value in "
f"`hidden_layer_dims` ({self.hidden_layer_dims}) of a "
"FreeLogStdMLPHeadConfig must be an even int (dividable by 2), "
"e.g. `output_layer_dim=8` or `hidden_layer_dims=[133, 128]`!"
)
@_framework_implemented()
def build(self, framework: str = "torch") -> "Model":
self._validate(framework=framework)
if framework == "torch":
from ray.rllib.core.models.torch.heads import TorchFreeLogStdMLPHead
return TorchFreeLogStdMLPHead(self)
@ExperimentalAPI
@dataclass
| FreeLogStdMLPHeadConfig |
python | huggingface__transformers | src/transformers/models/falcon_mamba/modeling_falcon_mamba.py | {
"start": 2393,
"end": 7618
} | class ____:
"""
Cache for falcon_mamba model which does not have attention mechanism and key value states.
Arguments:
config (`PreTrainedConfig):
The configuration file defining the shape-related attributes required to initialize the static cache.
max_batch_size (`int`):
The maximum batch size with which the model will be used. Note that a new instance must be instantiated if
a smaller batch size is used.
dtype (`torch.dtype`, *optional*, defaults to `torch.float16`):
The default `dtype` to use when initializing the layer.
device (`torch.device` or `str`, *optional*):
The device on which the cache should be initialized. Should be the same as the layer.
Example:
```python
>>> import torch
>>> from transformers import AutoTokenizer, FalconMambaForCausalLM, FalconMambaCache
>>> model = FalconMambaForCausalLM.from_pretrained("tiiuae/falcon-mamba-7b")
>>> tokenizer = AutoTokenizer.from_pretrained("tiiuae/falcon-mamba-7b")
>>> inputs = tokenizer(text="My name is FalconMamba", return_tensors="pt")
>>> # Prepare a cache class and pass it to model's forward
>>> cache_params = FalconMambaCache(config=model.config, max_batch_size=1, device=model.device, dtype=model.dtype)
>>> cache_position = torch.arange(len(inputs["input_ids"][0]), device=model.device) # sequence length
>>> outputs = model(**inputs, cache_params=cache_params, cache_position=cache_position, use_cache=True)
>>> outputs.cache_params
```
"""
is_compileable = True
# TODO (joao): add layer_device_map arg and update code in `generate` accordingly
def __init__(
self,
config: PreTrainedConfig,
max_batch_size: int,
dtype: torch.dtype = torch.float16,
device: Union[torch.device, str, None] = None,
):
self.max_batch_size = max_batch_size
self._dtype = dtype
self.intermediate_size = config.intermediate_size
self.ssm_state_size = config.state_size
self.conv_kernel_size = config.conv_kernel
self.conv_states: list[torch.Tensor] = []
self.ssm_states: list[torch.Tensor] = []
device = torch.device(device) if device is not None else None
for _ in range(config.num_hidden_layers):
conv_state: torch.Tensor = torch.zeros(
self.max_batch_size,
self.intermediate_size,
self.conv_kernel_size,
device=device,
dtype=self._dtype,
)
ssm_state: torch.Tensor = torch.zeros(
self.max_batch_size,
self.intermediate_size,
self.ssm_state_size,
device=device,
dtype=self._dtype,
)
torch._dynamo.mark_static_address(conv_state)
torch._dynamo.mark_static_address(ssm_state)
self.conv_states.append(conv_state)
self.ssm_states.append(ssm_state)
def update_conv_state(
self, layer_idx: int, new_conv_state: torch.Tensor, cache_position: torch.LongTensor
) -> torch.Tensor:
# This `if` blocks is only reached in multigpu and if `layer_device_map` is not passed. It is used
# when the cache is initialized in the forward pass (e.g. FalconMamba)
if self.conv_states[layer_idx].device != new_conv_state.device:
self.conv_states[layer_idx] = self.conv_states[layer_idx].to(new_conv_state.device)
conv_state = self.conv_states[layer_idx]
cache_position = cache_position.clamp(0, self.conv_kernel_size - 1)
conv_state = conv_state.roll(shifts=-1, dims=-1)
conv_state[:, :, cache_position] = new_conv_state.to(device=conv_state.device, dtype=conv_state.dtype)
self.conv_states[layer_idx].zero_()
self.conv_states[layer_idx] += conv_state
return self.conv_states[layer_idx]
def update_ssm_state(self, layer_idx: int, new_ssm_state: torch.Tensor):
self.ssm_states[layer_idx].zero_()
self.ssm_states[layer_idx] += new_ssm_state.to(self.ssm_states[layer_idx].device)
return self.ssm_states[layer_idx]
def reset(self):
for layer_idx in range(len(self.conv_states)):
# In-place ops prevent breaking the static address
self.conv_states[layer_idx].zero_()
self.ssm_states[layer_idx].zero_()
def rms_forward(hidden_states, variance_epsilon=1e-6):
"""
Calculates simple RMSNorm with no learnable weights. `MambaRMSNorm` will
leverage this in order to multiply the final result with the RMSNorm weight
Args:
hidden_states (`torch.Tensor`):
Hidden states to normalize
variance_epsilon (`float`):
The eps value to add in the square root scaling factor
"""
input_dtype = hidden_states.dtype
hidden_states = hidden_states.to(torch.float32)
variance = hidden_states.pow(2).mean(-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + variance_epsilon)
return hidden_states.to(input_dtype)
| FalconMambaCache |
python | PyCQA__pylint | tests/functional/ext/docparams/return/missing_return_doc_Google.py | {
"start": 2492,
"end": 2818
} | class ____:
"""test_ignores_return_in_abstract_method_google_2
Example of a method documenting the return type that an
implementation should return.
"""
def foo_method(self, arg):
"""docstring ...
Args:
arg (int): An argument.
"""
raise NotImplementedError()
| Foo |
python | euske__pdfminer | pdfminer/lzw.py | {
"start": 47,
"end": 111
} | class ____(Exception):
pass
## LZWDecoder
##
| CorruptDataError |
python | celery__celery | t/unit/app/test_beat.py | {
"start": 5115,
"end": 22906
} | class ____:
def test_custom_schedule_dict(self):
custom = {'foo': 'bar'}
scheduler = mScheduler(app=self.app, schedule=custom, lazy=True)
assert scheduler.data is custom
def test_apply_async_uses_registered_task_instances(self):
@self.app.task(shared=False)
def foo():
pass
foo.apply_async = Mock(name='foo.apply_async')
assert foo.name in foo._get_app().tasks
scheduler = mScheduler(app=self.app)
scheduler.apply_async(scheduler.Entry(task=foo.name, app=self.app))
foo.apply_async.assert_called()
def test_apply_async_with_null_args(self):
@self.app.task(shared=False)
def foo():
pass
foo.apply_async = Mock(name='foo.apply_async')
scheduler = mScheduler(app=self.app)
scheduler.apply_async(
scheduler.Entry(
task=foo.name, app=self.app, args=None, kwargs=None))
foo.apply_async.assert_called()
def test_apply_async_with_null_args_set_to_none(self):
@self.app.task(shared=False)
def foo():
pass
foo.apply_async = Mock(name='foo.apply_async')
scheduler = mScheduler(app=self.app)
entry = scheduler.Entry(task=foo.name, app=self.app, args=None,
kwargs=None)
entry.args = None
entry.kwargs = None
scheduler.apply_async(entry, advance=False)
foo.apply_async.assert_called()
def test_apply_async_without_null_args(self):
@self.app.task(shared=False)
def foo(moo: int):
return moo
foo.apply_async = Mock(name='foo.apply_async')
scheduler = mScheduler(app=self.app)
entry = scheduler.Entry(task=foo.name, app=self.app, args=None,
kwargs=None)
entry.args = (101,)
entry.kwargs = None
scheduler.apply_async(entry, advance=False)
foo.apply_async.assert_called()
assert foo.apply_async.call_args[0][0] == [101]
def test_should_sync(self):
@self.app.task(shared=False)
def not_sync():
pass
not_sync.apply_async = Mock()
s = mScheduler(app=self.app)
s._do_sync = Mock()
s.should_sync = Mock()
s.should_sync.return_value = True
s.apply_async(s.Entry(task=not_sync.name, app=self.app))
s._do_sync.assert_called_with()
s._do_sync = Mock()
s.should_sync.return_value = False
s.apply_async(s.Entry(task=not_sync.name, app=self.app))
s._do_sync.assert_not_called()
def test_should_sync_increments_sync_every_counter(self):
self.app.conf.beat_sync_every = 2
@self.app.task(shared=False)
def not_sync():
pass
not_sync.apply_async = Mock()
s = mScheduler(app=self.app)
assert s.sync_every_tasks == 2
s._do_sync = Mock()
s.apply_async(s.Entry(task=not_sync.name, app=self.app))
assert s._tasks_since_sync == 1
s.apply_async(s.Entry(task=not_sync.name, app=self.app))
s._do_sync.assert_called_with()
self.app.conf.beat_sync_every = 0
def test_sync_task_counter_resets_on_do_sync(self):
self.app.conf.beat_sync_every = 1
@self.app.task(shared=False)
def not_sync():
pass
not_sync.apply_async = Mock()
s = mScheduler(app=self.app)
assert s.sync_every_tasks == 1
s.apply_async(s.Entry(task=not_sync.name, app=self.app))
assert s._tasks_since_sync == 0
self.app.conf.beat_sync_every = 0
@patch('celery.app.base.Celery.send_task')
def test_send_task(self, send_task):
b = beat.Scheduler(app=self.app)
b.send_task('tasks.add', countdown=10)
send_task.assert_called_with('tasks.add', countdown=10)
def test_info(self):
scheduler = mScheduler(app=self.app)
assert isinstance(scheduler.info, str)
def test_apply_entry_handles_empty_result(self):
s = mScheduler(app=self.app)
entry = s.Entry(name='a name', task='foo', app=self.app)
with patch.object(s, 'apply_async') as mock_apply_async:
with patch("celery.beat.debug") as mock_debug:
mock_apply_async.return_value = None
s.apply_entry(entry)
mock_debug.assert_called_once_with('%s sent.', entry.task)
with patch.object(s, 'apply_async') as mock_apply_async:
with patch("celery.beat.debug") as mock_debug:
mock_apply_async.return_value = object()
s.apply_entry(entry)
mock_debug.assert_called_once_with('%s sent.', entry.task)
task_id = 'taskId123456'
with patch.object(s, 'apply_async') as mock_apply_async:
with patch("celery.beat.debug") as mock_debug:
mock_apply_async.return_value = self.app.AsyncResult(task_id)
s.apply_entry(entry)
mock_debug.assert_called_once_with('%s sent. id->%s', entry.task, task_id)
def test_maybe_entry(self):
s = mScheduler(app=self.app)
entry = s.Entry(name='add every', task='tasks.add', app=self.app)
assert s._maybe_entry(entry.name, entry) is entry
assert s._maybe_entry('add every', {'task': 'tasks.add'})
def test_set_schedule(self):
s = mScheduler(app=self.app)
s.schedule = {'foo': 'bar'}
assert s.data == {'foo': 'bar'}
@patch('kombu.connection.Connection.ensure_connection')
def test_ensure_connection_error_handler(self, ensure):
s = mScheduler(app=self.app)
assert s._ensure_connected()
ensure.assert_called()
callback = ensure.call_args[0][0]
callback(KeyError(), 5)
def test_install_default_entries(self):
self.app.conf.result_expires = None
self.app.conf.beat_schedule = {}
s = mScheduler(app=self.app)
s.install_default_entries({})
assert 'celery.backend_cleanup' not in s.data
self.app.backend.supports_autoexpire = False
self.app.conf.result_expires = 30
s = mScheduler(app=self.app)
s.install_default_entries({})
assert 'celery.backend_cleanup' in s.data
self.app.backend.supports_autoexpire = True
self.app.conf.result_expires = 31
s = mScheduler(app=self.app)
s.install_default_entries({})
assert 'celery.backend_cleanup' not in s.data
def test_due_tick(self):
scheduler = mScheduler(app=self.app)
scheduler.add(name='test_due_tick',
schedule=always_due,
args=(1, 2),
kwargs={'foo': 'bar'})
assert scheduler.tick() == 0
@patch('celery.beat.error')
def test_due_tick_SchedulingError(self, error):
scheduler = mSchedulerSchedulingError(app=self.app)
scheduler.add(name='test_due_tick_SchedulingError',
schedule=always_due)
assert scheduler.tick() == 0
error.assert_called()
def test_pending_tick(self):
scheduler = mScheduler(app=self.app)
scheduler.add(name='test_pending_tick',
schedule=always_pending)
assert scheduler.tick() == 1 - 0.010
def test_pending_left_10_milliseconds_tick(self):
scheduler = mScheduler(app=self.app)
scheduler.add(name='test_pending_left_10_milliseconds_tick',
schedule=always_pending_left_10_milliseconds)
assert scheduler.tick() == 0.010 - 0.010
def test_honors_max_interval(self):
scheduler = mScheduler(app=self.app)
maxi = scheduler.max_interval
scheduler.add(name='test_honors_max_interval',
schedule=mocked_schedule(False, maxi * 4))
assert scheduler.tick() == maxi
def test_ticks(self):
scheduler = mScheduler(app=self.app)
nums = [600, 300, 650, 120, 250, 36]
s = {'test_ticks%s' % i: {'schedule': mocked_schedule(False, j)}
for i, j in enumerate(nums)}
scheduler.update_from_dict(s)
assert scheduler.tick() == min(nums) - 0.010
def test_ticks_microseconds(self):
scheduler = mScheduler(app=self.app)
now_ts = 1514797200.2
now = datetime.utcfromtimestamp(now_ts)
schedule_half = schedule(timedelta(seconds=0.5), nowfun=lambda: now)
scheduler.add(name='half_second_schedule', schedule=schedule_half)
scheduler.tick()
# ensure those 0.2 seconds on now_ts don't get dropped
expected_time = now_ts + 0.5 - 0.010
assert scheduler._heap[0].time == expected_time
def test_ticks_schedule_change(self):
# initialise schedule and check heap is not initialized
scheduler = mScheduler(app=self.app)
assert scheduler._heap is None
# set initial schedule and check heap is updated
schedule_5 = schedule(5)
scheduler.add(name='test_schedule', schedule=schedule_5)
scheduler.tick()
assert scheduler._heap[0].entry.schedule == schedule_5
# update schedule and check heap is updated
schedule_10 = schedule(10)
scheduler.add(name='test_schedule', schedule=schedule(10))
scheduler.tick()
assert scheduler._heap[0].entry.schedule == schedule_10
def test_schedule_no_remain(self):
scheduler = mScheduler(app=self.app)
scheduler.add(name='test_schedule_no_remain',
schedule=mocked_schedule(False, None))
assert scheduler.tick() == scheduler.max_interval
def test_interface(self):
scheduler = mScheduler(app=self.app)
scheduler.sync()
scheduler.setup_schedule()
scheduler.close()
def test_merge_inplace(self):
a = mScheduler(app=self.app)
b = mScheduler(app=self.app)
a.update_from_dict({'foo': {'schedule': mocked_schedule(True, 10)},
'bar': {'schedule': mocked_schedule(True, 20)}})
b.update_from_dict({'bar': {'schedule': mocked_schedule(True, 40)},
'baz': {'schedule': mocked_schedule(True, 10)}})
a.merge_inplace(b.schedule)
assert 'foo' not in a.schedule
assert 'baz' in a.schedule
assert a.schedule['bar'].schedule._next_run_at == 40
def test_when(self):
now_time_utc = datetime(2000, 10, 10, 10, 10,
10, 10, tzinfo=ZoneInfo("UTC"))
now_time_casey = now_time_utc.astimezone(
ZoneInfo('Antarctica/Casey')
)
scheduler = mScheduler(app=self.app)
result_utc = scheduler._when(
mocked_schedule(True, 10, lambda: now_time_utc),
10
)
result_casey = scheduler._when(
mocked_schedule(True, 10, lambda: now_time_casey),
10
)
assert result_utc == result_casey
@patch('celery.beat.Scheduler._when', return_value=1)
def test_populate_heap(self, _when):
scheduler = mScheduler(app=self.app)
scheduler.update_from_dict(
{'foo': {'schedule': mocked_schedule(True, 10)}}
)
scheduler.populate_heap()
assert scheduler._heap == [event_t(1, 5, scheduler.schedule['foo'])]
def create_schedule_entry(self, schedule=None, args=(), kwargs={},
options={}, task=None):
entry = {
'name': 'celery.unittest.add',
'schedule': schedule,
'app': self.app,
'args': args,
'kwargs': kwargs,
'options': options,
'task': task
}
return beat.ScheduleEntry(**dict(entry))
def test_schedule_equal_schedule_vs_schedule_success(self):
scheduler = beat.Scheduler(app=self.app)
a = {'a': self.create_schedule_entry(schedule=schedule(5))}
b = {'a': self.create_schedule_entry(schedule=schedule(5))}
assert scheduler.schedules_equal(a, b)
def test_schedule_equal_schedule_vs_schedule_fail(self):
scheduler = beat.Scheduler(app=self.app)
a = {'a': self.create_schedule_entry(schedule=schedule(5))}
b = {'a': self.create_schedule_entry(schedule=schedule(10))}
assert not scheduler.schedules_equal(a, b)
def test_schedule_equal_crontab_vs_crontab_success(self):
scheduler = beat.Scheduler(app=self.app)
a = {'a': self.create_schedule_entry(schedule=crontab(minute=5))}
b = {'a': self.create_schedule_entry(schedule=crontab(minute=5))}
assert scheduler.schedules_equal(a, b)
def test_schedule_equal_crontab_vs_crontab_fail(self):
scheduler = beat.Scheduler(app=self.app)
a = {'a': self.create_schedule_entry(schedule=crontab(minute=5))}
b = {'a': self.create_schedule_entry(schedule=crontab(minute=10))}
assert not scheduler.schedules_equal(a, b)
def test_schedule_equal_crontab_vs_schedule_fail(self):
scheduler = beat.Scheduler(app=self.app)
a = {'a': self.create_schedule_entry(schedule=crontab(minute=5))}
b = {'a': self.create_schedule_entry(schedule=schedule(5))}
assert not scheduler.schedules_equal(a, b)
def test_schedule_equal_different_key_fail(self):
scheduler = beat.Scheduler(app=self.app)
a = {'a': self.create_schedule_entry(schedule=schedule(5))}
b = {'b': self.create_schedule_entry(schedule=schedule(5))}
assert not scheduler.schedules_equal(a, b)
def test_schedule_equal_args_vs_args_success(self):
scheduler = beat.Scheduler(app=self.app)
a = {'a': self.create_schedule_entry(args='a')}
b = {'a': self.create_schedule_entry(args='a')}
assert scheduler.schedules_equal(a, b)
def test_schedule_equal_args_vs_args_fail(self):
scheduler = beat.Scheduler(app=self.app)
a = {'a': self.create_schedule_entry(args='a')}
b = {'a': self.create_schedule_entry(args='b')}
assert not scheduler.schedules_equal(a, b)
def test_schedule_equal_kwargs_vs_kwargs_success(self):
scheduler = beat.Scheduler(app=self.app)
a = {'a': self.create_schedule_entry(kwargs={'a': 'a'})}
b = {'a': self.create_schedule_entry(kwargs={'a': 'a'})}
assert scheduler.schedules_equal(a, b)
def test_schedule_equal_kwargs_vs_kwargs_fail(self):
scheduler = beat.Scheduler(app=self.app)
a = {'a': self.create_schedule_entry(kwargs={'a': 'a'})}
b = {'a': self.create_schedule_entry(kwargs={'b': 'b'})}
assert not scheduler.schedules_equal(a, b)
def test_schedule_equal_options_vs_options_success(self):
scheduler = beat.Scheduler(app=self.app)
a = {'a': self.create_schedule_entry(options={'a': 'a'})}
b = {'a': self.create_schedule_entry(options={'a': 'a'})}
assert scheduler.schedules_equal(a, b)
def test_schedule_equal_options_vs_options_fail(self):
scheduler = beat.Scheduler(app=self.app)
a = {'a': self.create_schedule_entry(options={'a': 'a'})}
b = {'a': self.create_schedule_entry(options={'b': 'b'})}
assert not scheduler.schedules_equal(a, b)
def test_schedule_equal_task_vs_task_success(self):
scheduler = beat.Scheduler(app=self.app)
a = {'a': self.create_schedule_entry(task='a')}
b = {'a': self.create_schedule_entry(task='a')}
assert scheduler.schedules_equal(a, b)
def test_schedule_equal_task_vs_task_fail(self):
scheduler = beat.Scheduler(app=self.app)
a = {'a': self.create_schedule_entry(task='a')}
b = {'a': self.create_schedule_entry(task='b')}
assert not scheduler.schedules_equal(a, b)
def test_schedule_equal_none_entry_vs_entry(self):
scheduler = beat.Scheduler(app=self.app)
a = None
b = {'a': self.create_schedule_entry(task='b')}
assert not scheduler.schedules_equal(a, b)
def test_schedule_equal_entry_vs_none_entry(self):
scheduler = beat.Scheduler(app=self.app)
a = {'a': self.create_schedule_entry(task='a')}
b = None
assert not scheduler.schedules_equal(a, b)
def test_schedule_equal_none_entry_vs_none_entry(self):
scheduler = beat.Scheduler(app=self.app)
a = None
b = None
assert scheduler.schedules_equal(a, b)
def create_persistent_scheduler(shelv=None):
if shelv is None:
shelv = MockShelve()
class MockPersistentScheduler(beat.PersistentScheduler):
sh = shelv
persistence = Bunch(
open=lambda *a, **kw: shelv,
)
tick_raises_exit = False
shutdown_service = None
def tick(self):
if self.tick_raises_exit:
raise SystemExit()
if self.shutdown_service:
self.shutdown_service._is_shutdown.set()
return 0.0
return MockPersistentScheduler, shelv
def create_persistent_scheduler_w_call_logging(shelv=None):
if shelv is None:
shelv = MockShelve()
class MockPersistentScheduler(beat.PersistentScheduler):
sh = shelv
persistence = Bunch(
open=lambda *a, **kw: shelv,
)
def __init__(self, *args, **kwargs):
self.sent = []
super().__init__(*args, **kwargs)
def send_task(self, task=None, args=None, kwargs=None, **options):
self.sent.append({'task': task,
'args': args,
'kwargs': kwargs,
'options': options})
return self.app.AsyncResult(uuid())
return MockPersistentScheduler, shelv
| test_Scheduler |
python | tornadoweb__tornado | tornado/web.py | {
"start": 131688,
"end": 133957
} | class ____:
"""A re-usable, modular UI unit on a page.
UI modules often execute additional queries, and they can include
additional CSS and JavaScript that will be included in the output
page, which is automatically inserted on page render.
Subclasses of UIModule must override the `render` method.
"""
def __init__(self, handler: RequestHandler) -> None:
self.handler = handler
self.request = handler.request
self.ui = handler.ui
self.locale = handler.locale
@property
def current_user(self) -> Any:
return self.handler.current_user
def render(self, *args: Any, **kwargs: Any) -> Union[str, bytes]:
"""Override in subclasses to return this module's output."""
raise NotImplementedError()
def embedded_javascript(self) -> Optional[str]:
"""Override to return a JavaScript string
to be embedded in the page."""
return None
def javascript_files(self) -> Optional[Iterable[str]]:
"""Override to return a list of JavaScript files needed by this module.
If the return values are relative paths, they will be passed to
`RequestHandler.static_url`; otherwise they will be used as-is.
"""
return None
def embedded_css(self) -> Optional[str]:
"""Override to return a CSS string
that will be embedded in the page."""
return None
def css_files(self) -> Optional[Iterable[str]]:
"""Override to returns a list of CSS files required by this module.
If the return values are relative paths, they will be passed to
`RequestHandler.static_url`; otherwise they will be used as-is.
"""
return None
def html_head(self) -> Optional[str]:
"""Override to return an HTML string that will be put in the <head/>
element.
"""
return None
def html_body(self) -> Optional[str]:
"""Override to return an HTML string that will be put at the end of
the <body/> element.
"""
return None
def render_string(self, path: str, **kwargs: Any) -> bytes:
"""Renders a template and returns it as a string."""
return self.handler.render_string(path, **kwargs)
| UIModule |
python | PyCQA__pylint | tests/test_self.py | {
"start": 2101,
"end": 3307
} | class ____(BaseReporter):
def __init__(self, reporters: list[BaseReporter]) -> None:
# pylint: disable=super-init-not-called
# We don't call it because there is an attribute "linter" that is set inside the base class,
# and we have another setter here using yet undefined attribute.
# I don't think fixing the init order in a test class used once is worth it.
self._reporters = reporters
self.path_strip_prefix = os.getcwd() + os.sep
def on_set_current_module(self, module: str, filepath: str | None) -> None:
for rep in self._reporters:
rep.on_set_current_module(module, filepath)
def handle_message(self, msg: Message) -> None:
for rep in self._reporters:
rep.handle_message(msg)
def _display(self, layout: Section) -> None:
pass
@property
def out(self) -> TextIO: # type: ignore[override]
return self._reporters[0].out
@property
def linter(self) -> PyLinter:
return self._linter
@linter.setter
def linter(self, value: PyLinter) -> None:
self._linter = value
for rep in self._reporters:
rep.linter = value
| MultiReporter |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/constructors.py | {
"start": 4869,
"end": 4959
} | class ____:
def __init__(self, foo, baz):
self.foo = foo
| SanitizeTaintInTaintOut |
python | ray-project__ray | python/ray/tune/experimental/output.py | {
"start": 6615,
"end": 16696
} | class ____:
header: List[str]
data: List[_PerStatusTrialTableData]
def _max_len(value: Any, max_len: int = 20, wrap: bool = False) -> Any:
"""Abbreviate a string representation of an object to `max_len` characters.
For numbers, booleans and None, the original value will be returned for
correct rendering in the table formatting tool.
Args:
value: Object to be represented as a string.
max_len: Maximum return string length.
"""
if value is None or isinstance(value, (int, float, numbers.Number, bool)):
return value
string = str(value)
if len(string) <= max_len:
return string
if wrap:
# Maximum two rows.
# Todo: Make this configurable in the refactor
if len(value) > max_len * 2:
value = "..." + string[(3 - (max_len * 2)) :]
wrapped = textwrap.wrap(value, width=max_len)
return "\n".join(wrapped)
result = "..." + string[(3 - max_len) :]
return result
def _get_trial_info(
trial: Trial, param_keys: List[str], metric_keys: List[str]
) -> List[str]:
"""Returns the following information about a trial:
name | status | metrics...
Args:
trial: Trial to get information for.
param_keys: Names of parameters to include.
metric_keys: Names of metrics to include.
"""
result = trial.last_result
trial_info = [str(trial), trial.status]
# params
trial_info.extend(
[
_max_len(
unflattened_lookup(param, trial.config, default=None),
)
for param in param_keys
]
)
# metrics
trial_info.extend(
[
_max_len(
unflattened_lookup(metric, result, default=None),
)
for metric in metric_keys
]
)
return trial_info
def _get_trial_table_data_per_status(
status: str,
trials: List[Trial],
param_keys: List[str],
metric_keys: List[str],
force_max_rows: bool = False,
) -> Optional[_PerStatusTrialTableData]:
"""Gather all information of trials pertained to one `status`.
Args:
status: The trial status of interest.
trials: all the trials of that status.
param_keys: *Ordered* list of parameters to be displayed in the table.
metric_keys: *Ordered* list of metrics to be displayed in the table.
Including both default and user defined.
force_max_rows: Whether or not to enforce a max row number for this status.
If True, only a max of `5` rows will be shown.
Returns:
All information of trials pertained to the `status`.
"""
# TODO: configure it.
max_row = 5 if force_max_rows else math.inf
if not trials:
return None
trial_infos = list()
more_info = None
for t in trials:
if len(trial_infos) >= max_row:
remaining = len(trials) - max_row
more_info = f"{remaining} more {status}"
break
trial_infos.append(_get_trial_info(t, param_keys, metric_keys))
return _PerStatusTrialTableData(trial_infos, more_info)
def _get_trial_table_data(
trials: List[Trial],
param_keys: List[str],
metric_keys: List[str],
all_rows: bool = False,
wrap_headers: bool = False,
) -> _TrialTableData:
"""Generate a table showing the current progress of tuning trials.
Args:
trials: List of trials for which progress is to be shown.
param_keys: Ordered list of parameters to be displayed in the table.
metric_keys: Ordered list of metrics to be displayed in the table.
Including both default and user defined.
Will only be shown if at least one trial is having the key.
all_rows: Force to show all rows.
wrap_headers: If True, header columns can be wrapped with ``\n``.
Returns:
Trial table data, including header and trial table per each status.
"""
# TODO: configure
max_trial_num_to_show = 20
max_column_length = 20
trials_by_state = _get_trials_by_state(trials)
# get the right metric to show.
metric_keys = [
k
for k in metric_keys
if any(
unflattened_lookup(k, t.last_result, default=None) is not None
for t in trials
)
]
# get header from metric keys
formatted_metric_columns = [
_max_len(k, max_len=max_column_length, wrap=wrap_headers) for k in metric_keys
]
formatted_param_columns = [
_max_len(k, max_len=max_column_length, wrap=wrap_headers) for k in param_keys
]
metric_header = [
DEFAULT_COLUMNS[metric] if metric in DEFAULT_COLUMNS else formatted
for metric, formatted in zip(metric_keys, formatted_metric_columns)
]
param_header = formatted_param_columns
# Map to the abbreviated version if necessary.
header = ["Trial name", "status"] + param_header + metric_header
trial_data = list()
for t_status in ORDER:
trial_data_per_status = _get_trial_table_data_per_status(
t_status,
trials_by_state[t_status],
param_keys=param_keys,
metric_keys=metric_keys,
force_max_rows=not all_rows and len(trials) > max_trial_num_to_show,
)
if trial_data_per_status:
trial_data.append(trial_data_per_status)
return _TrialTableData(header, trial_data)
def _best_trial_str(
trial: Trial,
metric: str,
):
"""Returns a readable message stating the current best trial."""
# returns something like
# Current best trial: 18ae7_00005 with loss=0.5918508041056858 and params={'train_loop_config': {'lr': 0.059253447253394785}}. # noqa
val = unflattened_lookup(metric, trial.last_result, default=None)
config = trial.last_result.get("config", {})
parameter_columns = list(config.keys())
params = {p: unflattened_lookup(p, config) for p in parameter_columns}
return (
f"Current best trial: {trial.trial_id} with {metric}={val} and "
f"params={params}"
)
def _render_table_item(
key: str, item: Any, prefix: str = ""
) -> Iterable[Tuple[str, str]]:
key = prefix + key
if isinstance(item, argparse.Namespace):
item = item.__dict__
if isinstance(item, float):
# tabulate does not work well with mixed-type columns, so we format
# numbers ourselves.
yield key, f"{item:.5f}".rstrip("0")
elif isinstance(item, dict):
flattened = flatten_dict(item)
for k, v in sorted(flattened.items()):
yield key + "/" + str(k), _max_len(v)
else:
yield key, _max_len(item, 20)
def _get_dict_as_table_data(
data: Dict,
include: Optional[Collection] = None,
exclude: Optional[Collection] = None,
upper_keys: Optional[Collection] = None,
):
"""Get ``data`` dict as table rows.
If specified, excluded keys are removed. Excluded keys can either be
fully specified (e.g. ``foo/bar/baz``) or specify a top-level dictionary
(e.g. ``foo``), but no intermediate levels (e.g. ``foo/bar``). If this is
needed, we can revisit the logic at a later point.
The same is true for included keys. If a top-level key is included (e.g. ``foo``)
then all sub keys will be included, too, except if they are excluded.
If keys are both excluded and included, exclusion takes precedence. Thus, if
``foo`` is excluded but ``foo/bar`` is included, it won't show up in the output.
"""
include = include or set()
exclude = exclude or set()
upper_keys = upper_keys or set()
upper = []
lower = []
for key, value in sorted(data.items()):
# Exclude top-level keys
if key in exclude:
continue
for k, v in _render_table_item(str(key), value):
# k is now the full subkey, e.g. config/nested/key
# We can exclude the full key
if k in exclude:
continue
# If we specify includes, top-level includes should take precedence
# (e.g. if `config` is in include, include config always).
if include and key not in include and k not in include:
continue
if key in upper_keys:
upper.append([k, v])
else:
lower.append([k, v])
if not upper:
return lower
elif not lower:
return upper
else:
return upper + lower
if sys.stdout and sys.stdout.encoding and sys.stdout.encoding.startswith("utf"):
# Copied/adjusted from tabulate
AIR_TABULATE_TABLEFMT = TableFormat(
lineabove=Line("â•", "─", "─", "â•®"),
linebelowheader=Line("├", "─", "─", "┤"),
linebetweenrows=None,
linebelow=Line("╰", "─", "─", "╯"),
headerrow=DataRow("│", " ", "│"),
datarow=DataRow("│", " ", "│"),
padding=1,
with_header_hide=None,
)
else:
# For non-utf output, use ascii-compatible characters.
# This prevents errors e.g. when legacy windows encoding is used.
AIR_TABULATE_TABLEFMT = TableFormat(
lineabove=Line("+", "-", "-", "+"),
linebelowheader=Line("+", "-", "-", "+"),
linebetweenrows=None,
linebelow=Line("+", "-", "-", "+"),
headerrow=DataRow("|", " ", "|"),
datarow=DataRow("|", " ", "|"),
padding=1,
with_header_hide=None,
)
def _print_dict_as_table(
data: Dict,
header: Optional[str] = None,
include: Optional[Collection[str]] = None,
exclude: Optional[Collection[str]] = None,
division: Optional[Collection[str]] = None,
):
table_data = _get_dict_as_table_data(
data=data, include=include, exclude=exclude, upper_keys=division
)
headers = [header, ""] if header else []
if not table_data:
return
print(
tabulate(
table_data,
headers=headers,
colalign=("left", "right"),
tablefmt=AIR_TABULATE_TABLEFMT,
)
)
| _TrialTableData |
python | davidhalter__jedi | test/run.py | {
"start": 9732,
"end": 18071
} | class ____(BaseTestCase):
"""
Static Analysis cases lie in the static_analysis folder.
The tests also start with `#!`, like the inference tests.
"""
def __init__(self, path):
self._path = path
self.name = os.path.basename(path)
with open(path) as f:
self._source = f.read()
skip_version_info = None
for line in self._source.splitlines():
skip_version_info = skip_python_version(line) or skip_version_info
super().__init__(skip_version_info)
def collect_comparison(self):
cases = []
for line_nr, line in enumerate(self._source.splitlines(), 1):
match = re.match(r'(\s*)#! (\d+ )?(.*)$', line)
if match is not None:
column = int(match.group(2) or 0) + len(match.group(1))
cases.append((line_nr + 1, column, match.group(3)))
return cases
def run(self, compare_cb, environment):
def typ_str(inst):
return 'warning ' if isinstance(inst, Warning) else ''
analysis = jedi.Script(
self._source,
path=self._path,
environment=environment,
)._analysis()
analysis = [(r.line, r.column, typ_str(r) + r.name)
for r in analysis]
compare_cb(self, analysis, self.collect_comparison())
def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, os.path.basename(self._path))
def skip_python_version(line):
# check for python minimal version number
match = re.match(r" *# *python *([<>]=?|==) *(\d+(?:\.\d+)?)$", line)
if match:
minimal_python_version = tuple(map(int, match.group(2).split(".")))
return minimal_python_version, match.group(1)
return None
def collect_file_tests(path, lines, lines_to_execute):
def makecase(t):
return IntegrationTestCase(t, correct, line_nr, column,
start, line, path=path,
skip_version_info=skip_version_info)
start = None
correct = None
test_type = None
skip_version_info = None
for line_nr, line in enumerate(lines, 1):
if correct is not None:
r = re.match(r'^(\d+)\s*(.*)$', correct)
if r:
column = int(r.group(1))
correct = r.group(2)
start += r.regs[2][0] # second group, start index
else:
column = len(line) - 1 # -1 for the \n
if test_type == '!':
yield makecase(TEST_GOTO)
elif test_type == '<':
yield makecase(TEST_REFERENCES)
elif correct.startswith('['):
yield makecase(TEST_COMPLETIONS)
else:
yield makecase(TEST_INFERENCE)
correct = None
else:
skip_version_info = skip_python_version(line) or skip_version_info
try:
r = re.search(r'(?:^|(?<=\s))#([?!<])\s*([^\n]*)', line)
# test_type is ? for completion and ! for goto
test_type = r.group(1)
correct = r.group(2)
# Quick hack to make everything work (not quite a bloody unicorn hack though).
if correct == '':
correct = ' '
start = r.start()
except AttributeError:
correct = None
else:
# Skip the test, if this is not specified test.
for l in lines_to_execute:
if isinstance(l, tuple) and l[0] <= line_nr <= l[1] \
or line_nr == l:
break
else:
if lines_to_execute:
correct = None
def collect_dir_tests(base_dir, test_files, check_thirdparty=False):
for f_name in os.listdir(base_dir):
files_to_execute = [a for a in test_files.items() if f_name.startswith(a[0])]
lines_to_execute = reduce(lambda x, y: x + y[1], files_to_execute, [])
if f_name.endswith(".py") and (not test_files or files_to_execute):
skip = None
if check_thirdparty:
lib = f_name.replace('_.py', '')
try:
# there is always an underline at the end.
# It looks like: completion/thirdparty/pylab_.py
__import__(lib)
except ImportError:
skip = 'Thirdparty-Library %s not found.' % lib
path = os.path.join(base_dir, f_name)
with open(path, newline='') as f:
source = f.read()
for case in collect_file_tests(path, StringIO(source),
lines_to_execute):
case.source = source
if skip:
case.set_skip(skip)
yield case
docoptstr = """
Using run.py to make debugging easier with integration tests.
An alternative testing format, which is much more hacky, but very nice to
work with.
Usage:
run.py [--pdb] [--debug] [--thirdparty] [--env <dotted>] [<rest>...]
run.py --help
Options:
-h --help Show this screen.
--pdb Enable pdb debugging on fail.
-d, --debug Enable text output debugging (please install ``colorama``).
--thirdparty Also run thirdparty tests (in ``completion/thirdparty``).
--env <dotted> A Python version, like 3.9, 3.8, etc.
"""
if __name__ == '__main__':
import docopt
arguments = docopt.docopt(docoptstr)
import time
t_start = time.time()
if arguments['--debug']:
jedi.set_debug_function()
# get test list, that should be executed
test_files = {}
last = None
for arg in arguments['<rest>']:
match = re.match(r'(\d+)-(\d+)', arg)
if match:
start, end = match.groups()
test_files[last].append((int(start), int(end)))
elif arg.isdigit():
if last is None:
continue
test_files[last].append(int(arg))
else:
test_files[arg] = []
last = arg
# completion tests:
dir_ = os.path.dirname(os.path.realpath(__file__))
completion_test_dir = os.path.join(dir_, '../test/completion')
completion_test_dir = os.path.abspath(completion_test_dir)
tests_fail = 0
# execute tests
cases = list(collect_dir_tests(completion_test_dir, test_files))
if test_files or arguments['--thirdparty']:
completion_test_dir += '/thirdparty'
cases += collect_dir_tests(completion_test_dir, test_files, True)
def file_change(current, tests, fails):
if current is None:
current = ''
else:
current = os.path.basename(current)
print('{:25} {} tests and {} fails.'.format(current, tests, fails))
def report(case, actual, desired):
if actual == desired:
return 0
else:
print("\ttest fail @%d, actual = %s, desired = %s"
% (case.line_nr - 1, actual, desired))
return 1
if arguments['--env']:
environment = get_system_environment(arguments['--env'])
else:
# Will be 3.13.
environment = get_default_environment()
import traceback
current = cases[0].path if cases else None
count = fails = 0
for c in cases:
if c.get_skip_reason(environment):
continue
if current != c.path:
file_change(current, count, fails)
current = c.path
count = fails = 0
try:
if c.run(report, environment):
tests_fail += 1
fails += 1
except Exception:
traceback.print_exc()
print("\ttest fail @%d" % (c.line_nr - 1))
tests_fail += 1
fails += 1
if arguments['--pdb']:
import pdb
pdb.post_mortem()
except Skipped:
pass
count += 1
file_change(current, count, fails)
print('\nSummary: (%s fails of %s tests) in %.3fs'
% (tests_fail, len(cases), time.time() - t_start))
exit_code = 1 if tests_fail else 0
sys.exit(exit_code)
| StaticAnalysisCase |
python | huggingface__transformers | src/transformers/models/vivit/modeling_vivit.py | {
"start": 1338,
"end": 3295
} | class ____(nn.Module):
"""
Construct Vivit Tubelet embeddings.
This module turns a batch of videos of shape (batch_size, num_frames, num_channels, height, width) into a tensor of
shape (batch_size, seq_len, hidden_size) to be consumed by a Transformer encoder.
The seq_len (the number of patches) equals (number of frames // tubelet_size[0]) * (height // tubelet_size[1]) *
(width // tubelet_size[2]).
"""
def __init__(self, config: VivitConfig):
super().__init__()
self.num_frames = config.num_frames
self.image_size = config.image_size
self.patch_size = config.tubelet_size
self.num_patches = (
(self.image_size // self.patch_size[2])
* (self.image_size // self.patch_size[1])
* (self.num_frames // self.patch_size[0])
)
self.embed_dim = config.hidden_size
self.projection = nn.Conv3d(
config.num_channels, config.hidden_size, kernel_size=config.tubelet_size, stride=config.tubelet_size
)
def forward(self, pixel_values: torch.Tensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
batch_size, num_frames, num_channels, height, width = pixel_values.shape
if not interpolate_pos_encoding and (height != self.image_size or width != self.image_size):
raise ValueError(
f"Image image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
)
# permute to (batch_size, num_channels, num_frames, height, width)
pixel_values = pixel_values.permute(0, 2, 1, 3, 4)
x = self.projection(pixel_values)
# out_batch_size, out_num_channels, out_num_frames, out_height, out_width = x.shape
# flattens time and space dimensions, transposes to (out_batch_size, flat_tokens, out_num_channels)
x = x.flatten(2).transpose(1, 2)
return x
| VivitTubeletEmbeddings |
python | jazzband__prettytable | src/prettytable/colortable.py | {
"start": 1161,
"end": 2477
} | class ____:
DEFAULT = Theme()
DYSLEXIA_FRIENDLY = Theme(
default_color="38;5;223",
vertical_color="38;5;22",
horizontal_color="38;5;22",
junction_color="38;5;58",
)
EARTH = Theme(
default_color="33",
vertical_color="38;5;94",
horizontal_color="38;5;22",
junction_color="38;5;130",
)
GLARE_REDUCTION = Theme(
default_color="38;5;252",
vertical_color="38;5;240",
horizontal_color="38;5;240",
junction_color="38;5;246",
)
HIGH_CONTRAST = Theme(
default_color="97",
vertical_color="91",
horizontal_color="94",
junction_color="93",
)
LAVENDER = Theme(
default_color="38;5;183",
vertical_color="35",
horizontal_color="38;5;147",
junction_color="38;5;219",
)
OCEAN = Theme(
default_color="96",
vertical_color="34",
horizontal_color="34",
junction_color="36",
)
OCEAN_DEEP = Theme(
default_color="96",
vertical_color="34",
horizontal_color="36",
junction_color="94",
)
PASTEL = Theme(
default_color="38;5;223",
vertical_color="38;5;152",
horizontal_color="38;5;187",
junction_color="38;5;157",
)
| Themes |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.