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 | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_step_function.py | {
"start": 1345,
"end": 3801
} | class ____:
def test_init(self):
sensor = StepFunctionExecutionSensor(
task_id=TASK_ID,
execution_arn=EXECUTION_ARN,
aws_conn_id=AWS_CONN_ID,
region_name=REGION_NAME,
verify=True,
botocore_config={"read_timeout": 42},
)
assert sensor.execution_arn == EXECUTION_ARN
assert sensor.hook.aws_conn_id == AWS_CONN_ID
assert sensor.hook._region_name == REGION_NAME
assert sensor.hook._verify is True
assert sensor.hook._config is not None
assert sensor.hook._config.read_timeout == 42
sensor = StepFunctionExecutionSensor(task_id=TASK_ID, execution_arn=EXECUTION_ARN)
assert sensor.hook.aws_conn_id == "aws_default"
assert sensor.hook._region_name is None
assert sensor.hook._verify is None
assert sensor.hook._config is None
@mock.patch.object(StepFunctionExecutionSensor, "hook")
@pytest.mark.parametrize("status", StepFunctionExecutionSensor.INTERMEDIATE_STATES)
def test_running(self, mocked_hook, status, mocked_context):
mocked_hook.describe_execution.return_value = {"status": status}
sensor = StepFunctionExecutionSensor(task_id=TASK_ID, execution_arn=EXECUTION_ARN, aws_conn_id=None)
assert sensor.poke(mocked_context) is False
@mock.patch.object(StepFunctionExecutionSensor, "hook")
@pytest.mark.parametrize("status", StepFunctionExecutionSensor.SUCCESS_STATES)
def test_succeeded(self, mocked_hook, status, mocked_context):
mocked_hook.describe_execution.return_value = {"status": status}
sensor = StepFunctionExecutionSensor(task_id=TASK_ID, execution_arn=EXECUTION_ARN, aws_conn_id=None)
assert sensor.poke(mocked_context) is True
@mock.patch.object(StepFunctionExecutionSensor, "hook")
@pytest.mark.parametrize("status", StepFunctionExecutionSensor.FAILURE_STATES)
def test_failure(self, mocked_hook, status, mocked_context):
output = {"test": "test"}
mocked_hook.describe_execution.return_value = {"status": status, "output": json.dumps(output)}
sensor = StepFunctionExecutionSensor(task_id=TASK_ID, execution_arn=EXECUTION_ARN, aws_conn_id=None)
message = f"Step Function sensor failed. State Machine Output: {output}"
with pytest.raises(AirflowException, match=message):
sensor.poke(mocked_context)
| TestStepFunctionExecutionSensor |
python | encode__django-rest-framework | tests/schemas/test_openapi.py | {
"start": 39907,
"end": 47853
} | class ____(TestCase):
def test_override_settings(self):
assert isinstance(views.ExampleListView.schema, AutoSchema)
def test_paths_construction(self):
"""Construction of the `paths` key."""
patterns = [
path('example/', views.ExampleListView.as_view()),
]
generator = SchemaGenerator(patterns=patterns)
generator._initialise_endpoints()
paths = generator.get_schema()["paths"]
assert '/example/' in paths
example_operations = paths['/example/']
assert len(example_operations) == 2
assert 'get' in example_operations
assert 'post' in example_operations
def test_prefixed_paths_construction(self):
"""Construction of the `paths` key maintains a common prefix."""
patterns = [
path('v1/example/', views.ExampleListView.as_view()),
path('v1/example/{pk}/', views.ExampleDetailView.as_view()),
]
generator = SchemaGenerator(patterns=patterns)
generator._initialise_endpoints()
paths = generator.get_schema()["paths"]
assert '/v1/example/' in paths
assert '/v1/example/{id}/' in paths
def test_mount_url_prefixed_to_paths(self):
patterns = [
path('example/', views.ExampleListView.as_view()),
path('example/{pk}/', views.ExampleDetailView.as_view()),
]
generator = SchemaGenerator(patterns=patterns, url='/api')
generator._initialise_endpoints()
paths = generator.get_schema()["paths"]
assert '/api/example/' in paths
assert '/api/example/{id}/' in paths
def test_schema_construction(self):
"""Construction of the top level dictionary."""
patterns = [
path('example/', views.ExampleListView.as_view()),
]
generator = SchemaGenerator(patterns=patterns)
request = create_request('/')
schema = generator.get_schema(request=request)
assert 'openapi' in schema
assert 'paths' in schema
def test_schema_rendering_to_json(self):
patterns = [
path('example/', views.ExampleGenericAPIView.as_view()),
]
generator = SchemaGenerator(patterns=patterns)
request = create_request('/')
schema = generator.get_schema(request=request)
ret = JSONOpenAPIRenderer().render(schema)
assert b'"openapi": "' in ret
assert b'"default": "0.0"' in ret
def test_schema_rendering_to_yaml(self):
patterns = [
path('example/', views.ExampleGenericAPIView.as_view()),
]
generator = SchemaGenerator(patterns=patterns)
request = create_request('/')
schema = generator.get_schema(request=request)
ret = OpenAPIRenderer().render(schema)
assert b"openapi: " in ret
assert b"default: '0.0'" in ret
def test_schema_rendering_timedelta_to_yaml_with_validator(self):
patterns = [
path('example/', views.ExampleValidatedAPIView.as_view()),
]
generator = SchemaGenerator(patterns=patterns)
request = create_request('/')
schema = generator.get_schema(request=request)
ret = OpenAPIRenderer().render(schema)
assert b"openapi: " in ret
assert b"duration:\n type: string\n minimum: \'10.0\'\n" in ret
def test_schema_with_no_paths(self):
patterns = []
generator = SchemaGenerator(patterns=patterns)
request = create_request('/')
schema = generator.get_schema(request=request)
assert schema['paths'] == {}
def test_schema_information(self):
"""Construction of the top level dictionary."""
patterns = [
path('example/', views.ExampleListView.as_view()),
]
generator = SchemaGenerator(patterns=patterns, title='My title', version='1.2.3', description='My description')
request = create_request('/')
schema = generator.get_schema(request=request)
assert schema['info']['title'] == 'My title'
assert schema['info']['version'] == '1.2.3'
assert schema['info']['description'] == 'My description'
def test_schema_information_empty(self):
"""Construction of the top level dictionary."""
patterns = [
path('example/', views.ExampleListView.as_view()),
]
generator = SchemaGenerator(patterns=patterns)
request = create_request('/')
schema = generator.get_schema(request=request)
assert schema['info']['title'] == ''
assert schema['info']['version'] == ''
def test_serializer_model(self):
"""Construction of the top level dictionary."""
patterns = [
path('example/', views.ExampleGenericAPIViewModel.as_view()),
]
generator = SchemaGenerator(patterns=patterns)
request = create_request('/')
schema = generator.get_schema(request=request)
print(schema)
assert 'components' in schema
assert 'schemas' in schema['components']
assert 'ExampleModel' in schema['components']['schemas']
def test_authtoken_serializer(self):
patterns = [
path('api-token-auth/', obtain_auth_token)
]
generator = SchemaGenerator(patterns=patterns)
request = create_request('/')
schema = generator.get_schema(request=request)
print(schema)
route = schema['paths']['/api-token-auth/']['post']
body_schema = route['requestBody']['content']['application/json']['schema']
assert body_schema == {
'$ref': '#/components/schemas/AuthToken'
}
assert schema['components']['schemas']['AuthToken'] == {
'type': 'object',
'properties': {
'username': {'type': 'string', 'writeOnly': True},
'password': {'type': 'string', 'writeOnly': True},
'token': {'type': 'string', 'readOnly': True},
},
'required': ['username', 'password']
}
def test_component_name(self):
patterns = [
path('example/', views.ExampleAutoSchemaComponentName.as_view()),
]
generator = SchemaGenerator(patterns=patterns)
request = create_request('/')
schema = generator.get_schema(request=request)
print(schema)
assert 'components' in schema
assert 'schemas' in schema['components']
assert 'Ulysses' in schema['components']['schemas']
def test_duplicate_component_name(self):
patterns = [
path('duplicate1/', views.ExampleAutoSchemaDuplicate1.as_view()),
path('duplicate2/', views.ExampleAutoSchemaDuplicate2.as_view()),
]
generator = SchemaGenerator(patterns=patterns)
request = create_request('/')
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
schema = generator.get_schema(request=request)
assert len(w) == 1
assert issubclass(w[-1].category, UserWarning)
assert 'has been overridden with a different value.' in str(w[-1].message)
assert 'components' in schema
assert 'schemas' in schema['components']
assert 'Duplicate' in schema['components']['schemas']
def test_component_should_not_be_generated_for_delete_method(self):
class ExampleView(generics.DestroyAPIView):
schema = AutoSchema(operation_id_base='example')
url_patterns = [
path('example/', ExampleView.as_view()),
]
generator = SchemaGenerator(patterns=url_patterns)
schema = generator.get_schema(request=create_request('/'))
assert 'components' not in schema
assert 'content' not in schema['paths']['/example/']['delete']['responses']['204']
| TestGenerator |
python | ray-project__ray | release/ray_release/exception.py | {
"start": 2800,
"end": 2900
} | class ____(EnvironmentSetupError):
exit_code = ExitCode.REMOTE_ENV_SETUP_ERROR
| RemoteEnvSetupError |
python | pytorch__pytorch | test/jit/test_list_dict.py | {
"start": 73253,
"end": 80819
} | class ____(JitTestCase):
"""
This class contains a suite of tests for torch.jit.script, a
function that returns a dictionary-like object that has reference
semantics across the Python/TorchScript boundary. That is,
it can be passed to a TorchScript function that mutates it
and those modifications are visible in the scope of the Python
caller of said TorchScript function.
The vast majority of tests are for making sure that objects returned
by torch.jit.script behave like dictionaries do so that they are fungible
in almost all circumstances with regular dictionaries.
"""
def _script_dict_add(self, d: torch._C.ScriptDict, k: int, v: int):
"""
This is a helper function that inserts the pair (k, v) into the
dictionary d in TorchScript. It is used for testing reference
semantics.
"""
@torch.jit.script
def dict_add(d: Dict[int, int], k: int, v: int):
d[k] = v
dict_add(d, k, v)
def _compare_eager_and_script(self, fn, input_dict, script_input_dict=None):
"""
This is a helper function that facilitates comparing behaviour between
Python dictionaries and "scripted" dictionaries.
Args:
fn: The function to test and compare the behaviour of.
input_dict: The input dictionary to use for the test (passed to fn).
script_input_dict: The scripted input dictionary to use for the tests.
If None, input_dict is scripted with torch.jit.script
and used instead.
"""
# Create ScriptDict version of input_dict if needed.
script_input_dict = script_input_dict or torch.jit.script(input_dict)
# Run fn with both input_dict and scripted_dict.
eager_raised, script_raised = False, False
try:
eager_out = fn(input_dict)
except Exception as e:
eager_exception = e
eager_raised = True
try:
script_out = fn(script_input_dict)
except Exception as e:
script_exception = e
script_raised = True
# Check that both calls raised or none of them raised.
self.assertEqual(eager_raised, script_raised)
if eager_raised:
# If fn raised an exception, it should be the same between
# regular and scripted dictionaries.
self.assertEqual(type(eager_exception), type(script_exception))
else:
# Otherwise, make sure the outputs match and the dictionaries
# match (the latter may not be the same as the output).
self.assertEqual(eager_out, script_out)
self.assertEqual(input_dict, script_input_dict)
def test_repr(self):
"""
Test the __repr__ method.
"""
self._compare_eager_and_script(lambda d: repr(d), {1: 2})
def test_bool(self):
"""
Test the __bool__ method. This should return True
if the dictionary is non-empty and False otherwise.
"""
self._compare_eager_and_script(lambda d: bool(d), {1: 2})
self._compare_eager_and_script(lambda d: bool(d), {})
def test_iter(self):
"""
Test iteration over a dictionary's keys.
"""
def sum_keys(input_dict):
s = 0
for k in input_dict:
s += k
return s
self._compare_eager_and_script(sum_keys, {1: 2, 3: 4})
def test_items(self):
"""
Test .items().
"""
def sum_pair_product(input_dict):
s = 0
for k, v in input_dict.items():
s += k * v
return s
self._compare_eager_and_script(sum_pair_product, {1: 2, 3: 4})
def test_getitem(self):
"""
Test accessing dictionary values using the [] operator.
"""
data = {1: 2, 3: 4}
self._compare_eager_and_script(lambda d: d[1], data)
self._compare_eager_and_script(lambda d: d[4], data)
self._compare_eager_and_script(lambda d: d[2], data)
self._compare_eager_and_script(lambda d: d["key"], data)
def test_setitem(self):
"""
Test setting dictionary values using the [] operator.
"""
data = {1: 2, 3: 4}
def fn(input_dict):
input_dict[1] = 10
input_dict[3] = 11
self._compare_eager_and_script(fn, data)
# Check that using improperly typed keys and values
# throws TypeError.
# _compare_eager_and_script cannot be used here since
# the following uses of __setitem__ are valid in
# Python.
script_data = torch.jit.script(data)
with self.assertRaises(TypeError):
script_data["str"] = 3
with self.assertRaises(TypeError):
script_data[3] = "str"
def test_contains(self):
"""
Test membership checks (x in y, x not in y).
"""
data = {1: 2, 3: 4}
def fn(input_dict):
return (
1 in input_dict,
2 not in input_dict,
3 in input_dict,
4 not in input_dict,
)
self._compare_eager_and_script(fn, data)
# Check that using an improperly typed key
# throws KeyError.
script_data = torch.jit.script(data)
with self.assertRaises(KeyError):
a = "str" in script_data
def test_delitem(self):
"""
Test deletion.
"""
data = {1: 2, 3: 4}
def del_fn(input_dict):
del input_dict[1]
def del_fn_raises(input_dict):
del input_dict[10]
self._compare_eager_and_script(del_fn, data)
self._compare_eager_and_script(del_fn_raises, data)
# Check that using an improperly typed key
# throws TypeError.
script_data = torch.jit.script(data)
with self.assertRaises(TypeError):
del script_data["str"]
def test_len(self):
"""
Test len() builtin function.
"""
self._compare_eager_and_script(lambda d: len(d), {1: 2})
self._compare_eager_and_script(lambda d: len(d), {})
@unittest.skip(
"Cannot pass until all dicts returned from TorchScript are ScriptDicts"
)
def test_nested(self):
"""
Test that reference semantics are honoured when the ScriptDict that is
mutated using TorchScript is inside another.
"""
nested = torch.jit.script(
{1: {1: 2}, 2: {3: 4}}, type_hint=Dict[int, Dict[int, int]]
)
one = nested[1]
two = nested[2]
self._script_dict_add(one, 9, 10)
self._script_dict_add(two, 11, 12)
# The mutation should be visible in the original dictionary, nested.
self.assertEqual(len(one), 2)
self.assertEqual(len(two), 2)
self.assertEqual(len(nested[1]), 2)
self.assertEqual(len(nested[2]), 2)
def test_reference_semantics(self):
"""
Test that reference semantics are honoured; that modifications made
to a ScriptDict in TorchScript are visible in Python.
"""
data = torch.jit.script({1: 2})
self._script_dict_add(data, 3, 4)
# The mutation should be visible in the original dictionary.
self.assertEqual(len(data), 2)
self.assertTrue(3 in data)
self.assertEqual(data[3], 4)
| TestScriptDict |
python | wandb__wandb | wandb/apis/importers/internals/internal.py | {
"start": 1981,
"end": 12887
} | class ____:
run: ImporterRun
interface: InterfaceQueue = InterfaceQueue()
@property
def run_dir(self) -> str:
p = Path(f"{ROOT_DIR}/{self.run.run_id()}/wandb")
p.mkdir(parents=True, exist_ok=True)
return f"{ROOT_DIR}/{self.run.run_id()}"
def make_artifacts_only_records(
self,
artifacts: Optional[Iterable[Artifact]] = None,
used_artifacts: Optional[Iterable[Artifact]] = None,
) -> Iterable[pb.Record]:
"""Only make records required to upload artifacts.
Escape hatch for adding extra artifacts to a run.
"""
yield self._make_run_record()
if used_artifacts:
for art in used_artifacts:
yield self._make_artifact_record(art, use_artifact=True)
if artifacts:
for art in artifacts:
yield self._make_artifact_record(art)
def make_records(
self,
config: SendManagerConfig,
) -> Iterable[pb.Record]:
"""Make all the records that constitute a run."""
yield self._make_run_record()
yield self._make_telem_record()
include_artifacts = config.log_artifacts or config.use_artifacts
yield self._make_files_record(
include_artifacts, config.files, config.media, config.code
)
if config.use_artifacts:
if (used_artifacts := self.run.used_artifacts()) is not None:
for artifact in used_artifacts:
yield self._make_artifact_record(artifact, use_artifact=True)
if config.log_artifacts:
if (artifacts := self.run.artifacts()) is not None:
for artifact in artifacts:
yield self._make_artifact_record(artifact)
if config.history:
yield from self._make_history_records()
if config.summary:
yield self._make_summary_record()
if config.terminal_output:
if (lines := self.run.logs()) is not None:
for line in lines:
yield self._make_output_record(line)
def _make_run_record(self) -> pb.Record:
run = pb.RunRecord()
run.run_id = self.run.run_id()
run.entity = self.run.entity()
run.project = self.run.project()
run.display_name = coalesce(self.run.display_name())
run.notes = coalesce(self.run.notes(), "")
run.tags.extend(coalesce(self.run.tags(), []))
run.start_time.FromMilliseconds(self.run.start_time())
host = self.run.host()
if host is not None:
run.host = host
runtime = self.run.runtime()
if runtime is not None:
run.runtime = runtime
run_group = self.run.run_group()
if run_group is not None:
run.run_group = run_group
config = self.run.config()
if "_wandb" not in config:
config["_wandb"] = {}
# how do I get this automatically?
config["_wandb"]["code_path"] = self.run.code_path()
config["_wandb"]["python_version"] = self.run.python_version()
config["_wandb"]["cli_version"] = self.run.cli_version()
self.interface._make_config(
data=config,
obj=run.config,
) # is there a better way?
return self.interface._make_record(run=run)
def _make_output_record(self, line) -> pb.Record:
output_raw = pb.OutputRawRecord()
output_raw.output_type = pb.OutputRawRecord.OutputType.STDOUT
output_raw.line = line
return self.interface._make_record(output_raw=output_raw)
def _make_summary_record(self) -> pb.Record:
d: dict = {
**self.run.summary(),
"_runtime": self.run.runtime(), # quirk of runtime -- it has to be here!
# '_timestamp': self.run.start_time()/1000,
}
d = recursive_cast_dictlike_to_dict(d)
summary = self.interface._make_summary_from_dict(d)
return self.interface._make_record(summary=summary)
def _make_history_records(self) -> Iterable[pb.Record]:
for metrics in self.run.metrics():
history = pb.HistoryRecord()
for k, v in metrics.items():
item = history.item.add()
item.key = k
# There seems to be some conversion issue to breaks when we try to re-upload.
# np.NaN gets converted to float("nan"), which is not expected by our system.
# If this cast to string (!) is not done, the row will be dropped.
if (isinstance(v, float) and math.isnan(v)) or v == "NaN":
v = np.NaN
if isinstance(v, bytes):
# it's a json string encoded as bytes
v = v.decode("utf-8")
else:
v = json.dumps(v)
item.value_json = v
rec = self.interface._make_record(history=history)
yield rec
def _make_files_record(
self, artifacts: bool, files: bool, media: bool, code: bool
) -> pb.Record:
run_files = self.run.files()
metadata_fname = f"{self.run_dir}/files/wandb-metadata.json"
if not files or run_files is None:
# We'll always need a metadata file even if there are no other files to upload
metadata_fname = self._make_metadata_file()
run_files = [(metadata_fname, "end")]
files_record = pb.FilesRecord()
for path, policy in run_files:
if not artifacts and path.startswith("artifact/"):
continue
if not media and path.startswith("media/"):
continue
if not code and path.startswith("code/"):
continue
# DirWatcher requires the path to start with media/ instead of the full path
if "media" in path:
p = Path(path)
path = str(p.relative_to(f"{self.run_dir}/files"))
f = files_record.files.add()
f.path = path
f.policy = file_policy_to_enum(policy)
return self.interface._make_record(files=files_record)
def _make_artifact_record(
self, artifact: Artifact, use_artifact=False
) -> pb.Record:
proto = self.interface._make_artifact(artifact)
proto.run_id = str(self.run.run_id())
proto.project = str(self.run.project())
proto.entity = str(self.run.entity())
proto.user_created = use_artifact
proto.use_after_commit = use_artifact
proto.finalize = True
aliases = artifact._aliases
aliases += ["latest", "imported"]
for alias in aliases:
proto.aliases.append(alias)
return self.interface._make_record(artifact=proto)
def _make_telem_record(self) -> pb.Record:
telem = telem_pb.TelemetryRecord()
feature = telem_pb.Feature()
feature.importer_mlflow = True
telem.feature.CopyFrom(feature)
cli_version = self.run.cli_version()
if cli_version:
telem.cli_version = cli_version
python_version = self.run.python_version()
if python_version:
telem.python_version = python_version
return self.interface._make_record(telemetry=telem)
def _make_metadata_file(self) -> str:
missing_text = "This data was not captured"
files_dir = f"{self.run_dir}/files"
os.makedirs(files_dir, exist_ok=True)
d = {}
d["os"] = coalesce(self.run.os_version(), missing_text)
d["python"] = coalesce(self.run.python_version(), missing_text)
d["program"] = coalesce(self.run.program(), missing_text)
d["cuda"] = coalesce(self.run.cuda_version(), missing_text)
d["host"] = coalesce(self.run.host(), missing_text)
d["username"] = coalesce(self.run.username(), missing_text)
d["executable"] = coalesce(self.run.executable(), missing_text)
gpus_used = self.run.gpus_used()
if gpus_used is not None:
d["gpu_devices"] = json.dumps(gpus_used)
d["gpu_count"] = json.dumps(len(gpus_used))
cpus_used = self.run.cpus_used()
if cpus_used is not None:
d["cpu_count"] = json.dumps(self.run.cpus_used())
mem_used = self.run.memory_used()
if mem_used is not None:
d["memory"] = json.dumps({"total": self.run.memory_used()})
fname = f"{files_dir}/wandb-metadata.json"
with open(fname, "w") as f:
f.write(json.dumps(d))
return fname
def _make_settings(
root_dir: str, settings_override: Optional[Dict[str, Any]] = None
) -> SettingsStatic:
_settings_override = coalesce(settings_override, {})
return SettingsStatic(
{
"x_files_dir": os.path.join(root_dir, "files"),
"root_dir": root_dir,
"resume": "never",
"program": None,
"ignore_globs": [],
"disable_job_creation": True,
"x_start_time": 0,
"x_sync": True,
"x_live_policy_rate_limit": 15, # matches dir_watcher
"x_live_policy_wait_time": 600, # matches dir_watcher
"x_file_stream_timeout_seconds": 60,
**_settings_override,
}
)
def send_run(
run: ImporterRun,
*,
extra_arts: Optional[Iterable[Artifact]] = None,
extra_used_arts: Optional[Iterable[Artifact]] = None,
config: Optional[SendManagerConfig] = None,
overrides: Optional[Dict[str, Any]] = None,
settings_override: Optional[Dict[str, Any]] = None,
) -> None:
if config is None:
config = SendManagerConfig()
# does this need to be here for pmap?
if overrides:
for k, v in overrides.items():
# `lambda: v` won't work!
# https://stackoverflow.com/questions/10802002/why-deepcopy-doesnt-create-new-references-to-lambda-function
setattr(run, k, lambda v=v: v)
rm = RecordMaker(run)
root_dir = rm.run_dir
settings = _make_settings(root_dir, settings_override)
sm_record_q = queue.Queue()
# wm_record_q = queue.Queue()
result_q = queue.Queue()
interface = InterfaceQueue(record_q=sm_record_q)
context_keeper = context.ContextKeeper()
sm = AlternateSendManager(
settings, sm_record_q, result_q, interface, context_keeper
)
if extra_arts or extra_used_arts:
records = rm.make_artifacts_only_records(extra_arts, extra_used_arts)
else:
records = rm.make_records(config)
for r in records:
logger.debug(f"Sending {r=}")
# In a future update, it might be good to write to a transaction log and have
# incremental uploads only send the missing records.
# wm.write(r)
sm.send(r)
sm.finish()
# wm.finish()
| RecordMaker |
python | automl__auto-sklearn | autosklearn/pipeline/components/regression/decision_tree.py | {
"start": 566,
"end": 4904
} | class ____(AutoSklearnRegressionAlgorithm):
def __init__(
self,
criterion,
max_features,
max_depth_factor,
min_samples_split,
min_samples_leaf,
min_weight_fraction_leaf,
max_leaf_nodes,
min_impurity_decrease,
random_state=None,
):
self.criterion = criterion
self.max_features = max_features
self.max_depth_factor = max_depth_factor
self.min_samples_split = min_samples_split
self.min_samples_leaf = min_samples_leaf
self.max_leaf_nodes = max_leaf_nodes
self.min_weight_fraction_leaf = min_weight_fraction_leaf
self.min_impurity_decrease = min_impurity_decrease
self.random_state = random_state
self.estimator = None
def fit(self, X, y, sample_weight=None):
from sklearn.tree import DecisionTreeRegressor
self.max_features = float(self.max_features)
if check_none(self.max_depth_factor):
max_depth_factor = self.max_depth_factor = None
else:
num_features = X.shape[1]
self.max_depth_factor = int(self.max_depth_factor)
max_depth_factor = max(
1, int(np.round(self.max_depth_factor * num_features, 0))
)
self.min_samples_split = int(self.min_samples_split)
self.min_samples_leaf = int(self.min_samples_leaf)
if check_none(self.max_leaf_nodes):
self.max_leaf_nodes = None
else:
self.max_leaf_nodes = int(self.max_leaf_nodes)
self.min_weight_fraction_leaf = float(self.min_weight_fraction_leaf)
self.min_impurity_decrease = float(self.min_impurity_decrease)
self.estimator = DecisionTreeRegressor(
criterion=self.criterion,
max_depth=max_depth_factor,
min_samples_split=self.min_samples_split,
min_samples_leaf=self.min_samples_leaf,
max_leaf_nodes=self.max_leaf_nodes,
min_weight_fraction_leaf=self.min_weight_fraction_leaf,
min_impurity_decrease=self.min_impurity_decrease,
random_state=self.random_state,
)
if y.ndim == 2 and y.shape[1] == 1:
y = y.flatten()
self.estimator.fit(X, y, sample_weight=sample_weight)
return self
def predict(self, X):
if self.estimator is None:
raise NotImplementedError
return self.estimator.predict(X)
@staticmethod
def get_properties(dataset_properties=None):
return {
"shortname": "DT",
"name": "Decision Tree Classifier",
"handles_regression": True,
"handles_classification": False,
"handles_multiclass": False,
"handles_multilabel": False,
"handles_multioutput": True,
"is_deterministic": False,
"input": (DENSE, SPARSE, UNSIGNED_DATA),
"output": (PREDICTIONS,),
}
@staticmethod
def get_hyperparameter_search_space(
feat_type: Optional[FEAT_TYPE_TYPE] = None, dataset_properties=None
):
cs = ConfigurationSpace()
criterion = CategoricalHyperparameter(
"criterion", ["mse", "friedman_mse", "mae"]
)
max_features = Constant("max_features", 1.0)
max_depth_factor = UniformFloatHyperparameter(
"max_depth_factor", 0.0, 2.0, default_value=0.5
)
min_samples_split = UniformIntegerHyperparameter(
"min_samples_split", 2, 20, default_value=2
)
min_samples_leaf = UniformIntegerHyperparameter(
"min_samples_leaf", 1, 20, default_value=1
)
min_weight_fraction_leaf = Constant("min_weight_fraction_leaf", 0.0)
max_leaf_nodes = UnParametrizedHyperparameter("max_leaf_nodes", "None")
min_impurity_decrease = UnParametrizedHyperparameter(
"min_impurity_decrease", 0.0
)
cs.add_hyperparameters(
[
criterion,
max_features,
max_depth_factor,
min_samples_split,
min_samples_leaf,
min_weight_fraction_leaf,
max_leaf_nodes,
min_impurity_decrease,
]
)
return cs
| DecisionTree |
python | qdrant__qdrant-client | qdrant_client/local/sparse_distances.py | {
"start": 1549,
"end": 1864
} | class ____:
def __init__(self, positive: SparseVector, negative: SparseVector):
validate_sparse_vector(positive)
validate_sparse_vector(negative)
self.positive: SparseVector = sort_sparse_vector(positive)
self.negative: SparseVector = sort_sparse_vector(negative)
| SparseContextPair |
python | modin-project__modin | asv_bench/benchmarks/benchmarks.py | {
"start": 20381,
"end": 22288
} | class ____:
param_names = ["shape", "indexer_type"]
params = [
get_benchmark_shapes("TimeIndexing"),
[
"bool_array",
"bool_series",
"scalar",
"slice",
"continuous_slice",
"numpy_array_take_all_values",
"python_list_take_10_values",
"function",
],
]
indexer_getters = {
"bool_array": lambda df: np.array([False, True] * (len(df) // 2)),
# This boolean-Series is a projection of the source frame, it shouldn't
# be reimported or triggered to execute:
"bool_series": lambda df: df.iloc[:, 0] > 50,
"scalar": lambda df: len(df) // 2,
"slice": lambda df: slice(0, len(df), 2),
"continuous_slice": lambda df: slice(len(df) // 2),
"numpy_array_take_all_values": lambda df: np.arange(len(df)),
"python_list_take_10_values": lambda df: list(range(min(10, len(df)))),
"function": lambda df: (lambda df: df.index[::-2]),
}
def setup(self, shape, indexer_type):
self.df = generate_dataframe("int", *shape, RAND_LOW, RAND_HIGH)
self.indexer = self.indexer_getters[indexer_type](self.df)
if isinstance(self.indexer, (IMPL.Series, IMPL.DataFrame)):
# HACK: Triggering `dtypes` meta-data computation in advance,
# so it won't affect the `loc/iloc` time:
self.indexer.dtypes
def time_iloc(self, shape, indexer_type):
# Pandas doesn't implement `df.iloc[series boolean_mask]` and raises an exception on it.
# Replacing this with the semantically equivalent construction:
if indexer_type != "bool_series":
execute(self.df.iloc[self.indexer])
else:
execute(self.df[self.indexer])
def time_loc(self, shape, indexer_type):
execute(self.df.loc[self.indexer])
| TimeIndexing |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mssql/json.py | {
"start": 4182,
"end": 4431
} | class ____(_FormatTypeMixin, sqltypes.JSON.JSONIndexType):
def _format_value(self, value):
if isinstance(value, int):
value = "$[%s]" % value
else:
value = '$."%s"' % value
return value
| JSONIndexType |
python | getsentry__sentry | src/sentry/features/base.py | {
"start": 1224,
"end": 1482
} | class ____(Feature):
def __init__(self, name: str, organization: Organization) -> None:
super().__init__(name)
self.organization = organization
def get_subject(self) -> Organization:
return self.organization
| OrganizationFeature |
python | kubernetes-client__python | kubernetes/client/models/v1_replication_controller_list.py | {
"start": 383,
"end": 7334
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'api_version': 'str',
'items': 'list[V1ReplicationController]',
'kind': 'str',
'metadata': 'V1ListMeta'
}
attribute_map = {
'api_version': 'apiVersion',
'items': 'items',
'kind': 'kind',
'metadata': 'metadata'
}
def __init__(self, api_version=None, items=None, kind=None, metadata=None, local_vars_configuration=None): # noqa: E501
"""V1ReplicationControllerList - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._api_version = None
self._items = None
self._kind = None
self._metadata = None
self.discriminator = None
if api_version is not None:
self.api_version = api_version
self.items = items
if kind is not None:
self.kind = kind
if metadata is not None:
self.metadata = metadata
@property
def api_version(self):
"""Gets the api_version of this V1ReplicationControllerList. # noqa: E501
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:return: The api_version of this V1ReplicationControllerList. # noqa: E501
:rtype: str
"""
return self._api_version
@api_version.setter
def api_version(self, api_version):
"""Sets the api_version of this V1ReplicationControllerList.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:param api_version: The api_version of this V1ReplicationControllerList. # noqa: E501
:type: str
"""
self._api_version = api_version
@property
def items(self):
"""Gets the items of this V1ReplicationControllerList. # noqa: E501
List of replication controllers. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller # noqa: E501
:return: The items of this V1ReplicationControllerList. # noqa: E501
:rtype: list[V1ReplicationController]
"""
return self._items
@items.setter
def items(self, items):
"""Sets the items of this V1ReplicationControllerList.
List of replication controllers. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller # noqa: E501
:param items: The items of this V1ReplicationControllerList. # noqa: E501
:type: list[V1ReplicationController]
"""
if self.local_vars_configuration.client_side_validation and items is None: # noqa: E501
raise ValueError("Invalid value for `items`, must not be `None`") # noqa: E501
self._items = items
@property
def kind(self):
"""Gets the kind of this V1ReplicationControllerList. # noqa: E501
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:return: The kind of this V1ReplicationControllerList. # noqa: E501
:rtype: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""Sets the kind of this V1ReplicationControllerList.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:param kind: The kind of this V1ReplicationControllerList. # noqa: E501
:type: str
"""
self._kind = kind
@property
def metadata(self):
"""Gets the metadata of this V1ReplicationControllerList. # noqa: E501
:return: The metadata of this V1ReplicationControllerList. # noqa: E501
:rtype: V1ListMeta
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""Sets the metadata of this V1ReplicationControllerList.
:param metadata: The metadata of this V1ReplicationControllerList. # noqa: E501
:type: V1ListMeta
"""
self._metadata = metadata
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1ReplicationControllerList):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1ReplicationControllerList):
return True
return self.to_dict() != other.to_dict()
| V1ReplicationControllerList |
python | PyCQA__pylint | tests/functional/r/regression_02/regression_5244.py | {
"start": 205,
"end": 332
} | class ____:
def some_func(self):
return lambda: 42
def __len__(self):
return len(self.some_func())
| MyClass |
python | run-llama__llama_index | llama-index-core/llama_index/core/memory/types.py | {
"start": 442,
"end": 2412
} | class ____(BaseComponent):
"""Base class for all memory types."""
@classmethod
def class_name(cls) -> str:
"""Get class name."""
return "BaseMemory"
@classmethod
@abstractmethod
def from_defaults(
cls,
**kwargs: Any,
) -> "BaseMemory":
"""Create a chat memory from defaults."""
@abstractmethod
def get(self, input: Optional[str] = None, **kwargs: Any) -> List[ChatMessage]:
"""Get chat history."""
async def aget(
self, input: Optional[str] = None, **kwargs: Any
) -> List[ChatMessage]:
"""Get chat history."""
return await asyncio.to_thread(self.get, input=input, **kwargs)
@abstractmethod
def get_all(self) -> List[ChatMessage]:
"""Get all chat history."""
async def aget_all(self) -> List[ChatMessage]:
"""Get all chat history."""
return await asyncio.to_thread(self.get_all)
@abstractmethod
def put(self, message: ChatMessage) -> None:
"""Put chat history."""
async def aput(self, message: ChatMessage) -> None:
"""Put chat history."""
await asyncio.to_thread(self.put, message)
def put_messages(self, messages: List[ChatMessage]) -> None:
"""Put chat history."""
for message in messages:
self.put(message)
async def aput_messages(self, messages: List[ChatMessage]) -> None:
"""Put chat history."""
await asyncio.to_thread(self.put_messages, messages)
@abstractmethod
def set(self, messages: List[ChatMessage]) -> None:
"""Set chat history."""
async def aset(self, messages: List[ChatMessage]) -> None:
"""Set chat history."""
await asyncio.to_thread(self.set, messages)
@abstractmethod
def reset(self) -> None:
"""Reset chat history."""
async def areset(self) -> None:
"""Reset chat history."""
await asyncio.to_thread(self.reset)
| BaseMemory |
python | Netflix__metaflow | metaflow/plugins/argo/argo_workflows.py | {
"start": 215846,
"end": 216776
} | class ____(object):
# https://github.com/argoproj/argo-events/blob/master/api/sensor.md#argoproj.io/v1alpha1.ArgoWorkflowTrigger
def __init__(self):
tree = lambda: defaultdict(tree)
self.payload = tree()
self.payload["operation"] = "submit"
self.payload["group"] = "argoproj.io"
self.payload["version"] = "v1alpha1"
self.payload["resource"] = "workflows"
def source(self, source):
self.payload["source"] = source
return self
def parameters(self, trigger_parameters):
if "parameters" not in self.payload:
self.payload["parameters"] = []
for trigger_parameter in trigger_parameters:
self.payload["parameters"].append(trigger_parameter.to_json())
return self
def to_json(self):
return self.payload
def __str__(self):
return json.dumps(self.payload, indent=4)
| ArgoWorkflowTrigger |
python | allegroai__clearml | examples/frameworks/pytorch/pytorch_tensorboard.py | {
"start": 409,
"end": 6227
} | class ____(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 10)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 320)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = self.fc2(x)
return F.log_softmax(x, dim=1)
def train(model, epoch, train_loader, args, optimizer, writer):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
if args.cuda:
data, target = data.cuda(), target.cuda()
data, target = Variable(data), Variable(target)
optimizer.zero_grad()
output = model(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.step()
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.data.item()))
niter = epoch*len(train_loader)+batch_idx
writer.add_scalar('Train/Loss', loss.data.item(), niter)
def test(model, test_loader, args, optimizer, writer):
model.eval()
test_loss = 0
correct = 0
for niter, (data, target) in enumerate(test_loader):
if args.cuda:
data, target = data.cuda(), target.cuda()
data, target = Variable(data), Variable(target)
output = model(data)
test_loss += F.nll_loss(output, target, reduction='sum').data.item() # sum up batch loss
pred = output.data.max(1)[1] # get the index of the max log-probability
pred = pred.eq(target.data).cpu().sum()
writer.add_scalar('Test/Loss', pred, niter)
correct += pred
if niter % 100 == 0:
writer.add_image('test', data[0, :, :, :], niter)
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
def main():
# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=10, metavar='N',
help='number of epochs to train (default: 10)')
parser.add_argument('--lr', type=float, default=0.01, metavar='LR',
help='learning rate (default: 0.01)')
parser.add_argument('--momentum', type=float, default=0.5, metavar='M',
help='SGD momentum (default: 0.5)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='disables CUDA training')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=10, metavar='N',
help='how many batches to wait before logging training status')
args = parser.parse_args()
# Connecting ClearML with the current process,
# from here on everything is logged automatically
task = Task.init(project_name='examples', task_name='PyTorch with TensorBoard') # noqa: F841
writer = SummaryWriter('runs')
writer.add_text('TEXT', 'This is some text', 0)
args.cuda = not args.no_cuda and torch.cuda.is_available()
torch.manual_seed(args.seed)
if args.cuda:
torch.cuda.manual_seed(args.seed)
kwargs = {'num_workers': 4, 'pin_memory': True} if args.cuda else {}
train_loader = torch.utils.data.DataLoader(datasets.MNIST('../data', train=True, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))])),
batch_size=args.batch_size, shuffle=True, **kwargs)
test_loader = torch.utils.data.DataLoader(datasets.MNIST('../data', train=False,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))])),
batch_size=args.test_batch_size, shuffle=True, **kwargs)
model = Net()
if args.cuda:
model.cuda()
optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)
for epoch in range(1, args.epochs + 1):
train(model, epoch, train_loader, args, optimizer, writer)
m = torch.jit.script(model)
m.save(os.path.join(gettempdir(), 'model{}'.format(epoch)))
#torch.save(model, os.path.join(gettempdir(), 'model{}'.format(epoch)))
test(model, test_loader, args, optimizer, writer)
if __name__ == "__main__":
# Hack for supporting Windows OS - https://pytorch.org/docs/stable/notes/windows.html#usage-multiprocessing
main()
| Net |
python | django__django | tests/bash_completion/management/commands/test_command.py | {
"start": 54,
"end": 258
} | class ____(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("--list", action="store_true", help="Print all options")
def handle(self, *args, **options):
pass
| Command |
python | sympy__sympy | sympy/stats/rv.py | {
"start": 6285,
"end": 8632
} | class ____(Expr):
"""
Random Symbols represent ProbabilitySpaces in SymPy Expressions.
In principle they can take on any value that their symbol can take on
within the associated PSpace with probability determined by the PSpace
Density.
Explanation
===========
Random Symbols contain pspace and symbol properties.
The pspace property points to the represented Probability Space
The symbol is a standard SymPy Symbol that is used in that probability space
for example in defining a density.
You can form normal SymPy expressions using RandomSymbols and operate on
those expressions with the Functions
E - Expectation of a random expression
P - Probability of a condition
density - Probability Density of an expression
given - A new random expression (with new random symbols) given a condition
An object of the RandomSymbol type should almost never be created by the
user. They tend to be created instead by the PSpace class's value method.
Traditionally a user does not even do this but instead calls one of the
convenience functions Normal, Exponential, Coin, Die, FiniteRV, etc....
"""
def __new__(cls, symbol, pspace=None):
from sympy.stats.joint_rv import JointRandomSymbol
if pspace is None:
# Allow single arg, representing pspace == PSpace()
pspace = PSpace()
symbol = _symbol_converter(symbol)
if not isinstance(pspace, PSpace):
raise TypeError("pspace variable should be of type PSpace")
if cls == JointRandomSymbol and isinstance(pspace, SinglePSpace):
cls = RandomSymbol
return Basic.__new__(cls, symbol, pspace)
is_finite = True
is_symbol = True
is_Atom = True
_diff_wrt = True
pspace = property(lambda self: self.args[1])
symbol = property(lambda self: self.args[0])
name = property(lambda self: self.symbol.name)
def _eval_is_positive(self):
return self.symbol.is_positive
def _eval_is_integer(self):
return self.symbol.is_integer
def _eval_is_real(self):
return self.symbol.is_real or self.pspace.is_real
@property
def is_commutative(self):
return self.symbol.is_commutative
@property
def free_symbols(self):
return {self}
| RandomSymbol |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/service/cross_trainer_cache_test.py | {
"start": 1237,
"end": 19200
} | class ____(data_service_test_base.TestBase,
parameterized.TestCase):
"""Tests for sharing datasets across jobs using a cross-trainer cache."""
@combinations.generate(test_base.default_test_combinations())
def testEnableCrossTrainerCache(self):
"""Tests cross-trainer cache with `distribute`."""
cluster = self._create_cluster(num_workers=1)
dataset = dataset_ops.Dataset.range(10000000).repeat()
dataset1 = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 1"))
self.assertDatasetProduces(dataset1.take(10), list(range(10)))
# The second client reads the same data from the cross-trainer cache.
dataset2 = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 2"))
self.assertDatasetProduces(dataset2.take(10), list(range(10)))
@combinations.generate(test_base.default_test_combinations())
def testFromDatasetId(self):
"""Tests cross-trainer cache with `register_dataset`/`from_dataset_id`."""
cluster = self._create_cluster(num_workers=1)
dataset = dataset_ops.Dataset.range(10000000).repeat()
dataset_id1 = data_service_ops.register_dataset(
cluster.dispatcher.target, dataset, dataset_id="dataset_id")
dataset1 = data_service_ops.from_dataset_id(
processing_mode=data_service_ops.ShardingPolicy.OFF,
service=cluster.dispatcher.target,
dataset_id=dataset_id1,
element_spec=dataset.element_spec,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 1"))
self.assertDatasetProduces(dataset1.take(10), list(range(10)))
dataset_id2 = data_service_ops.register_dataset(
cluster.dispatcher.target, dataset, dataset_id="dataset_id")
dataset2 = data_service_ops.from_dataset_id(
processing_mode=data_service_ops.ShardingPolicy.OFF,
service=cluster.dispatcher.target,
dataset_id=dataset_id2,
element_spec=dataset.element_spec,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 2"))
self.assertDatasetProduces(dataset2.take(10), list(range(10)))
@combinations.generate(test_base.default_test_combinations())
def testDisableCrossTrainerCacheByDefault(self):
cluster = self._create_cluster(num_workers=1)
dataset = dataset_ops.Dataset.range(10000000).repeat()
dataset1 = self.make_distributed_dataset(dataset, cluster, job_name="job")
self.assertDatasetProduces(dataset1.take(10), list(range(10)))
# The two clients use the same job. The second client can't read the data
# already read by the first client.
dataset2 = self.make_distributed_dataset(dataset, cluster, job_name="job")
output = self.getDatasetOutput(dataset2.take(10))
self.assertGreaterEqual(output[0], 10)
@combinations.generate(test_base.default_test_combinations())
def testConcurrentReaders(self):
# Fetching an element from the dataset will trigger prefetches of more
# elements, one per CPU core which will be placed in the cache.
# However if the number of prefetches exceeds the space available in
# the cache then the sliding window will be moved forward away from
# the element just read thus negating the use of the cache as other
# trainers will not get the correct element.
# Hence the need to calculate the size of the cache based on the
# number of CPU cores and the element size of 423. The extra 8
# entries are simply a bit of margin.
num_cpus = multiprocessing.cpu_count()
cluster = self._create_cluster(
num_workers=1, cross_trainer_cache_size_bytes=(num_cpus + 8) * 423)
num_readers = 20
num_elements = 50
dataset = dataset_ops.Dataset.range(10000000).repeat()
datasets = []
iterators = []
for i in range(num_readers):
distributed_dataset = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id=f"Trainer {i}"),
max_outstanding_requests=1)
iterator = self.getNext(distributed_dataset)
datasets.append(distributed_dataset)
iterators.append(iterator)
for i in range(num_elements):
# All the readers read the same element in one step.
for j in range(num_readers):
self.assertEqual(self.evaluate(iterators[j]()), i)
@combinations.generate(test_base.default_test_combinations())
def testSlowClientSkipsData(self):
cluster = self._create_cluster(
num_workers=1, cross_trainer_cache_size_bytes=500)
dataset = dataset_ops.Dataset.range(10000000).repeat()
dataset1 = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 1"))
self.assertDatasetProduces(dataset1.take(200), list(range(200)))
dataset2 = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 2"))
dataset2 = dataset2.take(200)
output = self.getDatasetOutput(dataset2)
# When the cache is small, the second trainer couldn't read the beginning of
# the dataset. It can still read 200 elements from the dataset, because the
# dataset is infinite.
self.assertGreater(output[0], 0)
self.assertLen(output, 200)
@combinations.generate(test_base.default_test_combinations())
def testSmallCache(self):
cluster = self._create_cluster(
num_workers=1, cross_trainer_cache_size_bytes=500)
dataset = dataset_ops.Dataset.range(10000000).repeat()
num_readers = 20
for i in range(num_readers):
# Even if the cache is small and may discard old data, each trainer can
# still read the required number of elements because the input dataset is
# infinite.
distributed_dataset = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id=f"Trainer {i}"))
output = self.getDatasetOutput(distributed_dataset.take(200))
self.assertLen(output, 200)
@combinations.generate(test_base.default_test_combinations())
def testShuffleDataset(self):
cluster = self._create_cluster(num_workers=1)
dataset = dataset_ops.Dataset.range(10000000).repeat().shuffle(
buffer_size=100)
dataset1 = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 1"))
output1 = self.getDatasetOutput(dataset1.take(10))
dataset2 = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 2"))
output2 = self.getDatasetOutput(dataset2.take(10))
self.assertEqual(output1, output2)
@combinations.generate(test_base.default_test_combinations())
def testSameTrainerID(self):
# Jobs from the same training cluster do not reuse data from the cache.
cluster = self._create_cluster(num_workers=1)
dataset = dataset_ops.Dataset.range(10000000).repeat()
dataset1 = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer ID"))
self.assertDatasetProduces(dataset1.take(10), list(range(10)))
dataset2 = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer ID"))
output = self.getDatasetOutput(dataset2.take(10))
self.assertGreaterEqual(output[0], 10)
@combinations.generate(test_base.default_test_combinations())
def testDifferentJobNames(self):
cluster = self._create_cluster(num_workers=1)
dataset = dataset_ops.Dataset.range(10000000).repeat()
dataset1 = self.make_distributed_dataset(
dataset,
cluster,
job_name="job1",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 1"))
self.assertDatasetProduces(dataset1.take(10), list(range(10)))
dataset2 = self.make_distributed_dataset(
dataset,
cluster,
job_name="job2",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 2"))
self.assertDatasetProduces(dataset2.take(10), list(range(10)))
@combinations.generate(test_base.default_test_combinations())
def testDynamicSharding(self):
cluster = self._create_cluster(num_workers=2)
dataset = dataset_ops.Dataset.range(10000000).repeat()
dataset1 = self.make_distributed_dataset(
dataset,
cluster,
processing_mode=data_service_ops.ShardingPolicy.DYNAMIC,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 1"))
output1 = self.getDatasetOutput(dataset1.take(100))
# The second client reads the same data from the cross-trainer cache.
dataset2 = self.make_distributed_dataset(
dataset,
cluster,
processing_mode=data_service_ops.ShardingPolicy.DYNAMIC,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 2"))
output2 = self.getDatasetOutput(dataset2.take(100))
# Verifies the intersection is non-empty.
self.assertTrue(set(output1) & set(output2))
@combinations.generate(test_base.default_test_combinations())
def testNoCompression(self):
cluster = self._create_cluster(num_workers=1)
dataset = dataset_ops.Dataset.range(10000000).repeat()
dataset1 = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
compression=None,
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 1"))
self.assertDatasetProduces(dataset1.take(10), list(range(10)))
dataset2 = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
compression=None,
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 2"))
self.assertDatasetProduces(dataset2.take(10), list(range(10)))
@combinations.generate(test_base.default_test_combinations())
def testCompressionMismatch(self):
cluster = self._create_cluster(num_workers=1)
dataset = dataset_ops.Dataset.range(10000000).repeat()
dataset1 = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 1"))
self.assertDatasetProduces(dataset1.take(10), list(range(10)))
with self.assertRaisesRegex(errors.InvalidArgumentError,
"Data type mismatch"):
dataset2 = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
compression=None,
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 1"))
self.getDatasetOutput(dataset2)
@combinations.generate(test_base.default_test_combinations())
def testRequiresJobName(self):
cluster = self._create_cluster(num_workers=1)
dataset = dataset_ops.Dataset.range(10000000).repeat()
with self.assertRaisesRegex(
errors.InvalidArgumentError,
"Cross-trainer caching requires named jobs. Got empty `job_name`."):
dataset = self.make_distributed_dataset(
dataset,
cluster,
job_name=None,
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 1"))
self.getDatasetOutput(dataset)
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
combinations.combine(range_=[0, 10])))
def testRequiresInfiniteDataset(self, range_):
cluster = self._create_cluster(num_workers=1)
dataset = dataset_ops.Dataset.range(range_).map(lambda x: x + 1)
with self.assertRaisesRegex(
errors.InvalidArgumentError,
"Cross-trainer caching requires the input dataset to be infinite."):
dataset = dataset.apply(
data_service_ops.distribute(
processing_mode=data_service_ops.ShardingPolicy.OFF,
service=cluster.dispatcher.target,
job_name="job_name",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer ID")))
self.getDatasetOutput(dataset)
@combinations.generate(test_base.eager_only_combinations())
def testMultipleIterationsForOneDatasetEagerMode(self):
cluster = self._create_cluster(num_workers=1)
dataset = dataset_ops.Dataset.range(10000000).repeat()
dataset1 = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 1"))
# In the eager mode, each iteration creates a new data service job and does
# not reuse cached data. We disallow this use case.
with self.assertRaisesRegex(
errors.InvalidArgumentError,
"Cross-trainer caching requires infinite datasets and disallows "
"multiple repetitions of the same dataset."):
self.getDatasetOutput(dataset1.take(10))
self.getDatasetOutput(dataset1.take(10))
self.getDatasetOutput(dataset1.take(10))
@combinations.generate(test_base.graph_only_combinations())
def testMultipleIterationsForOneDatasetGraphMode(self):
cluster = self._create_cluster(num_workers=1)
dataset = dataset_ops.Dataset.range(10000000).repeat()
dataset1 = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 1"))
# These clients are assumed to be from the same training cluster. Thus, they
# do not reuse data from the cross-trainer cache.
output1 = self.getDatasetOutput(dataset1.take(10))
output1 += self.getDatasetOutput(dataset1.take(10))
output1 += self.getDatasetOutput(dataset1.take(10))
self.assertLen(set(output1), 30)
dataset2 = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 2"))
# These clients reuse some data from the previous clients (not exactly the
# same data due to client-side buffering).
output2 = self.getDatasetOutput(dataset2.take(10))
output2 += self.getDatasetOutput(dataset2.take(10))
output2 += self.getDatasetOutput(dataset2.take(10))
self.assertTrue(set(output1) & set(output2))
@combinations.generate(test_base.default_test_combinations())
def testDisallowCoordinatedRead(self):
cluster = self._create_cluster(num_workers=1)
dataset = dataset_ops.Dataset.range(10000000).repeat()
with self.assertRaisesRegex(
errors.InvalidArgumentError,
"Cross-trainer caching does not support coordinated reads."):
dataset = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
num_consumers=1,
consumer_index=0,
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 1"))
self.getDatasetOutput(dataset)
@combinations.generate(test_base.default_test_combinations())
def testNamedJobMismatch(self):
cluster = self._create_cluster(num_workers=1)
dataset = dataset_ops.Dataset.range(10000000).repeat()
dataset1 = self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id="Trainer 1"))
self.assertDatasetProduces(dataset1.take(10), list(range(10)))
with self.assertRaisesRegex(
errors.InvalidArgumentError,
"Existing cross-trainer cache: <enabled>; got <disabled>"):
dataset2 = self.make_distributed_dataset(
dataset, cluster, job_name="job", cross_trainer_cache=None)
self.getDatasetOutput(dataset2)
@combinations.generate(test_base.default_test_combinations())
def testRequiresNonEmptyTrainerID(self):
cluster = self._create_cluster(num_workers=2)
dataset = dataset_ops.Dataset.range(10000000).repeat()
with self.assertRaisesRegex(
ValueError,
"tf.data service cross-trainer cache requires a non-empty trainer ID."):
self.make_distributed_dataset(
dataset,
cluster,
job_name="job",
cross_trainer_cache=data_service_ops.CrossTrainerCache(
trainer_id=None))
def _create_cluster(self,
num_workers,
cross_trainer_cache_size_bytes=10 * (2**30)):
cluster = data_service_test_base.TestCluster(num_workers=0)
for _ in range(num_workers):
worker = data_service_test_base.TestWorker(
dispatcher_address=cluster.dispatcher_address(),
shutdown_quiet_period_ms=0,
cross_trainer_cache_size_bytes=cross_trainer_cache_size_bytes)
worker.start()
cluster.workers.append(worker)
return cluster
if __name__ == "__main__":
test.main()
| CrossTrainerCacheTest |
python | mlflow__mlflow | mlflow/utils/autologging_utils/logging_and_warnings.py | {
"start": 237,
"end": 8120
} | class ____:
"""
Provides threadsafe utilities to modify warning behavior for MLflow autologging, including:
- Global disablement of MLflow warnings across all threads
- Global rerouting of MLflow warnings to an MLflow event logger (i.e. `logger.warning()`)
across all threads
- Disablement of non-MLflow warnings for the current thread
- Rerouting of non-MLflow warnings to an MLflow event logger for the current thread
"""
def __init__(self):
self._mlflow_root_path = Path(os.path.dirname(mlflow.__file__)).resolve()
self._state_lock = RLock()
self._did_patch_showwarning = False
self._disabled_threads = set()
self._rerouted_threads = set()
self._mlflow_warnings_disabled_globally = False
self._mlflow_warnings_rerouted_to_event_logs = False
def _patched_showwarning(self, message, category, filename, lineno, *args, **kwargs):
"""
A patched implementation of `warnings.showwarning` that enforces the warning configuration
options configured on the controller (e.g. rerouting or disablement of MLflow warnings,
disablement of all warnings for the current thread).
Note that reassigning `warnings.showwarning` is the standard / recommended approach for
modifying warning message display behaviors. For reference, see
https://docs.python.org/3/library/warnings.html#warnings.showwarning
"""
# NB: We explicitly avoid blocking on the `self._state_lock` lock during `showwarning`
# to so that threads don't have to execute serially whenever they emit warnings with
# `warnings.warn()`. We only lock during configuration changes to ensure that
# `warnings.showwarning` is patched or unpatched at the correct times.
from mlflow.utils.autologging_utils import _logger
# If the warning's source file is contained within the MLflow package's base
# directory, it is an MLflow warning and should be emitted via `logger.warning`
warning_source_path = Path(filename).resolve()
is_mlflow_warning = self._mlflow_root_path in warning_source_path.parents
curr_thread = get_current_thread_id()
if (curr_thread in self._disabled_threads) or (
is_mlflow_warning and self._mlflow_warnings_disabled_globally
):
return
elif (curr_thread in self._rerouted_threads and not is_mlflow_warning) or (
is_mlflow_warning and self._mlflow_warnings_rerouted_to_event_logs
):
_logger.warning(
'MLflow autologging encountered a warning: "%s:%d: %s: %s"',
filename,
lineno,
category.__name__,
message,
)
else:
ORIGINAL_SHOWWARNING(message, category, filename, lineno, *args, **kwargs)
def _should_patch_showwarning(self):
return (
(len(self._disabled_threads) > 0)
or (len(self._rerouted_threads) > 0)
or self._mlflow_warnings_disabled_globally
or self._mlflow_warnings_rerouted_to_event_logs
)
def _modify_patch_state_if_necessary(self):
"""
Patches or unpatches `warnings.showwarning` if necessary, as determined by:
- Whether or not `warnings.showwarning` is already patched
- Whether or not any custom warning state has been configured on the warnings
controller (i.e. disablement or rerouting of certain warnings globally or for a
particular thread)
Note that reassigning `warnings.showwarning` is the standard / recommended approach for
modifying warning message display behaviors. For reference, see
https://docs.python.org/3/library/warnings.html#warnings.showwarning
"""
with self._state_lock:
if self._should_patch_showwarning() and not self._did_patch_showwarning:
# NB: guard to prevent patching an instance of a patch
if warnings.showwarning != self._patched_showwarning:
warnings.showwarning = self._patched_showwarning
self._did_patch_showwarning = True
elif not self._should_patch_showwarning() and self._did_patch_showwarning:
# NB: only unpatch iff the patched function is active
if warnings.showwarning == self._patched_showwarning:
warnings.showwarning = ORIGINAL_SHOWWARNING
self._did_patch_showwarning = False
def set_mlflow_warnings_disablement_state_globally(self, disabled=True):
"""Disables (or re-enables) MLflow warnings globally across all threads.
Args:
disabled: If `True`, disables MLflow warnings globally across all threads.
If `False`, enables MLflow warnings globally across all threads.
"""
with self._state_lock:
self._mlflow_warnings_disabled_globally = disabled
self._modify_patch_state_if_necessary()
def set_mlflow_warnings_rerouting_state_globally(self, rerouted=True):
"""
Enables (or disables) rerouting of MLflow warnings to an MLflow event logger with level
WARNING (e.g. `logger.warning()`) globally across all threads.
Args:
rerouted: If `True`, enables MLflow warning rerouting globally across all threads.
If `False`, disables MLflow warning rerouting globally across all threads.
"""
with self._state_lock:
self._mlflow_warnings_rerouted_to_event_logs = rerouted
self._modify_patch_state_if_necessary()
def set_non_mlflow_warnings_disablement_state_for_current_thread(self, disabled=True):
"""Disables (or re-enables) non-MLflow warnings for the current thread.
Args:
disabled: If `True`, disables non-MLflow warnings for the current thread. If `False`,
enables non-MLflow warnings for the current thread. non-MLflow warning
behavior in other threads is unaffected.
"""
with self._state_lock:
if disabled:
self._disabled_threads.add(get_current_thread_id())
else:
self._disabled_threads.discard(get_current_thread_id())
self._modify_patch_state_if_necessary()
def set_non_mlflow_warnings_rerouting_state_for_current_thread(self, rerouted=True):
"""Enables (or disables) rerouting of non-MLflow warnings to an MLflow event logger with
level WARNING (e.g. `logger.warning()`) for the current thread.
Args:
rerouted: If `True`, enables non-MLflow warning rerouting for the current thread.
If `False`, disables non-MLflow warning rerouting for the current thread.
non-MLflow warning behavior in other threads is unaffected.
"""
with self._state_lock:
if rerouted:
self._rerouted_threads.add(get_current_thread_id())
else:
self._rerouted_threads.discard(get_current_thread_id())
self._modify_patch_state_if_necessary()
def get_warnings_disablement_state_for_current_thread(self):
"""
Returns:
True if non-MLflow warnings are disabled for the current thread. False otherwise.
"""
return get_current_thread_id() in self._disabled_threads
def get_warnings_rerouting_state_for_current_thread(self):
"""
Returns:
True if non-MLflow warnings are rerouted to an MLflow event logger with level
WARNING for the current thread. False otherwise.
"""
return get_current_thread_id() in self._rerouted_threads
_WARNINGS_CONTROLLER = _WarningsController()
| _WarningsController |
python | huggingface__transformers | src/transformers/models/nllb_moe/modeling_nllb_moe.py | {
"start": 33148,
"end": 38252
} | class ____(NllbMoePreTrainedModel):
"""
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`NllbMoeDecoderLayer`]
Args:
config:
NllbMoeConfig
embed_tokens (nn.Embedding):
output embedding
"""
_can_record_outputs = {
"hidden_states": NllbMoeDecoderLayer,
"attentions": OutputRecorder(NllbMoeAttention, layer_name="self_attn", index=1),
"router_logits": OutputRecorder(NllbMoeTop2Router, index=2),
"cross_attentions": OutputRecorder(NllbMoeAttention, layer_name="cross_attention", index=1),
}
def __init__(self, config: NllbMoeConfig):
super().__init__(config)
self.dropout = config.dropout
self.layerdrop = config.decoder_layerdrop
self.padding_idx = config.pad_token_id
self.max_target_positions = config.max_position_embeddings
embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
self.embed_tokens = NllbMoeScaledWordEmbedding(
config.vocab_size, config.d_model, self.padding_idx, embed_scale=embed_scale
)
self.embed_positions = NllbMoeSinusoidalPositionalEmbedding(
config.max_position_embeddings,
config.d_model,
self.padding_idx,
)
sparse_step = config.decoder_sparse_step
self.layers = nn.ModuleList()
for i in range(config.decoder_layers):
is_sparse = (i + 1) % sparse_step == 0 if sparse_step > 0 else False
self.layers.append(NllbMoeDecoderLayer(config, is_sparse, layer_idx=i))
self.layer_norm = nn.LayerNorm(config.d_model)
self.gradient_checkpointing = False
# Initialize weights and apply final processing
self.post_init()
@auto_docstring
@check_model_inputs()
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
encoder_hidden_states: Optional[torch.Tensor] = None,
encoder_attention_mask: Optional[torch.Tensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.Tensor] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple, BaseModelOutputWithPastAndCrossAttentions]:
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
input_shape = inputs_embeds.size()[:-1]
# initialize `past_key_values`
if use_cache and past_key_values is None:
past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
if cache_position is None:
cache_position = torch.arange(
past_key_values_length, past_key_values_length + input_shape[1], device=inputs_embeds.device
)
attention_mask = create_causal_mask(
config=self.config,
input_embeds=inputs_embeds,
attention_mask=attention_mask,
cache_position=cache_position,
past_key_values=past_key_values,
)
encoder_attention_mask = create_bidirectional_mask(
config=self.config,
input_embeds=inputs_embeds,
attention_mask=encoder_attention_mask,
encoder_hidden_states=encoder_hidden_states,
)
# embed positions
positions = self.embed_positions(input_ids, inputs_embeds, past_key_values_length)
positions = positions.to(inputs_embeds.device)
hidden_states = inputs_embeds + positions
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
for idx, decoder_layer in enumerate(self.layers):
# add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
dropout_probability = torch.rand([])
skip_the_layer = self.training and dropout_probability < self.layerdrop
if not skip_the_layer or synced_gpus:
hidden_states = decoder_layer(
hidden_states,
attention_mask,
encoder_hidden_states, # as a positional argument for gradient checkpointing
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
cache_position=cache_position,
**kwargs,
)
if skip_the_layer:
continue
last_hidden_states = self.layer_norm(hidden_states)
return MoEModelOutputWithPastAndCrossAttentions(
last_hidden_state=last_hidden_states, past_key_values=past_key_values
)
@auto_docstring
| NllbMoeDecoder |
python | huggingface__transformers | src/transformers/models/funnel/modeling_funnel.py | {
"start": 22520,
"end": 23318
} | class ____(nn.Module):
def __init__(self, config: FunnelConfig) -> None:
super().__init__()
self.linear_1 = nn.Linear(config.d_model, config.d_inner)
self.activation_function = ACT2FN[config.hidden_act]
self.activation_dropout = nn.Dropout(config.activation_dropout)
self.linear_2 = nn.Linear(config.d_inner, config.d_model)
self.dropout = nn.Dropout(config.hidden_dropout)
self.layer_norm = nn.LayerNorm(config.d_model, config.layer_norm_eps)
def forward(self, hidden: torch.Tensor) -> torch.Tensor:
h = self.linear_1(hidden)
h = self.activation_function(h)
h = self.activation_dropout(h)
h = self.linear_2(h)
h = self.dropout(h)
return self.layer_norm(hidden + h)
| FunnelPositionwiseFFN |
python | pydata__xarray | xarray/tests/arrays.py | {
"start": 373,
"end": 901
} | class ____(utils.NDArrayMixin, ExplicitlyIndexed):
"""Disallows any loading."""
def __init__(self, array):
self.array = array
def get_duck_array(self):
raise UnexpectedDataAccess("Tried accessing data")
def __array__(
self, dtype: np.typing.DTypeLike | None = None, /, *, copy: bool | None = None
) -> np.ndarray:
raise UnexpectedDataAccess("Tried accessing data")
def __getitem__(self, key):
raise UnexpectedDataAccess("Tried accessing data.")
| InaccessibleArray |
python | ansible__ansible | lib/ansible/config/manager.py | {
"start": 11980,
"end": 32459
} | class ____:
DEPRECATED = [] # type: list[tuple[str, dict[str, str]]]
WARNINGS = set() # type: set[str]
_errors: list[tuple[str, Exception]]
def __init__(self, conf_file=None, defs_file=None):
self._get_ini_config_value = functools.cache(self._get_ini_config_value)
self._base_defs = {}
self._plugins = {}
self._parsers = {}
self._config_file = conf_file
self._base_defs = self._read_config_yaml_file(defs_file or ('%s/base.yml' % os.path.dirname(__file__)))
_add_base_defs_deprecations(self._base_defs)
if self._config_file is None:
# set config using ini
self._config_file = find_ini_config_file(self.WARNINGS)
# consume configuration
if self._config_file:
# initialize parser and read config
self._parse_config_file()
self._errors = []
"""Deferred errors that will be turned into warnings."""
# ensure we always have config def entry
self._base_defs['CONFIG_FILE'] = {'default': None, 'type': 'path'}
def load_galaxy_server_defs(self, server_list):
def server_config_def(section, key, required, option_type):
config_def = {
'description': 'The %s of the %s Galaxy server' % (key, section),
'ini': [
{
'section': 'galaxy_server.%s' % section,
'key': key,
}
],
'env': [
{'name': 'ANSIBLE_GALAXY_SERVER_%s_%s' % (section.upper(), key.upper())},
],
'required': required,
'type': option_type,
}
if key in GALAXY_SERVER_ADDITIONAL:
config_def.update(GALAXY_SERVER_ADDITIONAL[key])
# ensure we always have a default timeout
if key == 'timeout' and 'default' not in config_def:
config_def['default'] = self.get_config_value('GALAXY_SERVER_TIMEOUT')
return config_def
if server_list:
for server_key in server_list:
if not server_key:
# To filter out empty strings or non truthy values as an empty server list env var is equal to [''].
continue
# Config definitions are looked up dynamically based on the C.GALAXY_SERVER_LIST entry. We look up the
# section [galaxy_server.<server>] for the values url, username, password, and token.
defs = dict((k, server_config_def(server_key, k, req, value_type)) for k, req, value_type in GALAXY_SERVER_DEF)
self.initialize_plugin_configuration_definitions('galaxy_server', server_key, defs)
def template_default(self, value, variables, key_name: str = '<unknown>'):
if isinstance(value, str) and (value.startswith('{{') and value.endswith('}}')) and variables is not None:
# template default values if possible
# NOTE: cannot use is_template due to circular dep
try:
# FIXME: This really should be using an immutable sandboxed native environment, not just native environment
template = NativeEnvironment().from_string(value)
value = template.render(variables)
except Exception as ex:
self._errors.append((f'Failed to template default for config {key_name}.', ex))
return value
def _read_config_yaml_file(self, yml_file):
# TODO: handle relative paths as relative to the directory containing the current playbook instead of CWD
# Currently this is only used with absolute paths to the `ansible/config` directory
yml_file = to_bytes(yml_file)
if os.path.exists(yml_file):
with open(yml_file, 'rb') as config_def:
return yaml_load(config_def) or {}
raise AnsibleError(
"Missing base YAML definition file (bad install?): %s" % to_native(yml_file))
def _parse_config_file(self, cfile=None):
""" return flat configuration settings from file(s) """
# TODO: take list of files with merge/nomerge
if cfile is None:
cfile = self._config_file
ftype = get_config_type(cfile)
if cfile is not None:
if ftype == 'ini':
self._parsers[cfile] = configparser.ConfigParser(inline_comment_prefixes=(';',))
with open(to_bytes(cfile), 'rb') as f:
try:
cfg_text = to_text(f.read(), errors='surrogate_or_strict')
except UnicodeError as e:
raise AnsibleOptionsError("Error reading config file(%s) because the config file was not utf8 encoded: %s" % (cfile, to_native(e)))
try:
self._parsers[cfile].read_string(cfg_text)
except configparser.Error as e:
raise AnsibleOptionsError("Error reading config file (%s): %s" % (cfile, to_native(e)))
# FIXME: this should eventually handle yaml config files
# elif ftype == 'yaml':
# with open(cfile, 'rb') as config_stream:
# self._parsers[cfile] = yaml_load(config_stream)
else:
raise AnsibleOptionsError("Unsupported configuration file type: %s" % to_native(ftype))
def _find_yaml_config_files(self):
""" Load YAML Config Files in order, check merge flags, keep origin of settings"""
pass
def get_plugin_options(self, plugin_type, name, keys=None, variables=None, direct=None):
options, dummy = self.get_plugin_options_and_origins(plugin_type, name, keys=keys, variables=variables, direct=direct)
return options
def get_plugin_options_and_origins(self, plugin_type, name, keys=None, variables=None, direct=None):
options = {}
origins = {}
defs = self.get_configuration_definitions(plugin_type=plugin_type, name=name)
for option in defs:
options[option], origins[option] = self.get_config_value_and_origin(option, plugin_type=plugin_type, plugin_name=name, keys=keys,
variables=variables, direct=direct)
return options, origins
def get_plugin_vars(self, plugin_type, name):
pvars = []
for pdef in self.get_configuration_definitions(plugin_type=plugin_type, name=name).values():
if 'vars' in pdef and pdef['vars']:
for var_entry in pdef['vars']:
pvars.append(var_entry['name'])
return pvars
def get_plugin_options_from_var(self, plugin_type, name, variable):
options = []
for option_name, pdef in self.get_configuration_definitions(plugin_type=plugin_type, name=name).items():
if 'vars' in pdef and pdef['vars']:
for var_entry in pdef['vars']:
if variable == var_entry['name']:
options.append(option_name)
return options
def get_configuration_definition(self, name, plugin_type=None, plugin_name=None):
ret = {}
if plugin_type is None:
ret = self._base_defs.get(name, None)
elif plugin_name is None:
ret = self._plugins.get(plugin_type, {}).get(name, None)
else:
ret = self._plugins.get(plugin_type, {}).get(plugin_name, {}).get(name, None)
return ret
def has_configuration_definition(self, plugin_type, name):
has = False
if plugin_type in self._plugins:
has = (name in self._plugins[plugin_type])
return has
def get_configuration_definitions(self, plugin_type=None, name=None, ignore_private=False):
""" just list the possible settings, either base or for specific plugins or plugin """
ret = {}
if plugin_type is None:
ret = self._base_defs
elif name is None:
ret = self._plugins.get(plugin_type, {})
else:
ret = self._plugins.get(plugin_type, {}).get(name, {})
if ignore_private: # ignore 'test' config entries, they should not change runtime behaviors
for cdef in list(ret.keys()):
if cdef.startswith('_Z_'):
del ret[cdef]
return ret
def _loop_entries(self, container, entry_list):
""" repeat code for value entry assignment """
value = None
origin = None
for entry in entry_list:
name = entry.get('name')
try:
temp_value = container.get(name, None)
except UnicodeEncodeError:
self.WARNINGS.add(u'value for config entry {0} contains invalid characters, ignoring...'.format(to_text(name)))
continue
if temp_value is not None: # only set if entry is defined in container
value = temp_value
origin = name
# deal with deprecation of setting source, if used
if 'deprecated' in entry:
self.DEPRECATED.append((entry['name'], entry['deprecated']))
return value, origin
def get_config_value(self, config, cfile=None, plugin_type=None, plugin_name=None, keys=None, variables=None, direct=None):
""" wrapper """
try:
value, _drop = self.get_config_value_and_origin(config, cfile=cfile, plugin_type=plugin_type, plugin_name=plugin_name,
keys=keys, variables=variables, direct=direct)
except AnsibleError:
raise
except Exception as ex:
raise AnsibleError(f"Unhandled exception when retrieving {config!r}.") from ex
return value
def get_config_default(self, config: str, plugin_type: str | None = None, plugin_name: str | None = None) -> t.Any:
"""Return the default value for the specified configuration."""
return self.get_configuration_definitions(plugin_type, plugin_name)[config]['default']
def get_config_value_and_origin(self, config, cfile=None, plugin_type=None, plugin_name=None, keys=None, variables=None, direct=None):
""" Given a config key figure out the actual value and report on the origin of the settings """
if cfile is None:
# use default config
cfile = self._config_file
if config == 'CONFIG_FILE':
return cfile, ''
# Note: sources that are lists listed in low to high precedence (last one wins)
value = None
origin = None
origin_ftype = None
defs = self.get_configuration_definitions(plugin_type=plugin_type, name=plugin_name)
if config in defs:
aliases = defs[config].get('aliases', [])
# direct setting via plugin arguments, can set to None so we bypass rest of processing/defaults
if direct:
if config in direct:
value = direct[config]
origin = 'Direct'
else:
direct_aliases = [direct[alias] for alias in aliases if alias in direct]
if direct_aliases:
value = direct_aliases[0]
origin = 'Direct'
if value is None and variables and defs[config].get('vars'):
# Use 'variable overrides' if present, highest precedence, but only present when querying running play
value, origin = self._loop_entries(variables, defs[config]['vars'])
origin = 'var: %s' % origin
# use playbook keywords if you have em
if value is None and defs[config].get('keyword') and keys:
value, origin = self._loop_entries(keys, defs[config]['keyword'])
origin = 'keyword: %s' % origin
# automap to keywords
# TODO: deprecate these in favor of explicit keyword above
if value is None and keys:
if config in keys:
value = keys[config]
keyword = config
elif aliases:
for alias in aliases:
if alias in keys:
value = keys[alias]
keyword = alias
break
if value is not None:
origin = 'keyword: %s' % keyword
if value is None and 'cli' in defs[config]:
# avoid circular import .. until valid
from ansible import context
value, origin = self._loop_entries(context.CLIARGS, defs[config]['cli'])
origin = 'cli: %s' % origin
# env vars are next precedence
if value is None and defs[config].get('env'):
value, origin = self._loop_entries(os.environ, defs[config]['env'])
value = _tags.TrustedAsTemplate().tag(value)
origin = 'env: %s' % origin
# try config file entries next, if we have one
if self._parsers.get(cfile, None) is None:
self._parse_config_file(cfile)
# attempt to read from config file
if value is None and cfile is not None:
ftype = get_config_type(cfile)
if ftype and defs[config].get(ftype):
try:
for entry in defs[config][ftype]:
# load from config
if ftype == 'ini':
temp_value = self._get_ini_config_value(cfile, entry.get('section', 'defaults'), entry['key'])
elif ftype == 'yaml':
raise AnsibleError('YAML configuration type has not been implemented yet')
else:
raise AnsibleError('Invalid configuration file type: %s' % ftype)
if temp_value is not None:
# set value and origin
value = temp_value
origin = cfile
origin_ftype = ftype
if 'deprecated' in entry:
if ftype == 'ini':
self.DEPRECATED.append(('[%s]%s' % (entry['section'], entry['key']), entry['deprecated']))
else:
raise AnsibleError('Unimplemented file type: %s' % ftype)
except Exception as e:
sys.stderr.write("Error while loading config %s: %s" % (cfile, to_native(e)))
# set default if we got here w/o a value
if value is None:
if defs[config].get('required', False):
if not plugin_type or config not in INTERNAL_DEFS.get(plugin_type, {}):
raise AnsibleRequiredOptionError(f"Required config {_get_config_label(plugin_type, plugin_name, config)} not provided.")
else:
origin = 'default'
value = self.template_default(defs[config].get('default'), variables, key_name=_get_config_label(plugin_type, plugin_name, config))
try:
# ensure correct type, can raise exceptions on mismatched types
value = ensure_type(value, defs[config].get('type'), origin=origin, origin_ftype=origin_ftype)
except ValueError as ex:
if origin.startswith('env:') and value == '':
# this is empty env var for non string so we can set to default
origin = 'default'
value = ensure_type(defs[config].get('default'), defs[config].get('type'), origin=origin, origin_ftype=origin_ftype)
else:
raise AnsibleOptionsError(f'Config {_get_config_label(plugin_type, plugin_name, config)} from {origin!r} has an invalid value.') from ex
# deal with restricted values
if value is not None and 'choices' in defs[config] and defs[config]['choices'] is not None:
invalid_choices = True # assume the worst!
if defs[config].get('type') == 'list':
# for a list type, compare all values in type are allowed
invalid_choices = not all(choice in defs[config]['choices'] for choice in value)
else:
# these should be only the simple data types (string, int, bool, float, etc) .. ignore dicts for now
invalid_choices = value not in defs[config]['choices']
if invalid_choices:
if isinstance(defs[config]['choices'], Mapping):
valid = ', '.join([to_text(k) for k in defs[config]['choices'].keys()])
elif isinstance(defs[config]['choices'], str):
valid = defs[config]['choices']
elif isinstance(defs[config]['choices'], Sequence):
valid = ', '.join([to_text(c) for c in defs[config]['choices']])
else:
valid = defs[config]['choices']
raise AnsibleOptionsError(f'Invalid value {value!r} for config {_get_config_label(plugin_type, plugin_name, config)}.',
help_text=f'Valid values are: {valid}')
# deal with deprecation of the setting
if 'deprecated' in defs[config] and origin != 'default':
self.DEPRECATED.append((config, defs[config].get('deprecated')))
else:
raise AnsibleUndefinedConfigEntry(f'No config definition exists for {_get_config_label(plugin_type, plugin_name, config)}.')
if not _tags.Origin.is_tagged_on(value):
value = _tags.Origin(description=f'<Config {origin}>').tag(value)
return value, origin
def initialize_plugin_configuration_definitions(self, plugin_type, name, defs):
if plugin_type not in self._plugins:
self._plugins[plugin_type] = {}
self._plugins[plugin_type][name] = defs
def _get_ini_config_value(self, config_file: str, section: str, option: str) -> t.Any:
"""
Fetch `option` from the specified `section`.
Returns `None` if the specified `section` or `option` are not present.
Origin and TrustedAsTemplate tags are applied to returned values.
CAUTION: Although INI sourced configuration values are trusted for templating, that does not automatically mean they will be templated.
It is up to the code consuming configuration values to apply templating if required.
"""
parser = self._parsers[config_file]
value = parser.get(section, option, raw=True, fallback=None)
if value is not None:
value = self._apply_tags(value, section, option)
return value
def _apply_tags(self, value: str, section: str, option: str) -> t.Any:
"""Apply origin and trust to the given `value` sourced from the stated `section` and `option`."""
description = f'section {section!r} option {option!r}'
origin = _tags.Origin(path=self._config_file, description=description)
tags = [origin, _tags.TrustedAsTemplate()]
value = AnsibleTagHelper.tag(value, tags)
return value
@staticmethod
def get_deprecated_msg_from_config(dep_docs, include_removal=False, collection_name=None):
removal = ''
if include_removal:
if 'removed_at_date' in dep_docs:
removal = f"Will be removed in a release after {dep_docs['removed_at_date']}\n\t"
elif collection_name:
removal = f"Will be removed in: {collection_name} {dep_docs['removed_in']}\n\t"
else:
removal = f"Will be removed in: Ansible {dep_docs['removed_in']}\n\t"
# TODO: choose to deprecate either singular or plural
alt = dep_docs.get('alternatives', dep_docs.get('alternative', 'none'))
return f"Reason: {dep_docs['why']}\n\t{removal}Alternatives: {alt}"
| ConfigManager |
python | langchain-ai__langchain | libs/core/langchain_core/language_models/base.py | {
"start": 1117,
"end": 3072
} | class ____(TypedDict, total=False):
"""LangSmith parameters for tracing."""
ls_provider: str
"""Provider of the model."""
ls_model_name: str
"""Name of the model."""
ls_model_type: Literal["chat", "llm"]
"""Type of the model. Should be 'chat' or 'llm'."""
ls_temperature: float | None
"""Temperature for generation."""
ls_max_tokens: int | None
"""Max tokens for generation."""
ls_stop: list[str] | None
"""Stop words for generation."""
@cache # Cache the tokenizer
def get_tokenizer() -> Any:
"""Get a GPT-2 tokenizer instance.
This function is cached to avoid re-loading the tokenizer every time it is called.
Raises:
ImportError: If the transformers package is not installed.
Returns:
The GPT-2 tokenizer instance.
"""
if not _HAS_TRANSFORMERS:
msg = (
"Could not import transformers python package. "
"This is needed in order to calculate get_token_ids. "
"Please install it with `pip install transformers`."
)
raise ImportError(msg)
# create a GPT-2 tokenizer instance
return GPT2TokenizerFast.from_pretrained("gpt2")
def _get_token_ids_default_method(text: str) -> list[int]:
"""Encode the text into token IDs."""
# get the cached tokenizer
tokenizer = get_tokenizer()
# tokenize the text using the GPT-2 tokenizer
return tokenizer.encode(text)
LanguageModelInput = PromptValue | str | Sequence[MessageLikeRepresentation]
"""Input to a language model."""
LanguageModelOutput = BaseMessage | str
"""Output from a language model."""
LanguageModelLike = Runnable[LanguageModelInput, LanguageModelOutput]
"""Input/output interface for a language model."""
LanguageModelOutputVar = TypeVar("LanguageModelOutputVar", AIMessage, str)
"""Type variable for the output of a language model."""
def _get_verbosity() -> bool:
return get_verbose()
| LangSmithParams |
python | pytorch__pytorch | test/distributed/_shard/sharding_spec/test_sharding_spec.py | {
"start": 1251,
"end": 19870
} | class ____(TestCase):
@skip_but_pass_in_sandcastle_if(not TEST_MULTIGPU, "2 CUDA GPUs are needed")
def test_device_placement(self):
# valid devices
DevicePlacementSpec("cuda:0")
DevicePlacementSpec(torch.device(0))
DevicePlacementSpec(torch.device("cuda:0"))
DevicePlacementSpec("rank:0/cuda:0")
DevicePlacementSpec("rank:0/cpu")
DevicePlacementSpec("rank:0")
# invalid devices
with self.assertRaisesRegex(ValueError, "Could not parse remote_device"):
DevicePlacementSpec("cuda:foo")
with self.assertRaisesRegex(ValueError, "Could not parse remote_device"):
DevicePlacementSpec("foo:0")
with self.assertRaisesRegex(RuntimeError, "Invalid device string"):
DevicePlacementSpec("rank:0/cuda:foo")
with self.assertRaisesRegex(RuntimeError, "Invalid device string"):
DevicePlacementSpec("rank:0/cpu2")
@skip_but_pass_in_sandcastle_if(not TEST_MULTIGPU, "2 CUDA GPUs are needed")
def test_chunked_sharding_spec(self):
# Test valid specs.
ChunkShardingSpec(0, [torch.device(0), torch.device(1)])
ChunkShardingSpec(0, [torch.device("cuda:0"), torch.device("cuda:1")])
ChunkShardingSpec(-1, ["cuda:0", "cuda:1"])
ChunkShardingSpec(0, ["rank:0/cuda:0", "rank:0/cuda:1"])
ChunkShardingSpec(0, ["rank:0", "rank:1"])
ChunkShardingSpec(0, ["rank:0/cpu", "rank:1/cpu"])
# Test unimplemented error
with self.assertRaisesRegex(NotImplementedError, "not support named dimension"):
# Named dimension.
ChunkShardingSpec("N", ["cuda:0", "cuda:1"])
# Test invalid specs
with self.assertRaisesRegex(ValueError, "needs to be an integer"):
ChunkShardingSpec(None, ["cuda:0", "cuda:1"])
with self.assertRaisesRegex(ValueError, "needs to be an integer"):
ChunkShardingSpec({}, ["cuda:0", "cuda:1"])
with self.assertRaisesRegex(ValueError, "Could not parse remote_device"):
ChunkShardingSpec(0, ["random:0", "cuda:1"])
with self.assertRaisesRegex(ValueError, "Could not parse remote_device"):
ChunkShardingSpec(0, ["cuda:foo", "cuda:1"])
with self.assertRaisesRegex(ValueError, "Could not parse remote_device"):
ChunkShardingSpec(0, ["rank:foo", "cuda:1"])
with self.assertRaisesRegex(RuntimeError, "Expected one of"):
ChunkShardingSpec(0, ["rank:0/foo", "cuda:1"])
with self.assertRaisesRegex(RuntimeError, "Expected one of"):
ChunkShardingSpec(0, ["rank:0/random:0", "cuda:1"])
with self.assertRaisesRegex(RuntimeError, "Invalid device string"):
ChunkShardingSpec(0, ["rank:0/cuda:foo", "cuda:1"])
@skip_but_pass_in_sandcastle_if(not TEST_MULTIGPU, "2 CUDA GPUs are needed")
def test_enumerable_sharding_spec(self):
# test valid specs
# test row-wise sharding
spec = EnumerableShardingSpec(
[
ShardMetadata(
shard_offsets=[0, 0],
shard_sizes=[5, 5],
placement="cuda:0",
),
ShardMetadata(
shard_offsets=[5, 0],
shard_sizes=[5, 5],
placement="cuda:1",
),
]
)
check_tensor(spec.shards, torch.rand(10, 5).size())
# test row and column sharding
spec = EnumerableShardingSpec(
[
ShardMetadata(
shard_offsets=[0, 0],
shard_sizes=[3, 3],
placement="cuda:0",
),
ShardMetadata(
shard_offsets=[0, 3],
shard_sizes=[3, 3],
placement="cuda:1",
),
ShardMetadata(
shard_offsets=[3, 0],
shard_sizes=[3, 3],
placement="cuda:2",
),
ShardMetadata(
shard_offsets=[3, 3],
shard_sizes=[3, 3],
placement="cuda:3",
),
]
)
check_tensor(spec.shards, torch.rand(6, 6).size())
# test uneven shard sizes.
spec = EnumerableShardingSpec(
[
ShardMetadata(
shard_offsets=[0, 0],
shard_sizes=[2, 4],
placement="cuda:0",
),
ShardMetadata(
shard_offsets=[0, 4],
shard_sizes=[4, 2],
placement="cuda:1",
),
ShardMetadata(
shard_offsets=[2, 0],
shard_sizes=[4, 4],
placement="cuda:2",
),
ShardMetadata(
shard_offsets=[4, 4],
shard_sizes=[2, 2],
placement="cuda:3",
),
]
)
check_tensor(spec.shards, torch.rand(6, 6).size())
# test invalid sharding
with self.assertRaisesRegex(ValueError, "Could not parse remote_device"):
ShardMetadata(shard_offsets=[0], shard_sizes=[1], placement="cuda:foo")
with self.assertRaisesRegex(ValueError, "same number of elements"):
ShardMetadata(shard_offsets=[0, 0], shard_sizes=[1], placement="cuda:0")
with self.assertRaisesRegex(ValueError, "shard_offsets should be >=0"):
ShardMetadata(shard_offsets=[-1, 0], shard_sizes=[1, 1], placement="cuda:0")
with self.assertRaisesRegex(ValueError, "shard_sizes should be >= 0"):
ShardMetadata(shard_offsets=[0, 0], shard_sizes=[-1, 1], placement="cuda:0")
with self.assertRaisesRegex(ValueError, "Empty shard list provided"):
EnumerableShardingSpec([])
with self.assertRaisesRegex(ValueError, "Found inconsistent ranks for shards"):
EnumerableShardingSpec(
[
ShardMetadata(
shard_offsets=[0, 0], shard_sizes=[1, 1], placement="cpu"
),
ShardMetadata(
shard_offsets=[0, 0, 0], shard_sizes=[1, 1, 1], placement="cpu"
),
]
)
with self.assertRaisesRegex(ValueError, "Shards.*overlap"):
EnumerableShardingSpec(
[
ShardMetadata(
shard_offsets=[0, 0], shard_sizes=[3, 3], placement="cpu"
),
ShardMetadata(
shard_offsets=[2, 0], shard_sizes=[3, 3], placement="cpu"
),
]
)
spec = EnumerableShardingSpec(
[
ShardMetadata(
shard_offsets=[0, 0],
shard_sizes=[5, 5],
placement="cuda:0",
),
ShardMetadata(
shard_offsets=[5, 0],
shard_sizes=[5, 5],
placement="cuda:1",
),
]
)
with self.assertRaisesRegex(ValueError, "Rank of tensor is.*but shards rank"):
check_tensor(spec.shards, torch.rand(10, 10, 10).size())
spec = EnumerableShardingSpec(
[
ShardMetadata(
shard_offsets=[0, 0],
shard_sizes=[5, 5],
placement="cuda:0",
),
ShardMetadata(
shard_offsets=[5, 0],
shard_sizes=[5, 5],
placement="cuda:1",
),
]
)
with self.assertRaisesRegex(ValueError, "exceeds tensor dim"):
check_tensor(spec.shards, torch.rand(10, 3).size())
spec = EnumerableShardingSpec(
[
ShardMetadata(
shard_offsets=[0, 0],
shard_sizes=[5, 5],
placement="cuda:0",
),
ShardMetadata(
shard_offsets=[5, 5],
shard_sizes=[5, 5],
placement="cuda:1",
),
]
)
with self.assertRaisesRegex(ValueError, "does not match tensor volume"):
check_tensor(spec.shards, torch.rand(10, 10).size())
def test_get_split_size(self):
self.assertEqual(3, get_split_size(11, 4))
self.assertEqual(3, get_split_size(12, 4))
self.assertEqual(4, get_split_size(13, 4))
self.assertEqual(2, get_split_size(5, 4))
self.assertEqual(11, get_split_size(11, 1))
self.assertEqual(1, get_split_size(11, 11))
def test_get_chunked_dim_size(self):
self.assertEqual(3, get_chunked_dim_size(11, 3, 0))
self.assertEqual(2, get_chunked_dim_size(11, 3, 3))
self.assertEqual(4, get_chunked_dim_size(13, 4, 0))
self.assertEqual(1, get_chunked_dim_size(13, 4, 3))
self.assertEqual(0, get_chunked_dim_size(5, 2, 3))
def test_get_chunk_sharding_params(self):
ranks = [
"rank:0/cuda:0",
"rank:1/cuda:1",
"rank:2/cuda:2",
"rank:3/cuda:3",
]
spec = ChunkShardingSpec(
dim=0,
placements=ranks,
)
result = get_chunk_sharding_params(21, 4, spec, 1)
self.assertEqual(6, result[0])
self.assertEqual(6, result[1])
result = get_chunk_sharding_params(21, 4, spec, 3)
self.assertEqual(18, result[0])
self.assertEqual(3, result[1])
ranks[1], ranks[2] = ranks[2], ranks[1]
ranks[0], ranks[3] = ranks[3], ranks[0]
spec.placements = ranks
result = get_chunk_sharding_params(21, 4, spec, 1)
self.assertEqual(12, result[0])
self.assertEqual(6, result[1])
result = get_chunk_sharding_params(21, 4, spec, 3)
self.assertEqual(0, result[0])
self.assertEqual(6, result[1])
def _infer_enum_sharding_spec_case(self):
shards_metadata = [
ShardMetadata(
shard_offsets=[0, 0],
shard_sizes=[5, 5],
placement="cuda:0",
),
ShardMetadata(
shard_offsets=[5, 0],
shard_sizes=[10, 5],
placement="cuda:1",
),
]
spec = _infer_sharding_spec_from_shards_metadata(shards_metadata)
self.assertTrue(isinstance(spec, EnumerableShardingSpec))
self.assertEqual(spec.shards, shards_metadata)
shards_metadata = [
ShardMetadata(
shard_offsets=[0],
shard_sizes=[16],
placement="cuda:0",
),
ShardMetadata(
shard_offsets=[16],
shard_sizes=[9],
placement="cuda:1",
),
]
spec = _infer_sharding_spec_from_shards_metadata(shards_metadata)
self.assertTrue(isinstance(spec, EnumerableShardingSpec))
self.assertEqual(spec.shards, shards_metadata)
shards_metadata = [
ShardMetadata(
shard_offsets=[0, 0],
shard_sizes=[5, 5],
placement="rank:0/cuda:0",
),
ShardMetadata(
shard_offsets=[5, 0],
shard_sizes=[5, 5],
placement="rank:1/cuda:1",
),
ShardMetadata(
shard_offsets=[0, 5],
shard_sizes=[5, 5],
placement="rank:2/cuda:2",
),
ShardMetadata(
shard_offsets=[5, 5],
shard_sizes=[5, 5],
placement="rank:3/cuda:3",
),
]
spec = _infer_sharding_spec_from_shards_metadata(shards_metadata)
self.assertTrue(isinstance(spec, EnumerableShardingSpec))
self.assertEqual(spec.shards, shards_metadata)
def _infer_chunk_sharding_spec_case(self, placements, sharding_dim, st_size):
world_size = len(placements)
split_size = get_split_size(st_size[sharding_dim], world_size)
shards_metadata = [None] * world_size
for idx, placement in enumerate(placements):
shard_size = copy.deepcopy(st_size)
offsets = [0] * len(st_size)
offsets[sharding_dim] = split_size * idx
shard_size[sharding_dim] = get_chunked_dim_size(
st_size[sharding_dim], split_size, idx
)
shards_metadata[placement.rank()] = ShardMetadata(
shard_offsets=offsets,
shard_sizes=shard_size,
placement=placement,
)
spec = _infer_sharding_spec_from_shards_metadata(shards_metadata)
self.assertTrue(isinstance(spec, ChunkShardingSpec))
self.assertEqual(spec.dim, sharding_dim)
self.assertEqual(spec.placements, placements)
def test_infer_sharding_spec_from_shards_metadata(self):
self._infer_enum_sharding_spec_case()
chunk_specs = _chunk_sharding_specs_list_for_test([0, 0, 1, 1], seed=31)
for spec in chunk_specs:
self._infer_chunk_sharding_spec_case(spec.placements, 0, [4, 16])
self._infer_chunk_sharding_spec_case(spec.placements, 0, [5, 15, 16])
self._infer_chunk_sharding_spec_case(spec.placements, 1, [12, 16])
self._infer_chunk_sharding_spec_case(spec.placements, 2, [4, 18, 15])
self._infer_chunk_sharding_spec_case(spec.placements, 3, [7, 12, 16, 37])
self._infer_chunk_sharding_spec_case(
spec.placements, 4, [50, 4, 18, 15, 77]
)
def test_check_overlapping(self):
shards = [
ShardMetadata(
shard_offsets=[0, 0],
shard_sizes=[5, 5],
placement="cuda:0",
),
ShardMetadata(
shard_offsets=[5, 0],
shard_sizes=[5, 5],
placement="cuda:1",
),
]
validate_non_overlapping_shards_metadata(shards)
shards = [
ShardMetadata(
shard_offsets=[0, 0],
shard_sizes=[5, 5],
placement="cuda:0",
),
ShardMetadata(
shard_offsets=[4, 0],
shard_sizes=[5, 5],
placement="cuda:1",
),
]
with self.assertRaisesRegex(ValueError, "overlap"):
validate_non_overlapping_shards_metadata(shards)
shards = [
ShardMetadata(
shard_offsets=[0, 0],
shard_sizes=[5, 5],
placement="cuda:0",
),
ShardMetadata(
shard_offsets=[0, 4],
shard_sizes=[5, 5],
placement="cuda:1",
),
]
with self.assertRaisesRegex(ValueError, "overlap"):
validate_non_overlapping_shards_metadata(shards)
shards = [
ShardMetadata(
shard_offsets=[5, 0, 5],
shard_sizes=[5, 5, 5],
placement="cuda:0",
),
ShardMetadata(
shard_offsets=[5, 5, 5],
shard_sizes=[5, 5, 5],
placement="cuda:1",
),
]
validate_non_overlapping_shards_metadata(shards)
shards = [
ShardMetadata(
shard_offsets=[5, 0, 5],
shard_sizes=[5, 5, 5],
placement="cuda:0",
),
ShardMetadata(
shard_offsets=[5, 4, 5],
shard_sizes=[5, 5, 5],
placement="cuda:1",
),
]
with self.assertRaisesRegex(ValueError, "overlap"):
validate_non_overlapping_shards_metadata(shards)
shards = [
ShardMetadata(
shard_offsets=[5, 0, 5],
shard_sizes=[5, 5, 5],
placement="cuda:0",
),
ShardMetadata(
shard_offsets=[5, 4, 9],
shard_sizes=[5, 5, 5],
placement="cuda:1",
),
]
with self.assertRaisesRegex(ValueError, "overlap"):
validate_non_overlapping_shards_metadata(shards)
shards = [
ShardMetadata(
shard_offsets=[0, 0],
shard_sizes=[5, 5],
placement="cuda:0",
),
ShardMetadata(
shard_offsets=[0, 5],
shard_sizes=[5, 5],
placement="cuda:1",
),
ShardMetadata(
shard_offsets=[5, 0],
shard_sizes=[5, 5],
placement="cuda:2",
),
ShardMetadata(
shard_offsets=[5, 5],
shard_sizes=[5, 5],
placement="cuda:3",
),
]
validate_non_overlapping_shards_metadata(shards)
shards = [
ShardMetadata(
shard_offsets=[0, 0],
shard_sizes=[5, 5],
placement="cuda:0",
),
ShardMetadata(
shard_offsets=[5, 5],
shard_sizes=[5, 5],
placement="cuda:1",
),
]
validate_non_overlapping_shards_metadata(shards)
shards = [
ShardMetadata(
shard_offsets=[0, 0, 0],
shard_sizes=[5, 5, 5],
placement="cuda:0",
),
ShardMetadata(
shard_offsets=[5, 0, 0],
shard_sizes=[5, 5, 5],
placement="cuda:1",
),
ShardMetadata(
shard_offsets=[10, 0, 0],
shard_sizes=[5, 5, 5],
placement="cuda:2",
),
ShardMetadata(
shard_offsets=[10, 3, 0],
shard_sizes=[5, 5, 5],
placement="cuda:3",
),
]
with self.assertRaisesRegex(ValueError, "overlap"):
validate_non_overlapping_shards_metadata(shards)
# Custom ShardingSpec, an simple example to do grid sharding
@dataclass
| TestShardingSpec |
python | pytorch__pytorch | test/distributed/_shard/sharded_tensor/test_sharded_tensor.py | {
"start": 85361,
"end": 120165
} | class ____(ShardedTensorTestBase):
@with_comms(init_rpc=False)
@skip_if_lt_x_gpu(4)
@requires_nccl()
def test_local_shards(self):
shard_offsets = [(self.rank // 2) * 5, (self.rank % 2) * 5]
local_shard_metadata = ShardMetadata(
shard_offsets=shard_offsets,
shard_sizes=[5, 5],
placement=f"rank:{self.rank}/cuda:{self.rank}",
)
local_tensor = torch.randn(5, 5, device=f"cuda:{self.rank}")
local_shard = sharded_tensor.Shard(local_tensor, local_shard_metadata)
local_shard_from_offsets = sharded_tensor.Shard.from_tensor_and_offsets(
local_tensor, shard_offsets=shard_offsets, rank=self.rank
)
self.assertEqual(local_shard.metadata, local_shard_from_offsets.metadata)
wrong_local_shard_metadata = ShardMetadata(
shard_offsets=shard_offsets,
shard_sizes=[6, 5],
placement=f"rank:{self.rank}/cuda:{self.rank}",
)
with self.assertRaisesRegex(ValueError, "Shard tensor size does not match"):
sharded_tensor.Shard(local_tensor, metadata=wrong_local_shard_metadata)
@skipIfRocm
@with_comms
@skip_if_lt_x_gpu(4)
@requires_nccl()
def test_init_from_local_shards(self):
local_shard_metadata = ShardMetadata(
shard_offsets=[(self.rank // 2) * 5, (self.rank % 2) * 5],
shard_sizes=[5, 5],
placement=f"rank:{self.rank}/cuda:{self.rank}",
)
local_shards = [
sharded_tensor.Shard(
torch.randn(5, 5, device=f"cuda:{self.rank}"), local_shard_metadata
)
]
st = sharded_tensor.init_from_local_shards(
local_shards, [10, 10], init_rrefs=True
)
self.assertEqual((10, 10), st.size())
self.assertEqual(1, len(st.local_shards()))
# Verify local shard.
local_shard = st.local_shards()[0]
self.assertEqual(torch.device(f"cuda:{self.rank}"), local_shard.tensor.device)
self.assertEqual((5, 5), local_shard.tensor.size())
# Verify local shard metadata.
self.assertEqual(
(self.rank // 2 * 5, (self.rank % 2) * 5),
local_shard.metadata.shard_offsets,
)
self.assertEqual((5, 5), local_shard.metadata.shard_sizes)
self.assertEqual(
f"rank:{self.rank}/cuda:{self.rank}", str(local_shard.metadata.placement)
)
# Verify global metadata.
shards_metadata = st.metadata().shards_metadata
self.assertEqual(4, len(shards_metadata))
for rank, shard_metadata in enumerate(shards_metadata):
self.assertEqual(
(rank // 2 * 5, (rank % 2) * 5), shard_metadata.shard_offsets
)
self.assertEqual((5, 5), shard_metadata.shard_sizes)
self.assertEqual(f"rank:{rank}/cuda:{rank}", str(shard_metadata.placement))
# Validate remote shards.
remote_shards = st.remote_shards()
self.assertEqual(3, len(remote_shards))
for rpc_rank, shards in remote_shards.items():
self.assertEqual(1, len(shards))
for remote_shard in shards:
self.assertEqual(rpc_rank, remote_shard.owner().id)
shard = remote_shard.to_here()
self.assertEqual((5, 5), shard.tensor.size())
@skipIfRocm
@with_comms(init_rpc=False)
@skip_if_lt_x_gpu(4)
@requires_nccl()
def test_recalc_for_metadata(self):
shard_sizes = [0, 5] # test 2 different shard sizes
for shard_size in shard_sizes:
local_shard_metadata = ShardMetadata(
shard_offsets=[0, 0],
shard_sizes=[shard_size, shard_size],
placement=f"rank:{self.rank}/cuda:{self.rank}",
)
local_shards = [
sharded_tensor.Shard(
torch.randn(shard_size, shard_size, device=f"cuda:{self.rank}"),
local_shard_metadata,
)
]
st = sharded_tensor.init_from_local_shards(local_shards, None, None)
self.assertEqual((shard_size * 4, shard_size), st.size())
self.assertEqual(1, len(st.local_shards()))
# Verify local shard.
local_shard = st.local_shards()[0]
self.assertEqual(
torch.device(f"cuda:{self.rank}"), local_shard.tensor.device
)
self.assertEqual((shard_size, shard_size), local_shard.tensor.size())
# Verify local shard metadata.
self.assertEqual(
(self.rank * shard_size, 0),
local_shard.metadata.shard_offsets,
)
self.assertEqual((shard_size, shard_size), local_shard.metadata.shard_sizes)
self.assertEqual(
f"rank:{self.rank}/cuda:{self.rank}",
str(local_shard.metadata.placement),
)
# Verify global metadata.
shards_metadata = st.metadata().shards_metadata
self.assertEqual(4, len(shards_metadata))
for rank, shard_metadata in enumerate(shards_metadata):
self.assertEqual((rank * shard_size, 0), shard_metadata.shard_offsets)
self.assertEqual((shard_size, shard_size), shard_metadata.shard_sizes)
self.assertEqual(
f"rank:{rank}/cuda:{rank}", str(shard_metadata.placement)
)
with self.assertRaises(ValueError):
st = sharded_tensor.init_from_local_shards(local_shards)
@skipIfRocm
@with_comms(init_rpc=False)
@skip_if_lt_x_gpu(4)
@requires_nccl()
def test_init_from_local_shards_with_different_glb_size(self):
wrong_offset_local_shard_metadata = ShardMetadata(
shard_offsets=[0, 0],
shard_sizes=[5, 5],
placement=f"rank:{self.rank}/cuda:{self.rank}",
)
wrong_offset_local_shards = [
sharded_tensor.Shard(
torch.randn(5, 5, device=f"cuda:{self.rank}"),
wrong_offset_local_shard_metadata,
)
]
with self.assertRaises(ValueError):
sharded_tensor.init_from_local_shards(wrong_offset_local_shards, 0, 0)
local_shard_metadata = ShardMetadata(
shard_offsets=[self.rank * 5, 0],
shard_sizes=[5, 5],
placement=f"rank:{self.rank}/cuda:{self.rank}",
)
local_shards = [
sharded_tensor.Shard(
torch.randn(5, 5, device=f"cuda:{self.rank}"), local_shard_metadata
)
]
with self.assertRaises(ValueError):
sharded_tensor.init_from_local_shards(local_shards, 0, 0)
@skipIfRocm
@with_comms(init_rpc=False)
@skip_if_lt_x_gpu(4)
@requires_nccl()
def test_non_rw_sharded_recalc_for_metadata(self):
local_shard_metadata = ShardMetadata(
shard_offsets=[(self.rank // 2) * 5, (self.rank % 2) * 5],
shard_sizes=[5, 5],
placement=f"rank:{self.rank}/cuda:{self.rank}",
)
local_shards = [
sharded_tensor.Shard(
torch.randn(5, 5, device=f"cuda:{self.rank}"), local_shard_metadata
)
]
st = sharded_tensor.init_from_local_shards(local_shards, None, 5)
if self.rank == 0:
self.assertEqual(
st.local_shards()[0].metadata.shard_offsets,
local_shard_metadata.shard_offsets,
)
else:
self.assertNotEqual(
st.local_shards()[0].metadata.shard_offsets,
local_shard_metadata.shard_offsets,
)
self.assertEqual(
st.local_shards()[0].metadata.shard_sizes, local_shard_metadata.shard_sizes
)
self.assertEqual(
st.local_shards()[0].metadata.placement, local_shard_metadata.placement
)
@skip_if_lt_x_gpu(4)
def test_st_base_init_from_local_shards_and_global_metadata(self):
world_size = 4
shards_metadata = []
shards = []
for rank in range(world_size):
local_shard_metadata = ShardMetadata(
shard_offsets=[(rank // 2) * 5, (rank % 2) * 5],
shard_sizes=[5, 5],
placement=f"rank:{rank}/cuda:{rank}",
)
shards_metadata.append(local_shard_metadata)
shards.append(
sharded_tensor.Shard(
torch.randn(5, 5, device=f"cuda:{rank}"), local_shard_metadata
)
)
tensor_properties = TensorProperties(
dtype=torch.get_default_dtype(),
layout=torch.strided,
requires_grad=False,
memory_format=torch.contiguous_format,
pin_memory=False,
)
sharded_tensor_metadata = sharded_tensor.ShardedTensorMetadata(
shards_metadata=shards_metadata,
size=torch.Size([10, 10]),
tensor_properties=tensor_properties,
)
st_base = sharded_tensor.ShardedTensorBase._init_from_local_shards_and_global_metadata(
shards, sharded_tensor_metadata=sharded_tensor_metadata
)
self.assertEqual(4, len(st_base.local_shards()))
# Verify local shard of st_base
local_shard = st_base.local_shards()[0]
self.assertEqual(torch.device("cuda:0"), local_shard.tensor.device)
self.assertEqual((5, 5), local_shard.tensor.size())
# Verify local shard metadata.
self.assertEqual(
(0, 0),
local_shard.metadata.shard_offsets,
)
self.assertEqual((5, 5), local_shard.metadata.shard_sizes)
self.assertEqual("rank:0/cuda:0", str(local_shard.metadata.placement))
# Verify global metadata.
shards_metadata = st_base.metadata().shards_metadata
self.assertEqual(4, len(shards_metadata))
for rank, shard_metadata in enumerate(shards_metadata):
self.assertEqual(
(rank // 2 * 5, (rank % 2) * 5), shard_metadata.shard_offsets
)
self.assertEqual((5, 5), shard_metadata.shard_sizes)
self.assertEqual(f"rank:{rank}/cuda:{rank}", str(shard_metadata.placement))
@skipIfRocm
@with_comms(init_rpc=False)
@skip_if_lt_x_gpu(4)
@requires_nccl()
def test_init_from_local_shards_and_global_metadata_with_all_zeros(self):
local_shard_metadata = ShardMetadata(
shard_offsets=[0, 0],
shard_sizes=[0, 0],
placement=f"rank:{self.rank}/cuda:{self.rank}",
)
shards_metadata = []
for r in range(self.world_size):
if r == self.rank:
shards_metadata.append(local_shard_metadata)
else:
shards_metadata.append(
ShardMetadata(
shard_offsets=[0, 0],
shard_sizes=[0, 0],
placement=f"rank:{r}/cuda:{r}",
)
)
local_shards = [
sharded_tensor.Shard(
torch.randn(0, 0, device=f"cuda:{self.rank}"), local_shard_metadata
)
]
tensor_properties = TensorProperties(
dtype=torch.get_default_dtype(),
layout=torch.strided,
requires_grad=False,
memory_format=torch.contiguous_format,
pin_memory=False,
)
sharded_tensor_metadata = sharded_tensor.ShardedTensorMetadata(
shards_metadata=shards_metadata,
size=torch.Size([0, 0]),
tensor_properties=tensor_properties,
)
st = ShardedTensor._init_from_local_shards_and_global_metadata(
local_shards,
sharded_tensor_metadata,
)
self.assertEqual((0, 0), st.size())
self.assertEqual(1, len(st.local_shards()))
# Verify local shard.
local_shard = st.local_shards()[0]
self.assertEqual(torch.device(f"cuda:{self.rank}"), local_shard.tensor.device)
self.assertEqual((0, 0), local_shard.tensor.size())
# Verify local shard metadata.
self.assertEqual(
(0, 0),
local_shard.metadata.shard_offsets,
)
self.assertEqual((0, 0), local_shard.metadata.shard_sizes)
self.assertEqual(
f"rank:{self.rank}/cuda:{self.rank}", str(local_shard.metadata.placement)
)
# Verify global metadata.
shards_metadata = st.metadata().shards_metadata
self.assertEqual(4, len(shards_metadata))
for rank, shard_metadata in enumerate(shards_metadata):
self.assertEqual((0, 0), shard_metadata.shard_offsets)
self.assertEqual((0, 0), shard_metadata.shard_sizes)
self.assertEqual(f"rank:{rank}/cuda:{rank}", str(shard_metadata.placement))
@skipIfRocm
@with_comms(init_rpc=False)
@skip_if_lt_x_gpu(4)
@requires_nccl()
def test_init_from_local_shards_and_global_metadata_with_local_view(self):
# testing cases where we create ST with local view, meaning we initialize other rank's metadata with 0s
shard_offsets = [0, 1] # valid, invalid
for shard_offset in shard_offsets:
local_shard_metadata = ShardMetadata(
shard_offsets=[shard_offset, 0],
shard_sizes=[5, 5],
placement=f"rank:{self.rank}/cuda:{self.rank}",
)
shards_metadata = []
for r in range(self.world_size):
if r == self.rank:
shards_metadata.append(local_shard_metadata)
else:
shards_metadata.append(
ShardMetadata(
shard_offsets=[0 if r < self.rank else 5, 0],
shard_sizes=[0, 0],
placement=f"rank:{r}/cuda:{r}",
)
)
local_shards = [
sharded_tensor.Shard(
torch.randn(5, 5, device=f"cuda:{self.rank}"), local_shard_metadata
)
]
tensor_properties = TensorProperties(
dtype=torch.get_default_dtype(),
layout=torch.strided,
requires_grad=False,
memory_format=torch.contiguous_format,
pin_memory=False,
)
sharded_tensor_metadata = sharded_tensor.ShardedTensorMetadata(
shards_metadata=shards_metadata,
size=torch.Size([5, 5]),
tensor_properties=tensor_properties,
)
if shard_offset == 0:
# valid case
st = ShardedTensor._init_from_local_shards_and_global_metadata(
local_shards,
sharded_tensor_metadata,
)
else:
# invalid case
with self.assertRaises(ValueError):
ShardedTensor._init_from_local_shards_and_global_metadata(
local_shards,
sharded_tensor_metadata,
)
return
self.assertEqual((5, 5), st.size())
self.assertEqual(1, len(st.local_shards()))
# Verify local shard.
local_shard = st.local_shards()[0]
self.assertEqual(
torch.device(f"cuda:{self.rank}"), local_shard.tensor.device
)
self.assertEqual((5, 5), local_shard.tensor.size())
# Verify local shard metadata.
self.assertEqual(
(0, 0),
local_shard.metadata.shard_offsets,
)
self.assertEqual((5, 5), local_shard.metadata.shard_sizes)
self.assertEqual(
f"rank:{self.rank}/cuda:{self.rank}",
str(local_shard.metadata.placement),
)
# Verify global metadata.
shards_metadata = st.metadata().shards_metadata
self.assertEqual(4, len(shards_metadata))
for rank, shard_metadata in enumerate(shards_metadata):
self.assertEqual(
(0 if rank <= self.rank else 5, 0), shard_metadata.shard_offsets
)
if rank == self.rank:
self.assertEqual((5, 5), shard_metadata.shard_sizes)
else:
self.assertEqual((0, 0), shard_metadata.shard_sizes)
self.assertEqual(
f"rank:{rank}/cuda:{rank}", str(shard_metadata.placement)
)
@skipIfRocm
@with_comms
@skip_if_lt_x_gpu(4)
@requires_nccl()
def test_init_from_local_shards_and_global_metadata(self):
local_shard_metadata = ShardMetadata(
shard_offsets=[(self.rank // 2) * 5, (self.rank % 2) * 5],
shard_sizes=[5, 5],
placement=f"rank:{self.rank}/cuda:{self.rank}",
)
shards_metadata = []
for r in range(self.world_size):
if r == self.rank:
shards_metadata.append(local_shard_metadata)
else:
shards_metadata.append(
ShardMetadata(
shard_offsets=[(r // 2) * 5, (r % 2) * 5],
shard_sizes=[5, 5],
placement=f"rank:{r}/cuda:{r}",
)
)
local_shards = [
sharded_tensor.Shard(
torch.randn(5, 5, device=f"cuda:{self.rank}"), local_shard_metadata
)
]
tensor_properties = TensorProperties(
dtype=torch.get_default_dtype(),
layout=torch.strided,
requires_grad=False,
memory_format=torch.contiguous_format,
pin_memory=False,
)
sharded_tensor_metadata = sharded_tensor.ShardedTensorMetadata(
shards_metadata=shards_metadata,
size=torch.Size([10, 10]),
tensor_properties=tensor_properties,
)
st = ShardedTensor._init_from_local_shards_and_global_metadata(
local_shards,
sharded_tensor_metadata,
init_rrefs=True,
)
self.assertEqual((10, 10), st.size())
self.assertEqual(1, len(st.local_shards()))
# Verify local shard.
local_shard = st.local_shards()[0]
self.assertEqual(torch.device(f"cuda:{self.rank}"), local_shard.tensor.device)
self.assertEqual((5, 5), local_shard.tensor.size())
# Verify local shard metadata.
self.assertEqual(
(self.rank // 2 * 5, (self.rank % 2) * 5),
local_shard.metadata.shard_offsets,
)
self.assertEqual((5, 5), local_shard.metadata.shard_sizes)
self.assertEqual(
f"rank:{self.rank}/cuda:{self.rank}", str(local_shard.metadata.placement)
)
# Verify global metadata.
shards_metadata = st.metadata().shards_metadata
self.assertEqual(4, len(shards_metadata))
for rank, shard_metadata in enumerate(shards_metadata):
self.assertEqual(
(rank // 2 * 5, (rank % 2) * 5), shard_metadata.shard_offsets
)
self.assertEqual((5, 5), shard_metadata.shard_sizes)
self.assertEqual(f"rank:{rank}/cuda:{rank}", str(shard_metadata.placement))
# Validate remote shards.
remote_shards = st.remote_shards()
self.assertEqual(3, len(remote_shards))
for rpc_rank, shards in remote_shards.items():
self.assertEqual(1, len(shards))
for remote_shard in shards:
self.assertEqual(rpc_rank, remote_shard.owner().id)
shard = remote_shard.to_here()
self.assertEqual((5, 5), shard.tensor.size())
@with_comms
@skip_if_lt_x_gpu(4)
@requires_nccl()
def test_init_from_local_shards_new_group(self):
new_pg = dist.new_group(ranks=[1, 2, 3])
if self.rank != 0:
local_shard_metadata = ShardMetadata(
shard_offsets=[5 * (self.rank - 1), 0],
shard_sizes=[5, 5],
placement=f"rank:{self.rank}/cuda:{self.rank}",
)
local_shards = [
sharded_tensor.Shard(
torch.randn(5, 5, device=f"cuda:{self.rank}"), local_shard_metadata
)
]
st = sharded_tensor.init_from_local_shards(
local_shards, [15, 5], process_group=new_pg
)
# Verify local shard.
local_shard = st.local_shards()[0]
self.assertEqual(
torch.device(f"cuda:{self.rank}"), local_shard.tensor.device
)
self.assertEqual((5, 5), local_shard.tensor.size())
# Verify local shard metadata.
self.assertEqual(
((self.rank - 1) * 5, 0), local_shard.metadata.shard_offsets
)
self.assertEqual((5, 5), local_shard.metadata.shard_sizes)
self.assertEqual(
f"rank:{self.rank}/cuda:{self.rank}",
str(local_shard.metadata.placement),
)
# Verify global metadata.
st_metadata = st.metadata()
shards_metadata = st_metadata.shards_metadata
self.assertEqual(3, len(shards_metadata))
for rank, shard_metadata in enumerate(shards_metadata):
self.assertEqual((rank * 5, 0), shard_metadata.shard_offsets)
self.assertEqual((5, 5), shard_metadata.shard_sizes)
self.assertEqual(
f"rank:{rank + 1}/cuda:{rank + 1}", str(shard_metadata.placement)
)
@with_comms
@skip_if_lt_x_gpu(4)
@requires_nccl()
def test_init_from_local_shards_invalid_local_shards(self):
local_shard_metadata = ShardMetadata(
shard_offsets=[(self.rank // 2) * 5, (self.rank % 2) * 5],
shard_sizes=[5, 5],
placement=f"rank:{self.rank}/cuda:{self.rank}",
)
indices = [[0, 1, 1], [2, 0, 2]]
values = [3.2, 4.5, 5.8]
sparse_tensor = torch.sparse_coo_tensor(
indices, values, (5, 5), device=f"cuda:{self.rank}"
)
empty_local_shards = []
with self.assertRaisesRegex(ValueError, "have no local shards on all ranks"):
sharded_tensor.init_from_local_shards(
empty_local_shards, [10, 10], init_rrefs=True
)
wrong_layout_shards = [
sharded_tensor.Shard(sparse_tensor, local_shard_metadata)
]
with self.assertRaisesRegex(
ValueError, "Only torch.strided layout is currently supported"
):
sharded_tensor.init_from_local_shards(
wrong_layout_shards, [10, 10], init_rrefs=True
)
wrong_memory_format_shards = [
sharded_tensor.Shard(
torch.randn(5, 5, device=f"cuda:{self.rank}").t(), local_shard_metadata
)
]
with self.assertRaisesRegex(
ValueError,
"Only torch.contiguous_format memory_format is currently supported",
):
sharded_tensor.init_from_local_shards(
wrong_memory_format_shards, [10, 10], init_rrefs=True
)
with self.assertRaisesRegex(ValueError, "Shard tensor size does not match"):
sharded_tensor.Shard(
torch.randn(2, 3, device=f"cuda:{self.rank}"), local_shard_metadata
)
with self.assertRaisesRegex(
ValueError, "Local shard tensor device does not match"
):
sharded_tensor.Shard(torch.randn(5, 5), local_shard_metadata)
@with_comms
@skip_if_lt_x_gpu(4)
@requires_nccl()
def test_init_from_local_shards_invalid_property_cross_ranks(self):
local_shard_metadata = ShardMetadata(
shard_offsets=[(self.rank // 2) * 5, (self.rank % 2) * 5],
shard_sizes=[5, 5],
placement=f"rank:{self.rank}/cuda:{self.rank}",
)
tensor_overall_size = [10, 10] if self.rank == 0 else [10, 5]
wrong_dtype_shards = [
sharded_tensor.Shard(
torch.ones(5, 5, device=f"cuda:{self.rank}"), local_shard_metadata
)
]
with self.assertRaisesRegex(
ValueError,
"ShardedTensor global_size property does not match from different ranks!",
):
sharded_tensor.init_from_local_shards(
wrong_dtype_shards, tensor_overall_size, init_rrefs=True
)
tensor_dtype = torch.int if self.rank == 0 else torch.float32
wrong_dtype_shards = [
sharded_tensor.Shard(
torch.ones(5, 5, device=f"cuda:{self.rank}", dtype=tensor_dtype),
local_shard_metadata,
)
]
with self.assertRaisesRegex(
ValueError,
"ShardedTensor dtype property does not match from different ranks!",
):
sharded_tensor.init_from_local_shards(
wrong_dtype_shards, [10, 10], init_rrefs=True
)
tensor_requires_grad = self.rank == 0
wrong_requires_grad_shards = [
sharded_tensor.Shard(
torch.randn(
5, 5, device=f"cuda:{self.rank}", requires_grad=tensor_requires_grad
),
local_shard_metadata,
)
]
with self.assertRaisesRegex(
ValueError,
"ShardedTensor requires_grad property does not match from different ranks!",
):
sharded_tensor.init_from_local_shards(
wrong_requires_grad_shards, [10, 10], init_rrefs=True
)
local_shard_metadata = ShardMetadata(
shard_offsets=[(self.rank // 2) * 5, (self.rank % 2) * 5],
shard_sizes=[5, 5],
placement=f"rank:{self.rank}/cpu",
)
@with_comms(init_rpc=False, backend="gloo")
@skip_if_lt_x_gpu(4)
def test_init_from_local_shards_invalid_pin_memory(self):
# pin memory can only be on dense cpu
local_shard_metadata = ShardMetadata(
shard_offsets=[(self.rank // 2) * 5, (self.rank % 2) * 5],
shard_sizes=[5, 5],
placement=f"rank:{self.rank}/cpu",
)
wrong_pin_memory_local_shards = [
sharded_tensor.Shard(
torch.randn(5, 5, pin_memory=True), local_shard_metadata
),
sharded_tensor.Shard(
torch.randn(5, 5, pin_memory=False), local_shard_metadata
),
]
with self.assertRaisesRegex(
ValueError, "Local shards' tensor pin_memory property need to be the same"
):
sharded_tensor.init_from_local_shards(
wrong_pin_memory_local_shards, [10, 10], init_rrefs=True
)
tensor_pin_memory = self.rank == 0
wrong_pin_memory_shards_cross_ranks = [
sharded_tensor.Shard(
torch.randn(5, 5, pin_memory=tensor_pin_memory), local_shard_metadata
)
]
with self.assertRaisesRegex(
ValueError,
"ShardedTensor pin_memory property does not match from different ranks!",
):
sharded_tensor.init_from_local_shards(
wrong_pin_memory_shards_cross_ranks, [10, 10], init_rrefs=True
)
@with_comms
@skip_if_lt_x_gpu(4)
@requires_nccl()
def test_init_from_local_shards_invalid_shards_overlap(self):
local_shard_size = [5, 5] if self.rank != 0 else [6, 6]
local_shard_metadata = ShardMetadata(
shard_offsets=[(self.rank // 2) * 5, (self.rank % 2) * 5],
shard_sizes=local_shard_size,
placement=f"rank:{self.rank}/cuda:{self.rank}",
)
local_shards = [
sharded_tensor.Shard(
torch.randn(local_shard_size, device=f"cuda:{self.rank}"),
local_shard_metadata,
)
]
with self.assertRaisesRegex(ValueError, "overlap"):
sharded_tensor.init_from_local_shards(
local_shards, [10, 10], init_rrefs=True
)
@with_comms
@skip_if_lt_x_gpu(4)
@requires_nccl()
def test_init_from_local_shards_invalid_shards_gaps(self):
local_shard_size = [5, 5] if self.rank != 0 else [4, 4]
local_shard_metadata = ShardMetadata(
shard_offsets=[(self.rank // 2) * 5, (self.rank % 2) * 5],
shard_sizes=local_shard_size,
placement=f"rank:{self.rank}/cuda:{self.rank}",
)
local_shards = [
sharded_tensor.Shard(
torch.randn(local_shard_size, device=f"cuda:{self.rank}"),
local_shard_metadata,
)
]
with self.assertRaisesRegex(ValueError, "does not match tensor volume"):
sharded_tensor.init_from_local_shards(
local_shards, [10, 10], init_rrefs=True
)
@with_comms
@skip_if_lt_x_gpu(4)
@requires_nccl()
def test_init_from_local_shards_and_global_metadata_invalid_shards(self):
local_shard_metadata = ShardMetadata(
shard_offsets=[(self.rank // 2) * 5, (self.rank % 2) * 5],
shard_sizes=[5, 5],
placement=f"rank:{self.rank}/cuda:{self.rank}",
)
shards_metadata = []
for r in range(self.world_size):
if r == self.rank:
shards_metadata.append(local_shard_metadata)
else:
shards_metadata.append(
ShardMetadata(
shard_offsets=[(r // 2) * 5, (r % 2) * 5],
shard_sizes=[5, 5],
placement=f"rank:{r}/cuda:{r}",
)
)
tensor_properties = TensorProperties(
dtype=torch.get_default_dtype(),
layout=torch.strided,
requires_grad=False,
memory_format=torch.contiguous_format,
pin_memory=False,
)
sharded_tensor_metadata = sharded_tensor.ShardedTensorMetadata(
shards_metadata=shards_metadata,
size=torch.Size([10, 10]),
tensor_properties=tensor_properties,
)
empty_local_shards = []
with self.assertRaisesRegex(
RuntimeError, "does not match number of local shards metadata"
):
ShardedTensor._init_from_local_shards_and_global_metadata(
empty_local_shards, sharded_tensor_metadata
)
wrong_num_shards = [
sharded_tensor.Shard(
torch.randn(5, 5, device=f"cuda:{self.rank}"), local_shard_metadata
),
sharded_tensor.Shard(
torch.randn(5, 5, device=f"cuda:{self.rank}"), local_shard_metadata
),
]
with self.assertRaisesRegex(
RuntimeError, "does not match number of local shards metadata"
):
ShardedTensor._init_from_local_shards_and_global_metadata(
wrong_num_shards, sharded_tensor_metadata
)
with self.assertRaisesRegex(
ValueError, "Shard tensor size does not match with metadata.shard_lengths"
):
sharded_tensor.Shard(
torch.randn(2, 3, device=f"cuda:{self.rank}"), local_shard_metadata
)
with self.assertRaisesRegex(
ValueError,
"Local shard tensor device does not match with local Shard's placement",
):
sharded_tensor.Shard(torch.randn(5, 5), local_shard_metadata)
wrong_dtype_shards = [
sharded_tensor.Shard(
torch.ones(5, 5, device=f"cuda:{self.rank}", dtype=torch.int),
local_shard_metadata,
)
]
with self.assertRaisesRegex(
ValueError, "Local shards' tensor dtype property is incompatible with"
):
ShardedTensor._init_from_local_shards_and_global_metadata(
wrong_dtype_shards, sharded_tensor_metadata
)
indices = [[0, 1, 1], [2, 0, 2]]
values = [3.2, 4.5, 5.8]
sparse_tensor = torch.sparse_coo_tensor(
indices, values, (5, 5), device=f"cuda:{self.rank}"
)
wrong_layout_shards = [
sharded_tensor.Shard(sparse_tensor, local_shard_metadata)
]
with self.assertRaisesRegex(
ValueError, "Local shards' tensor layout property is incompatible with"
):
ShardedTensor._init_from_local_shards_and_global_metadata(
wrong_layout_shards, sharded_tensor_metadata
)
wrong_requires_grad_shards = [
sharded_tensor.Shard(
torch.randn(5, 5, device=f"cuda:{self.rank}", requires_grad=True),
local_shard_metadata,
)
]
with self.assertRaisesRegex(
ValueError,
"Local shards' tensor requires_grad property is incompatible with",
):
ShardedTensor._init_from_local_shards_and_global_metadata(
wrong_requires_grad_shards, sharded_tensor_metadata
)
wrong_memory_format_shards = [
sharded_tensor.Shard(
torch.randn(5, 5, device=f"cuda:{self.rank}").t(), local_shard_metadata
)
]
with self.assertRaisesRegex(
ValueError,
"Only torch.contiguous_format memory_format is currently supported",
):
ShardedTensor._init_from_local_shards_and_global_metadata(
wrong_memory_format_shards, sharded_tensor_metadata
)
# pin_memory can only be on CPU
local_shard_metadata.placement = _remote_device(f"rank:{self.rank}/cpu")
wrong_pin_memory_shards = [
sharded_tensor.Shard(
torch.randn(5, 5, pin_memory=True), local_shard_metadata
)
]
with self.assertRaisesRegex(
ValueError, "Local shards' tensor pin_memory property is incompatible with"
):
ShardedTensor._init_from_local_shards_and_global_metadata(
wrong_pin_memory_shards, sharded_tensor_metadata
)
| TestShardedTensorFromLocalShards |
python | pytorch__pytorch | test/test_nestedtensor.py | {
"start": 154252,
"end": 345832
} | class ____(NestedTensorTestCase):
# TODO: consolidate with the below
def _get_list_for_jagged_tensor(self, nested_size, device, requires_grad=True):
Ds = nested_size[1:]
out = []
for s in nested_size[0]:
out.append(
torch.randn(
s,
*Ds,
requires_grad=requires_grad,
device=device,
dtype=torch.float64,
)
)
return out
def _get_example_tensor_lists(
self,
include_list_of_lists=True,
include_requires_grad=True,
include_inner_dim_size_1=False,
include_2d_tensor=False,
):
def _make_tensor(
*shape, include_requires_grad=include_requires_grad, requires_grad=True
):
return torch.randn(
*shape,
requires_grad=(requires_grad if include_requires_grad else False),
)
# Purposefully introduce mixed requires_grad settings for the components
# when include_requires_grad=True.
example_lists = [
# (B, *, D) with B=4
[
_make_tensor(2, 5),
_make_tensor(3, 5, requires_grad=False),
_make_tensor(4, 5, requires_grad=False),
_make_tensor(6, 5),
],
# (B, *, D_0, D_1) with B=5
[
_make_tensor(2, 5, 6),
_make_tensor(3, 5, 6),
_make_tensor(4, 5, 6, requires_grad=False),
_make_tensor(5, 5, 6),
_make_tensor(6, 5, 6),
],
# (B, *, D_0, D_1, D_2) with B=6
[
_make_tensor(2, 5, 6, 7),
_make_tensor(3, 5, 6, 7),
_make_tensor(4, 5, 6, 7, requires_grad=False),
_make_tensor(5, 5, 6, 7),
_make_tensor(6, 5, 6, 7),
_make_tensor(7, 5, 6, 7),
],
]
if include_list_of_lists:
example_lists.append(
# (B, *, D) with B=3 in list form
[
_make_tensor(2, 5, requires_grad=False).tolist(),
_make_tensor(3, 5).tolist(),
_make_tensor(4, 5).tolist(),
]
)
if include_inner_dim_size_1:
example_lists.append(
[
_make_tensor(2, 1),
_make_tensor(3, 1, requires_grad=False),
_make_tensor(4, 1, requires_grad=False),
_make_tensor(6, 1),
] # (B, *, 1)
)
example_lists.append(
[
_make_tensor(2, 5, 1),
_make_tensor(3, 5, 1, requires_grad=False),
_make_tensor(4, 5, 1, requires_grad=False),
_make_tensor(6, 5, 1),
] # (B, *, 5, 1)
)
if include_2d_tensor:
example_lists.append(
[
_make_tensor(2),
_make_tensor(3, requires_grad=False),
_make_tensor(4, requires_grad=False),
_make_tensor(6),
] # (B, *)
)
return example_lists
@dtypes(torch.float32)
@parametrize(
"contiguity",
["contig", "noncontig_transposed", "noncontig_with_holes"],
name_fn=lambda c: c,
)
@parametrize("weights_only", [True, False])
def test_serialization(self, device, dtype, contiguity, weights_only):
# Test with 3 cases:
# 1. contiguous
# 2. non-contiguous transposed
# 3. non-contiguous with holes
if contiguity == "contig":
nt = random_nt_from_dims(
[4, None, 10],
device=device,
dtype=dtype,
layout=torch.jagged,
)
elif contiguity == "noncontig_transposed":
nt = random_nt_from_dims(
[3, None, 5, 2],
device=device,
dtype=dtype,
layout=torch.jagged,
).transpose(-3, -2)
elif contiguity == "noncontig_with_holes":
nt = torch.nested.nested_tensor_from_jagged(
values=torch.randn(10, 3, device=device, dtype=dtype),
offsets=torch.tensor([0, 3, 7, 10], device=device, dtype=torch.int64),
# these lengths specify holes
lengths=torch.tensor([1, 2, 3], device=device, dtype=torch.int64),
)
else:
raise ValueError("invalid contiguity specified for test_serialization()")
# Access sizes / strides to ensure cache doesn't break serialization.
# See https://github.com/pytorch/pytorch/issues/129366
nt.size()
nt.stride()
with tempfile.TemporaryFile() as f:
torch.save(nt, f)
f.seek(0)
nt_loaded = torch.load(f, weights_only=weights_only)
self.assertIsNot(nt, nt_loaded)
# we expect a new offsets tensor -> different nested int upon load
self.assertEqualIgnoringNestedInts(nt, nt_loaded)
self.assertEqual(nt._ragged_idx, nt_loaded._ragged_idx)
# ensure shapes are equal except nested int
nt_rest_of_shape = (
*nt.shape[: nt._ragged_idx],
*nt.shape[nt._ragged_idx + 1 :],
)
nt_loaded_rest_of_shape = (
*nt_loaded.shape[: nt_loaded._ragged_idx],
*nt_loaded.shape[nt_loaded._ragged_idx + 1 :],
)
self.assertEqual(nt_rest_of_shape, nt_loaded_rest_of_shape)
# ensure metadata cache is carried through serialization
self.assertEqual(nt._metadata_cache, nt_loaded._metadata_cache)
# ensure lengths are carried through if present
self.assertEqual(nt._lengths, nt_loaded._lengths)
def test_tensor_attributes(self, device):
a = torch.randn(2, 3, requires_grad=True, dtype=torch.float64, device=device)
b = torch.randn(3, 3, requires_grad=True, dtype=torch.float64, device=device)
c = torch.randn(4, 3, requires_grad=True, dtype=torch.float64, device=device)
nt = torch.nested.as_nested_tensor([a, b, c], layout=torch.jagged)
_offsets = nt.offsets()
for op in (
torch.ops.aten.is_non_overlapping_and_dense.default,
torch.ops.aten.sym_size.default,
torch.ops.aten.dim.default,
torch.ops.aten.numel.default,
torch.ops.aten.sym_numel.default,
torch.ops.aten.sym_stride.default,
torch.ops.aten.sym_storage_offset.default,
):
op(nt)
with self.assertRaisesRegex(
RuntimeError, "directly calling torch.ops.aten.size"
):
torch.ops.aten.size.default(nt)
nested_int = torch.nested._internal.nested_tensor.get_tensor_symint(
_offsets, coeff=1
)
self.assertEqual(nt.size(), (3, nested_int, 3))
self.assertEqual(nt.shape, (3, nested_int, 3))
self.assertEqual(nt.dim(), 3)
self.assertEqual(nt.numel(), 27)
@parametrize("nt_dim", [3, 4, 5])
def test_linear(self, device, nt_dim):
if nt_dim == 3:
fixed_shape = (3,)
elif nt_dim == 4:
fixed_shape = (4, 3)
elif nt_dim == 5:
fixed_shape = (5, 4, 3)
a = torch.randn(
2, *fixed_shape, requires_grad=True, dtype=torch.float64, device=device
)
b = torch.randn(
3, *fixed_shape, requires_grad=True, dtype=torch.float64, device=device
)
c = torch.randn(
4, *fixed_shape, requires_grad=True, dtype=torch.float64, device=device
)
weight = torch.randn(
4, 3, requires_grad=True, dtype=torch.float64, device=device
)
bias = torch.randn(4, requires_grad=True, dtype=torch.float64, device=device)
def grad_test_func(a, b, c, weight, bias):
nt = torch.nested.as_nested_tensor([a, b, c], layout=torch.jagged)
out = torch.nn.functional.linear(nt, weight, bias)
return out.values()
gradcheck(
grad_test_func, inputs=(a, b, c, weight, bias), check_batched_grad=False
)
@onlyCUDA
@dtypes(torch.float32)
@serialTest()
def test_linear_backward_memory_usage(self, device, dtype):
# Verify that linear_backward() doesn't use more memory than it should
# for higher dim input sizes.
# See https://github.com/pytorch/pytorch/issues/141112
B, D, max_seq_len = 64, 512, 100
torch._C._cuda_clearCublasWorkspaces()
m = torch.nn.Linear(D, D, device=device)
nt = torch.nested.as_nested_tensor(
[
torch.rand(size=[seq_len, D])
for seq_len in torch.randint(max_seq_len, size=(B,))
],
layout=torch.jagged,
device=device,
)
# (B, j1, D) -> (B, j1, 1, D) for a higher dim input size
nt = nt.unsqueeze(-2)
# linear_backward() should not explode the max memory usage
torch.cuda.reset_max_memory_allocated()
m(nt).sum().backward()
# expect under a GB for max memory allocated
max_after_gb = torch.cuda.max_memory_allocated(0) // (1024**3)
self.assertEqual(max_after_gb, 0)
def test_unary_pointwise(self, device):
a = torch.randn(2, 3, requires_grad=True, dtype=torch.float64, device=device)
b = torch.randn(3, 3, requires_grad=True, dtype=torch.float64, device=device)
c = torch.randn(4, 3, requires_grad=True, dtype=torch.float64, device=device)
def grad_test_func(a, b, c):
nt = torch.nested.as_nested_tensor([a, b, c], layout=torch.jagged)
out = torch.nn.functional.silu(nt.sin().cos())
return out.values()
gradcheck(grad_test_func, inputs=(a, b, c), check_batched_grad=False)
def test_unary_pointwise_transposed_inputs(self, device):
a, b, c = (
torch.randn(
i + 2, 5, requires_grad=True, dtype=torch.float64, device=device
)
for i in range(3)
)
nt = torch.nested.nested_tensor(
[a.detach(), b.detach(), c.detach()], layout=torch.jagged
)
nt_t = nt.transpose(1, 2)
self.assertFalse(nt_t.is_contiguous())
out = torch.nn.functional.silu(nt_t.sin().cos())
self.assertEqual(
out.is_contiguous(),
torch.nn.functional.silu(b.transpose(-1, -2).sin().cos()).is_contiguous(),
)
self.assertEqual(nt_t.shape, out.shape)
a, b, c = (
torch.randn(
i + 2, 5, requires_grad=True, dtype=torch.float64, device=device
)
for i in range(3)
)
def grad_test_func(a, b, c):
nt = torch.nested.as_nested_tensor([a, b, c], layout=torch.jagged)
nt_t = nt.transpose(1, 2)
out = torch.nn.functional.silu(nt_t.sin().cos())
return out.values()
gradcheck(grad_test_func, inputs=(a, b, c), check_batched_grad=False)
def test_binary_pointwise(self, device):
a = torch.randn(2, 3, requires_grad=True, dtype=torch.float64, device=device)
b = torch.randn(3, 3, requires_grad=True, dtype=torch.float64, device=device)
c = torch.randn(4, 3, requires_grad=True, dtype=torch.float64, device=device)
# Incorrect usage: shape check will fail if the offsets tensor are not
# the same exact tensor object
nt1 = torch.nested.as_nested_tensor([a, b, c], layout=torch.jagged)
nt2 = torch.nested.as_nested_tensor([a, b, c], layout=torch.jagged)
self.assertRaisesRegex(
RuntimeError,
"cannot call binary pointwise function .* with inputs of shapes",
lambda: nt1 * nt2,
)
# Correct usage: chain the calls using the same offsets tensor object
def grad_test_func(a, b, c):
nt1 = torch.nested.as_nested_tensor([a, b, c], layout=torch.jagged)
# TODO: Switch to public API that takes in (values, offsets) once it exists
nt2, offsets = jagged_from_list([a, b, c], nt1.offsets())
out = nt1 * nt2
return out.values()
gradcheck(grad_test_func, inputs=(a, b, c), check_batched_grad=False)
def test_binary_pointwise_transposed(self, device):
a, b, c = (
torch.randn(i + 2, 5, dtype=torch.float64, device=device) for i in range(3)
)
nt1, offsets = jagged_from_list([a, b, c], None)
nt2, offsets = jagged_from_list([a, b, c], offsets)
nt1_t = nt1.transpose(1, 2)
nt2_t = nt2.transpose(1, 2)
# out = nt1_t * nt2_t
# self.assertFalse(nt1_t.is_contiguous())
# self.assertEqual(out.is_contiguous(), (b.transpose(-1, -2) * b.transpose(-1, -2)).is_contiguous())
# self.assertEqual(out.shape, nt1_t.shape)
self.assertRaisesRegex(
RuntimeError,
"cannot call binary pointwise function mul.Tensor with inputs of shapes",
lambda: nt1 * nt2_t,
)
a, b, c = (
torch.randn(
i + 2, 5, requires_grad=True, dtype=torch.float64, device=device
)
for i in range(3)
)
# Correct usage: chain the calls using the same offsets tensor object
def grad_test_func(a, b, c):
nt1, offsets = jagged_from_list([a, b, c], None)
nt2, offsets = jagged_from_list([a, b, c], offsets)
nt1_t = nt1.transpose(1, 2)
nt2_t = nt2.transpose(1, 2)
out = nt1_t * nt2_t
return out.values()
gradcheck(grad_test_func, inputs=(a, b, c), check_batched_grad=False)
def test_binary_pointwise_with_nested_int_second_arg(self, device):
# See https://github.com/pytorch/pytorch/issues/138496
nt = random_nt_from_dims(
[3, None, 5],
device=device,
dtype=torch.float32,
layout=torch.jagged,
)
with self.assertRaisesRegex(RuntimeError, "invalid argument"):
nt * nt.size(1)
with self.assertRaisesRegex(RuntimeError, "invalid argument"):
nt + nt.size(1)
def test_split(self, device):
a = torch.randn(2, 3, requires_grad=True, dtype=torch.float64, device=device)
b = torch.randn(3, 3, requires_grad=True, dtype=torch.float64, device=device)
c = torch.randn(4, 3, requires_grad=True, dtype=torch.float64, device=device)
nt = torch.nested.as_nested_tensor([a, b, c], layout=torch.jagged)
out = torch.split(nt, 2, -1)
self.assertEqual(len(out), 2)
self.assertEqualIgnoringNestedInts(
out[0],
torch.nested.as_nested_tensor(
[a[:, 0:2], b[:, 0:2], c[:, 0:2]], layout=torch.jagged
),
)
self.assertEqualIgnoringNestedInts(
out[1],
torch.nested.as_nested_tensor(
[a[:, 2:], b[:, 2:], c[:, 2:]], layout=torch.jagged
),
)
with self.assertRaisesRegex(
RuntimeError,
r"split\(\): not supported for NestedTensor on ragged dim",
):
torch.split(nt, 2, 1)
def test_split_with_sizes(self, device):
a = torch.randn(2, 3, requires_grad=True, dtype=torch.float64, device=device)
b = torch.randn(3, 3, requires_grad=True, dtype=torch.float64, device=device)
c = torch.randn(4, 3, requires_grad=True, dtype=torch.float64, device=device)
nt = torch.nested.as_nested_tensor([a, b, c], layout=torch.jagged)
out = torch.split(nt, [1, 2], -1)
self.assertEqual(len(out), 2)
self.assertEqualIgnoringNestedInts(
out[0],
torch.nested.as_nested_tensor(
[a[:, 0:1], b[:, 0:1], c[:, 0:1]], layout=torch.jagged
),
)
self.assertEqualIgnoringNestedInts(
out[1],
torch.nested.as_nested_tensor(
[a[:, 1:], b[:, 1:], c[:, 1:]], layout=torch.jagged
),
)
with self.assertRaisesRegex(
RuntimeError,
r"split_with_sizes\(\): not supported for NestedTensor on ragged dim",
):
torch.split(nt, [1, 2], 1)
def test_softmax(self, device):
nt = random_nt_from_dims(
[3, None, 5],
device=device,
dtype=torch.float32,
layout=torch.jagged,
requires_grad=True,
)
# operate on dim=2
output = nt.softmax(dim=2)
@torch._dynamo.disable
def _compare_to_ref(nt, output, dim):
for in_component, out_component in zip(nt.unbind(), output.unbind()):
self.assertEqual(in_component.softmax(dim=dim), out_component)
# dim=2 -> dim=1 after unbind
_compare_to_ref(nt, output, dim=1)
# operate on dim=-1
output2 = nt.softmax(dim=-1)
torch._dynamo.disable(self.assertEqual)(output, output2)
_compare_to_ref(nt, output2, dim=-1)
def grad_test_func(a, b):
nt = torch.nested.as_nested_tensor([a, b], layout=torch.jagged)
out = nt.softmax(dim=-1)
return out.values()
a = torch.rand(4, 5, requires_grad=True, dtype=torch.float64, device=device)
b = torch.rand(8, 5, requires_grad=True, dtype=torch.float64, device=device)
gradcheck(grad_test_func, inputs=(a, b), check_batched_grad=False)
def test_views_inherit_ragged_dim(self, device):
# view
nt = random_nt_from_dims(
[4, None, 8, 10], device=device, dtype=torch.float32, layout=torch.jagged
)
# inherit ragged dim via -1
view = nt.view(4, -1, 80)
self.assertEqual(nt.shape[1], view.shape[1])
# inherit batch and ragged dims via -1
view2 = nt.view(-1, -1, 80)
self.assertEqual(nt.shape[:2], view2.shape[:2])
# expand
nt = random_nt_from_dims(
[3, None, 1], device=device, dtype=torch.float32, layout=torch.jagged
)
# inherit batch and ragged dims via -1
view = nt.expand(-1, -1, 5)
self.assertEqual(nt.shape[:2], view.shape[:2])
def test_view_ragged_idx_not_one(self, device):
nt = random_nt_from_dims(
[2, None, 20], device=device, dtype=torch.float32, layout=torch.jagged
)
view_transposed = nt.transpose(1, 2).view(2, 20, nt.size(1))
self.assertEqual((2, 20, nt.size(1)), (view_transposed.size()))
self.assertEqual(view_transposed._base, nt._base)
def test_unsafe_view(self, device):
nt = random_nt_from_dims(
[4, None, 8, 10], device=device, dtype=torch.float32, layout=torch.jagged
)
# basic view
view1 = torch.ops.aten._unsafe_view(nt, (4, -1, 80))
self.assertEqual((4, nt.size(1), 80), tuple(view1.size()))
# _unsafe_view differs from view in that the view information is not tracked
self.assertTrue(view1._base is None)
# test an unsafe_view when ragged_idx != 1, currently only supports identity view
nt_t = nt.transpose(1, 2)
view2 = torch.ops.aten._unsafe_view(nt_t, (4, 8, nt.size(1), 10))
self.assertEqual((4, 8, nt.size(1), 10), tuple(view2.size()))
self.assertTrue(view2._base is None)
@xfailIfTorchDynamo
@parametrize("requires_grad", [False, True])
def test_reshape_decomp(self, device, requires_grad):
# contiguous NT should result in view.
nt = (
random_nt_from_dims(
[3, None, 10],
device=device,
dtype=torch.float32,
layout=torch.jagged,
)
.detach()
.requires_grad_(requires_grad)
)
view = nt.reshape(-1, -1, 5, 2)
self.assertEqual(view.shape[:2], nt.shape[:2])
self.assertTrue(view._is_view() and view._base is nt)
# make sure gradients flow back
if requires_grad:
view.backward(torch.ones_like(view))
self.assertEqual(nt.grad, torch.ones_like(nt))
# non-contiguous NT should result in contiguous copy
nt = random_nt_from_dims(
[3, None, 5, 2],
device=device,
dtype=torch.float32,
layout=torch.jagged,
requires_grad=requires_grad,
)
nt_noncontig = nt.transpose(-1, -2)
self.assertFalse(nt_noncontig.is_contiguous())
copy = nt_noncontig.reshape(-1, -1, 10)
self.assertTrue(copy.is_contiguous())
self.assertEqual(copy.shape[:2], nt.shape[:2])
# make sure gradients flow back
if requires_grad:
copy.backward(torch.ones_like(copy))
self.assertEqual(nt.grad, torch.ones_like(nt))
def test_flatten_decomp(self, device):
nt = random_nt_from_dims(
[3, None, 5, 2], device=device, dtype=torch.float32, layout=torch.jagged
)
flattened = nt.flatten(-2, -1)
self.assertEqual(flattened.shape, nt.view(3, -1, 10).shape)
nt = random_nt_from_dims(
[3, None, 5, 2, 6], device=device, dtype=torch.float32, layout=torch.jagged
)
flattened = nt.flatten(-3, -2)
self.assertEqual(flattened.shape, nt.view(3, -1, 10, 6).shape)
def test_chunk(self, device):
# none NJT case
t = torch.randn(10, 4, 5, requires_grad=True)
t_list = t.chunk(3, dim=0)
loss = t_list[0].sum() + t_list[2].sum()
loss.backward()
# normal case
D = 30
B = 8
nt = random_nt_from_dims(
[B, None, D],
device=device,
dtype=torch.float32,
layout=torch.jagged,
requires_grad=True,
)
NUM_CHUNKS = 3
chunks = nt.chunk(NUM_CHUNKS, dim=-1)
self.assertEqual(len(chunks), NUM_CHUNKS)
for i in range(NUM_CHUNKS):
self.assertEqual(chunks[i].shape[-1], D // NUM_CHUNKS)
# test chunk_backward
values = torch.randn(
5, 11, dtype=torch.float64, device=device, requires_grad=True
)
offsets = torch.tensor([0, 2, 3, 5], device=device)
def grad_test_func(values, offsets):
nt = torch.nested.nested_tensor_from_jagged(values, offsets)
chunks = nt.chunk(3, dim=-1)
return chunks[0].values().sum()
assert gradcheck(
grad_test_func,
inputs=(values, offsets),
check_batched_grad=False,
)
# chunk on batch dim
chunks = nt.chunk(NUM_CHUNKS, dim=0)
self.assertEqual(len(chunks), NUM_CHUNKS)
chunk_size = math.ceil(B / NUM_CHUNKS)
for i in range(NUM_CHUNKS):
if i < NUM_CHUNKS - 1:
self.assertEqual(chunks[i].shape[0], chunk_size)
else:
self.assertEqual(chunks[i].shape[0], B - chunk_size * (NUM_CHUNKS - 1))
offsets_expected = (
nt._offsets[i * chunk_size + 1 : (i + 1) * chunk_size + 1]
- nt._offsets[i * chunk_size]
)
self.assertEqual(chunks[i]._offsets[1:], offsets_expected)
self.assertEqual(nt._values, torch.cat([x._values for x in chunks], dim=0))
# doesn't support backward for chunk (dim=0) yet
loss = (
chunks[0].values().sum()
+ chunks[1].values().sum()
+ chunks[2].values().sum()
)
loss.backward()
# chunk on ragged dim not supported
with self.assertRaisesRegex(
RuntimeError, "chunk.* not supported for NestedTensor on ragged dim"
):
nt.chunk(2, dim=1)
def test_squeeze(self, device):
B = 4
D = 6
# squeeze middle dim
nt = random_nt_from_dims(
[B, None, 1, D], device=device, dtype=torch.float32, layout=torch.jagged
)
j0 = nt.shape[1]
for dim_arg in [-2, 2]:
out = nt.squeeze(dim_arg)
self.assertEqual(out.shape, (B, j0, D))
self.assertEqual(out.unsqueeze(-2), nt)
# squeeze last dim
nt = random_nt_from_dims(
[B, None, 1], device=device, dtype=torch.float32, layout=torch.jagged
)
j1 = nt.shape[1]
for dim_arg in [-1, 2]:
out = nt.squeeze(dim_arg)
self.assertEqual(out.shape, (B, j1))
self.assertEqual(out.unsqueeze(-1), nt)
# squeeze on batch dim not supported
with self.assertRaisesRegex(
RuntimeError, "squeeze.* not supported for NestedTensor on dim=0"
):
nt.squeeze(0)
# squeeze on ragged dim not supported
with self.assertRaisesRegex(
RuntimeError, "squeeze.* not supported for NestedTensor on ragged dim"
):
nt.squeeze(1)
def test_binary_pointwise_broadcasting(self, device):
# (B, j0, 3, 4)
ts = self._get_list_for_jagged_tensor(
((2, 3, 4), 3, 4), device, requires_grad=True
)
# (B, j0, ?, ?) + (?) -> (B, j0, ?, ?)
# (B, j0, ?, ?) + (?, ?) -> (B, j0, ?, ?)
# (B, j0, ?, ?) + (1, ?, ?) -> (B, j0, ?, ?)
# Unsupported: (B, j0, ?, ?) + (1, 1, 1, ?, ?) -> (1, B, j0, ?, ?)
t_sizes = (
(4,),
(1, 4),
(3, 1),
(1, 3, 1),
(1, 1, 1, 4),
# (1, 1, 1, 1, 4), (unsupported today)
)
def grad_test_func(t, *ts):
nt = torch.nested.as_nested_tensor(list(ts), layout=torch.jagged)
out = nt + t
return out.values()
for t_size in t_sizes:
t = torch.rand(
t_size, requires_grad=True, device=device, dtype=torch.float64
)
gradcheck(grad_test_func, inputs=(t, *ts), check_batched_grad=False)
def test_threshold_backward(self, device):
ts1 = self._get_list_for_jagged_tensor(
((2, 3, 4), 16), device=device, requires_grad=False
)
ts2 = self._get_list_for_jagged_tensor(
((2, 3, 4), 16), device=device, requires_grad=False
)
nt1, offsets = jagged_from_list(ts1, None)
nt2, offsets = jagged_from_list(ts2, offsets)
buf1 = nt1.values().detach().clone()
buf2 = nt2.values().detach().clone()
res_nt = torch.ops.aten.threshold_backward(nt1, nt2, 0.0)
res_dense = torch.ops.aten.threshold_backward(buf1, buf2, 0.0)
self.assertEqual(res_dense, res_nt.values())
@onlyCUDA
@dtypes(torch.float32)
def test_record_stream(self, device, dtype):
def _create_nt():
values = torch.ones(1024, 4 * 1024, device="cuda")
offsets = torch.tensor([0, 500, 1024], device="cuda", dtype=torch.int64)
lengths = offsets.diff()
nt = torch.nested.nested_tensor_from_jagged(values, offsets, lengths)
data_ptrs = {
nt._values.data_ptr(),
nt._offsets.data_ptr(),
nt._lengths.data_ptr(),
}
return nt, data_ptrs
def fn(record_stream):
nt, data_ptrs = _create_nt()
s = torch.cuda.Stream()
with torch.cuda.stream(s):
# emulate doing something long via sleep
per_ms = 2e7
torch.cuda._sleep(int(per_ms * 100))
if record_stream:
nt.record_stream(s)
return data_ptrs
# expect memory reuse when record_stream() is not run
data_ptrs = fn(record_stream=False)
nt, nt_data_ptrs = _create_nt()
self.assertEqual(data_ptrs, nt_data_ptrs)
del nt
torch.cuda.synchronize()
# expect memory to be preserved (no reuse) when record_stream() is run
data_ptrs = fn(record_stream=True)
nt, nt_data_ptrs = _create_nt()
self.assertEqual(len(data_ptrs.intersection(nt_data_ptrs)), 0)
@dtypes(torch.float32)
@parametrize(
"func",
[torch.ops.aten.sum.dim_IntList, torch.ops.aten.mean.dim],
name_fn=get_op_name,
)
@parametrize("keepdim", [False, True])
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
def test_jagged_op_different_output_shape_dim(
self, device, dtype, keepdim, requires_grad, components_require_grad, func
):
"""
Operator passes when reducing on valid reduction dimensions.
This test is for operators which return an output tensor with a shape different from the input tensor.
"""
if get_op_name(func) == "mean" and not keepdim:
return
op_name = get_op_name(func)
ts = self._get_list_for_jagged_tensor(
((2, 3, 4), 3, 4), device=device, requires_grad=True
) # (B, j0, 3, 4)
# verify correctness of shapes (assuming that ragged_idx == 1)
if op_name == "sum":
reduce_dims = (
((0, 1), (3, 4), (1, 1, 3, 4), (0,)), # batch, ragged
((2, 3), (3, None), (3, None, 1, 1), (1, 2)), # non-batch, non-batch
((0, 1, 3), (3,), (1, 1, 3, 1), (0, 2)), # batch, ragged, non-batch
((0, 1, 2), (4,), (1, 1, 1, 4), (0, 1)), # batch, ragged, non-batch
(
(0, 1, 2, 3),
(),
(1, 1, 1, 1),
(0, 1, 2),
), # batch, ragged, non-batch, non-batch
((2,), (3, None, 4), (3, None, 1, 4), (1,)), # non-batch
) # (dims, expected shape, expected keepdim shape, reduce_dim_expected), where j0 is represented as None
elif op_name == "mean":
reduce_dims = (
((2,), (3, None, 4), (3, None, 1, 4), (1,)),
((3,), (3, None, 3), (3, None, 3, 1), (2,)),
)
for rd, ref_shape_no_keepdim, ref_shape_keepdim, _ in reduce_dims:
nt = torch.nested.as_nested_tensor(ts, layout=torch.jagged)
out = func(nt, dim=rd, keepdim=keepdim)
ref_shape = ref_shape_keepdim if keepdim else ref_shape_no_keepdim
if not torch.compiler.is_compiling(): # if not using torch dynamo
self.assertEqual(len(out.shape), len(ref_shape))
for o, r in zip(out.shape, ref_shape):
if r is not None:
self.assertEqual(o, r)
else:
self.assertTrue(isinstance(o, torch.SymInt))
# verify correctness of values
tensor_lists = self._get_example_tensor_lists(
include_list_of_lists=False,
include_requires_grad=components_require_grad,
include_inner_dim_size_1=True,
)
for tensor_list, reduce_dim_tuple in itertools.product(
tensor_lists, reduce_dims
):
nt = torch.nested.nested_tensor(
tensor_list,
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=requires_grad,
)
reduce_dim, _, _, reduce_dim_expected = reduce_dim_tuple
if nt.dim() > reduce_dim[-1]:
out_actual = func(nt, dim=reduce_dim, keepdim=keepdim)
if nt._ragged_idx in reduce_dim: # raggedness reduced away
out_expected = func(
nt.values(), dim=reduce_dim_expected, keepdim=keepdim
)
self.assertTrue(torch.allclose(out_actual, out_expected))
else: # raggedness preserved
out_expected = func(nt.values(), dim=reduce_dim_expected)
self.assertTrue(
torch.allclose(
out_actual.values().view(-1), out_expected.view(-1)
)
)
@dtypes(torch.float32)
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
@parametrize(
"func",
[torch.nn.functional.softmax, torch.nn.functional.log_softmax],
name_fn=lambda func: func.__name__,
)
def test_softmax_dim(
self,
device,
dtype,
requires_grad,
components_require_grad,
func,
):
"""
Softmax passes when reducing on valid reduction dimensions.
"""
ts = self._get_list_for_jagged_tensor(
((2, 3, 4), 3, 4), device=device, requires_grad=True
) # (B, j0, 3, 4)
output_shape = (3, None, 3, 4)
# verify correctness of shapes (assuming that ragged_idx == 1)
reduce_dims = (
(2, 1),
(3, 2),
) # (reduction dimension, effective reduction dimension for baseline)
for reduce_dim, _ in reduce_dims:
nt = torch.nested.as_nested_tensor(ts, layout=torch.jagged)
out_actual = func(nt, dim=reduce_dim)
torch._dynamo.disable(self.assertEqual)(
len(out_actual.shape), len(output_shape)
) # disable if running on dynamo
for dim_actual, dim_expected in zip(out_actual.shape, output_shape):
if dim_expected is not None:
self.assertEqual(dim_actual, dim_expected)
else:
self.assertTrue(isinstance(dim_actual, torch.SymInt))
# verify correctness of values
tensor_lists = self._get_example_tensor_lists(
include_list_of_lists=False,
include_requires_grad=components_require_grad,
include_inner_dim_size_1=True,
)
for tensor_list, reduce_dim_tuple in itertools.product(
tensor_lists, reduce_dims
):
nt = torch.nested.nested_tensor(
tensor_list,
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=requires_grad,
)
reduce_dim, reduce_dim_expected = reduce_dim_tuple
if nt.dim() > reduce_dim:
# nested tensor
out_actual = func(nt, dim=reduce_dim)
# dense tensor of dimensions 1 less than out_actual
out_expected = func(nt.values(), dim=reduce_dim_expected)
self.assertTrue(
torch.allclose(out_actual.values().view(-1), out_expected.view(-1))
)
@dtypes(torch.float32)
@parametrize(
"func",
[torch.ops.aten.sum.dim_IntList, torch.ops.aten.mean.dim],
name_fn=get_op_name,
)
@parametrize("keepdim", [False, True])
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
def test_op_dim_reduce_ragged_idx_1_different_output_shape(
self, device, dtype, keepdim, requires_grad, components_require_grad, func
):
"""
Operator on NestedTensor passes when trying to reduce across ragged dimension, where ragged_idx == 1.
This test is for operators which return an output tensor with a shape different from the input tensor.
"""
if get_op_name(func) == "mean" and not keepdim:
return
op_name = get_op_name(func)
tensor_lists = self._get_example_tensor_lists(
include_list_of_lists=False,
include_requires_grad=components_require_grad,
include_inner_dim_size_1=True, # (B, *, 1)
)
reduce_dim = (1,) # ragged
for tensor_list in tensor_lists:
nt = torch.nested.nested_tensor(
tensor_list,
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=requires_grad,
)
out_actual = func(nt, dim=reduce_dim, keepdim=keepdim)
out_expected = torch.cat(
[func(t, dim=(reduce_dim[0] - 1)).unsqueeze(0) for t in nt.unbind()]
)
if keepdim:
out_expected = out_expected.unsqueeze(reduce_dim[0])
self.assertFalse(
out_actual.is_nested,
f"{op_name}(): the result of reducing a nested tensor along the ragged dimension is a dense tensor",
) # output is a dense tensor
self.assertEqual(out_actual, out_expected)
@dtypes(torch.float32)
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
def test_softmax_dim_reduce_ragged_idx_1(
self, device, dtype, requires_grad, components_require_grad
):
"""
Softmax on NestedTensor passes when trying to reduce across ragged dimension, where ragged_idx == 1.
"""
tensor_lists = self._get_example_tensor_lists(
include_list_of_lists=False,
include_requires_grad=components_require_grad,
include_inner_dim_size_1=True, # (B, *, 1)
include_2d_tensor=True, # (B, *)
)
reduce_dim = 1 # ragged
for tensor_list in tensor_lists:
nt = torch.nested.nested_tensor(
tensor_list,
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=requires_grad,
)
out_actual = torch.nn.functional.softmax(nt, dim=reduce_dim)
out_expected = torch.cat(
[
torch.nn.functional.softmax(t, dim=reduce_dim - 1)
for t in nt.unbind()
]
)
self.assertTrue(
out_actual.is_nested,
"softmax(): the result of reducing a nested tensor along the ragged dimension is a nested tensor",
) # output is a nested tensor
self.assertTrue(torch.allclose(out_actual.values(), out_expected))
@dtypes(torch.float32)
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
@parametrize(
"func",
[torch.nn.functional.softmax, torch.nn.functional.log_softmax],
name_fn=lambda func: func.__name__,
)
def test_softmax_reduce_batch_dim(
self, device, dtype, requires_grad, components_require_grad, func
):
"""
Softmax on NestedTensor fails when trying to reduce across batch dimension.
"""
tensor_lists = self._get_example_tensor_lists(
include_list_of_lists=False,
include_requires_grad=components_require_grad,
include_inner_dim_size_1=True, # (B, *, 1)
)
reduce_dim = 0 # batch
for tensor_list in tensor_lists:
nt = torch.nested.nested_tensor(
tensor_list,
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=requires_grad,
)
with self.assertRaisesRegex(
RuntimeError,
"not supported when reducing across the batch dimension for NestedTensor",
):
out = func(nt, dim=reduce_dim)
@dtypes(torch.float32)
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
def test_layer_norm_reduce_ragged_idx_1(
self, device, dtype, requires_grad, components_require_grad
):
"""
Layer normalization on NestedTensor passes when trying to normalize across ragged dimension, where ragged_idx == 1.
"""
# requires_grad = False does not currently work with dynamo tests and throws this error:
# AssertionError: SymInts must use SymNodeVariable.
# If the underlying value is static, we will create a ConstantVariable and specialize.
if torch._dynamo.is_compiling() and not requires_grad:
return
tensor_lists = self._get_example_tensor_lists(
include_list_of_lists=False,
include_requires_grad=components_require_grad,
include_inner_dim_size_1=True, # (B, *, 1)
)
for tensor_list in tensor_lists:
nt = torch.nested.nested_tensor(
tensor_list,
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=requires_grad,
)
if (
nt.dim() >= 3
): # layer norm only works for tensors with 3 or more dimensions
normalized_shape = nt.shape[nt._ragged_idx :]
out_actual = torch.nn.functional.layer_norm(
nt, normalized_shape=normalized_shape
)
out_expected = torch.cat(
[
torch.nn.functional.layer_norm(t, normalized_shape=t.shape)
for t in nt.unbind()
]
) # e.g. in 3D tensor (B, *, M), performs layer normalization on B 2D tensors (*, M)
self.assertTrue(
out_actual.is_nested,
"layer_norm(): the result of reducing a nested tensor along the ragged dimension is a nested tensor",
) # output is a nested tensor
self.assertEqual(out_actual._values.shape, out_expected.shape)
self.assertTrue(torch.allclose(out_actual.values(), out_expected))
@dtypes(torch.float32)
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
def test_layer_norm_2d_input(
self,
device,
dtype,
requires_grad,
components_require_grad,
):
"""
Layer normalization on NestedTensor fails when trying to operate on a 2-dimensional tensor
"""
tensor_lists = self._get_example_tensor_lists(
include_list_of_lists=False,
include_requires_grad=components_require_grad,
include_inner_dim_size_1=True, # (B, *, 1)
include_2d_tensor=True, # (B, *)
)
for tensor_list in tensor_lists:
nt = torch.nested.nested_tensor(
tensor_list,
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=requires_grad,
)
if nt.dim() <= 2:
with self.assertRaisesRegex(
RuntimeError,
"not supported for NestedTensor objects with 2 or fewer dimensions",
):
out = torch.nn.functional.layer_norm(
nt, normalized_shape=(nt.shape[nt._ragged_idx],)
)
@dtypes(torch.float32)
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
def test_layer_norm_operate_on_batch_dim(
self,
device,
dtype,
requires_grad,
components_require_grad,
):
"""
Layer normalization on NestedTensor fails when trying to operate on the batch dimension
"""
tensor_lists = self._get_example_tensor_lists(
include_list_of_lists=False,
include_requires_grad=components_require_grad,
include_inner_dim_size_1=True, # (B, *, 1)
include_2d_tensor=True, # (B, *)
)
for tensor_list in tensor_lists:
nt = torch.nested.nested_tensor(
tensor_list,
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=requires_grad,
)
if nt.dim() > 2: # cannot perform layer normalization on 2D tensors
with self.assertRaisesRegex(
RuntimeError,
"not supported when normalizing over the batch dimension for NestedTensor",
):
out = torch.nn.functional.layer_norm(nt, normalized_shape=nt.shape)
@dtypes(torch.float32)
@parametrize(
"func",
[torch.ops.aten.sum.dim_IntList, torch.ops.aten.mean.dim],
name_fn=get_op_name,
)
@parametrize(
"transpose_offset", [1, 2]
) # [transpose consecutive dimensions, transpose nonconsecutive dimensions]
@parametrize("keepdim", [False, True])
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
def test_op_dim_reduce_ragged_idx_greater_than_1_different_output_shape(
self,
device,
dtype,
keepdim,
requires_grad,
components_require_grad,
func,
transpose_offset,
):
"""
Operator on NestedTensor passes when trying to reduce across a transposed ragged dimension, i.e. ragged_idx > 1
This test is for operators which return an output tensor with a shape different from the input tensor.
"""
if get_op_name(func) == "mean" and not keepdim:
return
op_name = get_op_name(func)
tensor_lists = self._get_example_tensor_lists(
include_list_of_lists=False,
include_requires_grad=components_require_grad,
include_inner_dim_size_1=True, # (B, *, 1)
include_2d_tensor=True, # (B, *)
)
for tensor_list in tensor_lists:
nt = torch.nested.nested_tensor(
tensor_list,
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=requires_grad,
)
if nt.dim() > nt._ragged_idx + transpose_offset:
nt_transposed = nt.transpose(
nt._ragged_idx, nt._ragged_idx + transpose_offset
)
reduce_dim = (nt_transposed._ragged_idx,) # ragged
out_actual = func(nt_transposed, dim=reduce_dim, keepdim=keepdim)
out_expected = torch.cat(
[
func(t, dim=(reduce_dim[0] - 1)).unsqueeze(0)
for t in nt_transposed.unbind()
]
)
if keepdim:
out_expected = out_expected.unsqueeze(reduce_dim[0])
self.assertFalse(
out_actual.is_nested,
f"{op_name}(): the result of reducing a nested tensor along the ragged dimension is a dense tensor",
) # output is a dense tensor
self.assertEqual(out_actual, out_expected)
@dtypes(torch.float32)
@parametrize(
"transpose_offset", [1, 2]
) # [transpose consecutive dimensions, transpose nonconsecutive dimensions]
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
def test_softmax_dim_reduce_ragged_idx_greater_than_1_same_output_shape(
self,
device,
dtype,
requires_grad,
components_require_grad,
transpose_offset,
):
"""
Softmax on NestedTensor fails when trying to reduce across a transposed ragged dimension, i.e. ragged_idx > 1
This test is for operators which return an output tensor with the same shape as the input tensor.
"""
tensor_lists = self._get_example_tensor_lists(
include_list_of_lists=False,
include_requires_grad=components_require_grad,
include_inner_dim_size_1=True, # (B, *, 1)
)
for tensor_list in tensor_lists:
nt = torch.nested.nested_tensor(
tensor_list,
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=requires_grad,
)
if nt.dim() > nt._ragged_idx + transpose_offset:
nt_transposed = nt.transpose(
nt._ragged_idx, nt._ragged_idx + transpose_offset
)
reduce_dim = nt_transposed._ragged_idx # ragged
with self.assertRaisesRegex(
RuntimeError,
"not supported when reducing along the ragged dimension for ragged_idx > 1 for NestedTensor",
):
out = torch.nn.functional.softmax(nt_transposed, dim=reduce_dim)
@dtypes(torch.float32)
@parametrize(
"func",
[torch.ops.aten.sum.dim_IntList, torch.ops.aten.mean.dim],
name_fn=get_op_name,
)
@parametrize("keepdim", [False, True])
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
def test_op_dim_transpose_non_ragged_dim_different_output_shape(
self, device, dtype, keepdim, requires_grad, components_require_grad, func
):
"""
Operator passes when reducing transposed nested tensors on valid reduction dimensions.
This test is for operators which return an output tensor with a shape different from the input tensor.
"""
if get_op_name(func) == "mean" and not keepdim:
return
# verify correctness of shapes (assuming that ragged_idx == 1)
if get_op_name(func) == "sum":
reduce_dims = (
((0, 1), (3, 4), (1, 1, 3, 4), (0,)), # batch, ragged
((2, 3), (3, None), (3, None, 1, 1), (1, 2)), # non-batch, non-batch
((0, 1, 3), (3,), (1, 1, 3, 1), (0, 2)), # batch, ragged, non-batch
((0, 1, 2), (4,), (1, 1, 1, 4), (0, 1)), # batch, ragged, non-batch
(
(0, 1, 2, 3),
(),
(1, 1, 1, 1),
(0, 1, 2),
), # batch, ragged, non-batch, non-batch
((2,), (3, None, 4), (3, None, 1, 4), (1,)), # non-batch
) # (dims, expected shape, expected keepdim shape, reduce_dim_expected), where j0 is represented as None
elif get_op_name(func) == "mean":
reduce_dims = (
((2,), (3, None, 4), (3, None, 1, 4), (1,)),
((3,), (3, None, 3), (3, None, 3, 1), (2,)),
)
# verify correctness of values
tensor_lists = self._get_example_tensor_lists(
include_list_of_lists=False,
include_requires_grad=components_require_grad,
)
for tensor_list, reduce_dim_tuple in itertools.product(
tensor_lists, reduce_dims
):
nt = torch.nested.nested_tensor(
tensor_list,
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=requires_grad,
).transpose(-1, -2)
reduce_dim, _, _, reduce_dim_expected = reduce_dim_tuple
if nt.dim() > max(
reduce_dim[-1], nt._ragged_idx + 2
): # ensure that transposed dimensions are non-batch, non-ragged dimensions
out_actual = func(nt, dim=reduce_dim, keepdim=keepdim)
if nt._ragged_idx in reduce_dim: # raggedness reduced away
out_expected = func(
nt.values(), dim=reduce_dim_expected, keepdim=keepdim
)
self.assertTrue(torch.allclose(out_actual, out_expected))
else: # raggedness preserved
out_expected = func(nt.values(), dim=reduce_dim_expected)
self.assertTrue(
torch.allclose(
out_actual.values().view(-1), out_expected.view(-1)
)
)
@dtypes(torch.float32)
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
def test_softmax_dim_transpose_non_ragged_dim(
self,
device,
dtype,
requires_grad,
components_require_grad,
):
"""
Softmax passes when reducing transposed nested tensors on valid reduction dimensions.
This test is for operators which return an output tensor with the same shape as the input tensor.
"""
# verify correctness of shapes (assuming that ragged_idx == 1)
reduce_dims = (
(2, 1),
(3, 2),
) # (reduction dimension, effective reduction dimension for baseline)
# verify correctness of values
tensor_lists = self._get_example_tensor_lists(
include_list_of_lists=False,
include_requires_grad=components_require_grad,
include_inner_dim_size_1=True, # (B, *, 1)
)
for tensor_list, reduce_dim_tuple in itertools.product(
tensor_lists, reduce_dims
):
nt = torch.nested.nested_tensor(
tensor_list,
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=requires_grad,
).transpose(-1, -2)
reduce_dim, reduce_dim_expected = reduce_dim_tuple
if nt.dim() > max(reduce_dim, nt._ragged_idx + 2):
out_actual = torch.nn.functional.softmax(
nt, dim=reduce_dim
) # nested tensor
out_expected = torch.nn.functional.softmax(
nt.values(), dim=reduce_dim_expected
) # dense tensor of dimensions 1 less than out_actual
self.assertTrue(
torch.allclose(out_actual.values().view(-1), out_expected.view(-1))
)
@dtypes(torch.float32)
@parametrize("keepdim", [False, True])
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
def test_sum_dim_reduce_ragged_and_non_batch(
self,
device,
dtype,
keepdim,
requires_grad,
components_require_grad,
):
"""
Sum on NestedTensor fails when trying to reduce across ragged and non-batch dimensions
"""
tensor_lists = self._get_example_tensor_lists(
include_list_of_lists=False, include_requires_grad=components_require_grad
)
reduce_dims = (
(1, 2), # ragged, non-batch
(1, 3), # ragged, non-batch
)
for tensor_list, reduce_dim in itertools.product(tensor_lists, reduce_dims):
nt = torch.nested.nested_tensor(
tensor_list,
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=requires_grad,
)
if nt.dim() > reduce_dim[-1]:
with self.assertRaisesRegex(
RuntimeError,
"reducing along a ragged and non-batch dimension is not supported",
):
out = torch.sum(nt, dim=reduce_dim, keepdim=keepdim)
@dtypes(torch.float32)
@parametrize("keepdim", [False, True])
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
def test_sum_dim_reduce_batch_and_non_batch(
self,
device,
dtype,
keepdim,
requires_grad,
components_require_grad,
):
"""
Sum on NestedTensor fails when trying to reduce across batch and non-batch dimensions
"""
tensor_lists = self._get_example_tensor_lists(
include_list_of_lists=False, include_requires_grad=components_require_grad
)
reduce_dims = (
(0, 2), # batch, non-batch
(0, 3), # batch, non-batch
)
for tensor_list, reduce_dim in itertools.product(tensor_lists, reduce_dims):
nt = torch.nested.nested_tensor(
tensor_list,
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=requires_grad,
)
if nt.dim() > reduce_dim[-1]:
with self.assertRaisesRegex(
RuntimeError,
"reducing along the batch dimension but not the ragged dimension "
+ "is not supported",
):
out = torch.sum(nt, dim=reduce_dim, keepdim=keepdim)
@dtypes(torch.float32)
@parametrize(
"func",
[torch.ops.aten.sum.dim_IntList, torch.ops.aten.mean.dim],
name_fn=get_op_name,
)
@parametrize("keepdim", [False, True])
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
def test_op_dim_reduce_batch_only_different_output_shape(
self, device, dtype, keepdim, requires_grad, components_require_grad, func
):
"""
Operator on NestedTensor fails when trying to reduce across batch dimension
"""
if get_op_name(func) == "mean" and not keepdim:
return
tensor_lists = self._get_example_tensor_lists(
include_list_of_lists=False, include_requires_grad=components_require_grad
)
reduce_dim = (0,) # batch
for tensor_list in tensor_lists:
nt = torch.nested.nested_tensor(
tensor_list,
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=requires_grad,
)
with self.assertRaisesRegex(
RuntimeError,
"reducing along the batch dimension but not the ragged dimension "
+ "is not supported",
):
out = func(nt, dim=reduce_dim, keepdim=keepdim)
@dtypes(torch.float32)
@parametrize(
"func",
[torch.ops.aten.sum.dim_IntList, torch.ops.aten.mean.dim],
name_fn=get_op_name,
)
@parametrize("keepdim", [False, True])
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
def test_op_dim_with_lengths_different_output_shape(
self,
device,
dtype,
keepdim,
requires_grad,
components_require_grad,
func,
):
"""
Operator on NestedTensor fails when trying to reduce a nested tensor with lengths,
i.e. a nested tensor with holes, if reducing on the ragged dimension.
This test is for operators which return an output tensor with different shape than the input tensor.
"""
if get_op_name(func) == "mean" and not keepdim:
return
reduce_dims = ((1,), (2,), (2, 3))
lengths = torch.randint(5, 10, (20,), device=device)
offsets = torch.zeros((21,), device=device, dtype=torch.int)
torch.cumsum(lengths, dim=0, out=offsets[1:])
values = torch.randn(
(offsets[-1].item(), 20),
device=device,
dtype=dtype,
requires_grad=requires_grad,
)
nt_with_holes = torch.nested.nested_tensor_from_jagged(
values,
offsets,
lengths=offsets.diff() - 2, # arbitrary subtraction to create holes
)
for reduce_dim in reduce_dims:
if nt_with_holes.dim() > reduce_dim[-1]:
if nt_with_holes._ragged_idx in reduce_dim:
with self.assertRaisesRegex(
RuntimeError,
"reducing across the ragged dimension is not supported for "
+ "non-contiguous nested tensors with holes",
):
out = func(nt_with_holes, dim=reduce_dim, keepdim=keepdim)
else:
out = func(nt_with_holes, dim=reduce_dim, keepdim=keepdim)
@dtypes(torch.float32)
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
def test_softmax_dim_with_lengths(
self,
device,
dtype,
requires_grad,
components_require_grad,
):
"""
Softmax on NestedTensor fails when trying to reduce a nested tensor with lengths,
i.e. a nested tensor with holes, if reducing on the ragged dimension.
"""
reduce_dims = (1, 2, 3)
lengths = torch.randint(5, 10, (20,), device=device)
offsets = torch.zeros((21,), device=device, dtype=torch.int)
torch.cumsum(lengths, dim=0, out=offsets[1:])
values = torch.randn(
(offsets[-1].item(), 20),
device=device,
dtype=dtype,
requires_grad=requires_grad,
)
nt_with_holes = torch.nested.nested_tensor_from_jagged(
values,
offsets,
lengths=offsets.diff() - 2, # arbitrary subtraction to create holes
)
for reduce_dim in reduce_dims:
if nt_with_holes.dim() > reduce_dim:
if nt_with_holes._ragged_idx == reduce_dim:
with self.assertRaisesRegex(
RuntimeError,
"not supported where lengths is not None "
+ "if reducing across the ragged dimension for NestedTensor",
):
out = torch.nn.functional.softmax(nt_with_holes, dim=reduce_dim)
else:
out = torch.nn.functional.softmax(nt_with_holes, dim=reduce_dim)
@skipIfTorchDynamo(
"ragged_size = nt_with_holes.shape[nt_with_holes._ragged_idx] does not currently work "
+ "with dynamo tests and throws this error: `AssertionError: SymInts must use SymNodeVariable. "
+ "If the underlying value is static, we will create a ConstantVariable and specialize.`"
)
@dtypes(torch.float32)
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
def test_layer_norm_with_lengths(
self,
device,
dtype,
requires_grad,
components_require_grad,
):
"""
Layer normalization on NestedTensor fails when trying to operate on a nested tensor with lengths,
i.e. a nested tensor with holes, if operating on the ragged dimension.
"""
# create components for nested tensor
lengths = torch.randint(5, 10, (20,), device=device)
offsets = torch.zeros((21,), device=device, dtype=torch.int)
torch.cumsum(lengths, dim=0, out=offsets[1:])
values = torch.randn(
(offsets[-1].item(), 10, 30),
device=device,
dtype=dtype,
requires_grad=requires_grad,
)
nt_with_holes = torch.nested.nested_tensor_from_jagged(
values,
offsets,
lengths=offsets.diff() - 2, # arbitrary subtraction to create holes
)
ragged_size = nt_with_holes.shape[nt_with_holes._ragged_idx]
normalized_shapes = (
(10, 30), # normalization on non-ragged dimension passes
(ragged_size, 10, 30), # normalization on ragged dimension fails
)
for normalized_shape in normalized_shapes:
if ragged_size in normalized_shape:
with self.assertRaisesRegex(
RuntimeError,
"not supported where lengths is not None if operating on the ragged dimension for NestedTensor",
):
out = torch.nn.functional.layer_norm(
nt_with_holes, normalized_shape=normalized_shape
)
else:
out = torch.nn.functional.layer_norm(
nt_with_holes, normalized_shape=normalized_shape
)
@unittest.skipIf(
PYTORCH_CUDA_MEMCHECK, "is_pinned uses failure to detect pointer property"
)
@onlyCUDA
def test_pin_memory(self, device):
nt_contiguous, nt_noncontiguous = random_nt_noncontiguous_pair((2, 3, 6, 7))
for nt in [nt_contiguous, nt_noncontiguous]:
self.assertFalse(nt.is_pinned())
pinned = nt.pin_memory()
self.assertTrue(pinned.is_pinned())
self.assertEqual(nt, pinned)
self.assertNotEqual(nt.data_ptr(), pinned.data_ptr())
# test that pin_memory on already pinned tensor has no effect
self.assertIs(pinned, pinned.pin_memory())
self.assertEqual(pinned.data_ptr(), pinned.pin_memory().data_ptr())
@torch.compiler.disable
def _validate_nt(
self,
nt,
device,
dtype,
layout,
requires_grad,
dim,
batch_size,
contiguous,
cached_min_seqlen=None,
cached_max_seqlen=None,
base=None,
ref_nt=None,
):
# Validate a bunch of properties after NT construction.
device = torch.device(device)
self.assertEqual(nt.dim(), dim)
self.assertEqual(nt.device, device)
self.assertEqual(nt.dtype, dtype)
self.assertEqual(nt.layout, layout)
self.assertEqual(nt.requires_grad, requires_grad)
self.assertEqual(nt.is_contiguous(), contiguous)
if layout == torch.jagged:
self.assertEqual(nt._values.device, device)
self.assertEqual(nt._offsets.device, device)
self.assertEqual(nt.shape[0], batch_size)
self.assertTrue(isinstance(nt.shape[1], torch.SymInt))
if base is not None:
self.assertTrue(nt._is_view() and nt._base is base)
replay_cache = nt._view_func(torch.randn_like(nt._base))._metadata_cache
self.assertEqual(
"min_seqlen" in replay_cache, cached_min_seqlen is not None
)
self.assertEqual(
"max_seqlen" in replay_cache, cached_max_seqlen is not None
)
self.assertEqual(
"min_seqlen" in nt._metadata_cache, cached_min_seqlen is not None
)
self.assertEqual(
"max_seqlen" in nt._metadata_cache, cached_max_seqlen is not None
)
if cached_min_seqlen is not None:
self.assertEqual(nt._min_seqlen, cached_min_seqlen)
if cached_max_seqlen is not None:
self.assertEqual(nt._max_seqlen, cached_max_seqlen)
if ref_nt is not None:
self.assertEqual(nt.size(0), ref_nt.size(0))
for n1, n2 in zip(nt.unbind(), ref_nt.unbind()):
self.assertEqual(n1, n2)
@dtypes(torch.float, torch.double, torch.half)
@parametrize("requires_grad", [False, True])
@parametrize("components_require_grad", [False, True])
def test_jagged_layout_construction_nested_tensor(
self, device, dtype, requires_grad, components_require_grad
):
for tensor_list in self._get_example_tensor_lists(
include_list_of_lists=True, include_requires_grad=components_require_grad
):
nt = torch.nested.nested_tensor(
tensor_list,
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=requires_grad,
)
expected_dim = torch.as_tensor(tensor_list[0]).dim() + 1
expected_batch_size = len(tensor_list)
expected_contiguous = True
expected_min_seqlen = min(
(torch.tensor(t) if isinstance(t, list) else t).shape[0]
for t in tensor_list
)
expected_max_seqlen = max(
(torch.tensor(t) if isinstance(t, list) else t).shape[0]
for t in tensor_list
)
self._validate_nt(
nt,
device,
dtype,
torch.jagged,
requires_grad,
expected_dim,
expected_batch_size,
expected_contiguous,
expected_min_seqlen,
expected_max_seqlen,
)
# Make sure grads -don't- flow back into original tensors for nested_tensor()
if requires_grad:
(nt * 2).backward(torch.ones_like(nt))
for t in tensor_list:
t = t if isinstance(t, torch.Tensor) else torch.as_tensor(t)
self.assertTrue(t.grad is None)
@dtypes(torch.float, torch.double, torch.half)
@parametrize("components_require_grad", [False, True])
def test_jagged_layout_construction_as_nested_tensor(
self, device, dtype, components_require_grad
):
# NB: as_nested_tensor(tensor_list) doesn't support lists of lists for tensor_list
for tensor_list in self._get_example_tensor_lists(
include_list_of_lists=False, include_requires_grad=components_require_grad
):
nt = torch.nested.as_nested_tensor(
tensor_list, device=device, dtype=dtype, layout=torch.jagged
)
# nt.requires_grad=True should be set if at least one component requires grad
expected_dim = tensor_list[0].dim() + 1
expected_batch_size = len(tensor_list)
expected_contiguous = True
expected_min_seqlen = min(
(torch.tensor(t) if isinstance(t, list) else t).shape[0]
for t in tensor_list
)
expected_max_seqlen = max(
(torch.tensor(t) if isinstance(t, list) else t).shape[0]
for t in tensor_list
)
self._validate_nt(
nt,
device,
dtype,
torch.jagged,
components_require_grad,
expected_dim,
expected_batch_size,
expected_contiguous,
expected_min_seqlen,
expected_max_seqlen,
)
# Make sure grads flow back into original tensors for as_nested_tensor()
if components_require_grad:
(nt * 2).backward(torch.ones_like(nt))
for t in tensor_list:
if t.requires_grad:
self.assertEqual(t.grad, torch.ones_like(t) * 2)
else:
self.assertTrue(t.grad is None)
@xfailIfTorchDynamo
@unittest.skipIf(
PYTORCH_CUDA_MEMCHECK, "is_pinned uses failure to detect pointer property"
)
@onlyCUDA
def test_jagged_layout_construction_with_pinned_memory(self, device):
for tensor_list in self._get_example_tensor_lists():
nt = torch.nested.nested_tensor(
tensor_list, layout=torch.jagged, device="cpu", pin_memory=True
)
expected_dim = torch.as_tensor(tensor_list[0]).dim() + 1
expected_batch_size = len(tensor_list)
expected_min_seqlen = min(
(torch.tensor(t) if isinstance(t, list) else t).shape[0]
for t in tensor_list
)
expected_max_seqlen = max(
(torch.tensor(t) if isinstance(t, list) else t).shape[0]
for t in tensor_list
)
self._validate_nt(
nt,
device="cpu",
dtype=torch.float32,
layout=torch.jagged,
requires_grad=False,
dim=expected_dim,
batch_size=expected_batch_size,
contiguous=True,
cached_min_seqlen=expected_min_seqlen,
cached_max_seqlen=expected_max_seqlen,
)
self.assertTrue(nt.is_pinned())
@dtypes(torch.float, torch.double, torch.half)
@parametrize("requires_grad", [False, True])
@parametrize("values_is_view", [False, True])
def test_jagged_view_from_values_offsets(
self, device, dtype, requires_grad, values_is_view
):
if values_is_view:
# make values a view of base
base = torch.randn(
2, 3, 4, 5, 6, device=device, dtype=dtype, requires_grad=requires_grad
)
values = base.flatten(0, -2)
else:
values = torch.randn(
10, 5, device=device, dtype=dtype, requires_grad=requires_grad
)
offsets = torch.tensor([0, 2, 4, 6, 10], device=device, dtype=torch.int64)
nt = nested_view_from_values_offsets(values, offsets)
expected_dim = values.dim() + 1
expected_batch_size = offsets.shape[0] - 1
expected_base = base if values_is_view else values
lengths = offsets.diff()
self._validate_nt(
nt,
device,
dtype,
torch.jagged,
requires_grad,
expected_dim,
expected_batch_size,
# ensure NT is a proper view
base=expected_base,
contiguous=True,
# if no min / max are passed, expect the metadata cache to be empty
cached_min_seqlen=None,
cached_max_seqlen=None,
)
if requires_grad:
# Make sure grads flow back
(nt * 2).backward(torch.ones_like(nt))
@torch.compiler.disable
def _check_grad(t):
self.assertTrue(t.grad is not None)
self.assertEqual(t.grad, torch.ones_like(t) * 2)
_check_grad(base if values_is_view else values)
@dtypes(torch.float)
@parametrize("pass_min_max", [False, True])
def test_nested_tensor_from_jagged(self, device, dtype, pass_min_max):
# === construct from (values, offsets) ===
values = torch.randn(10, 5, device=device, dtype=dtype)
offsets = torch.tensor([0, 2, 4, 6, 10], device=device, dtype=torch.int64)
# compute min / max seqlen
lengths = offsets.diff()
min_seqlen = lengths.min().item()
max_seqlen = lengths.max().item()
if pass_min_max:
nt = torch.nested.nested_tensor_from_jagged(
values, offsets=offsets, min_seqlen=min_seqlen, max_seqlen=max_seqlen
)
else:
nt = torch.nested.nested_tensor_from_jagged(values, offsets=offsets)
self._validate_nt(
nt,
device,
dtype,
torch.jagged,
requires_grad=False,
dim=3,
batch_size=4,
contiguous=True,
cached_min_seqlen=(min_seqlen if pass_min_max else None),
cached_max_seqlen=(max_seqlen if pass_min_max else None),
base=values,
)
# === construct from (values, offsets, lengths) ===
lengths = torch.tensor([2, 1, 1, 2], device=device)
# compute min / max seqlen
min_seqlen = lengths.min().item()
max_seqlen = lengths.max().item()
if pass_min_max:
nt = torch.nested.nested_tensor_from_jagged(
values,
offsets=offsets,
lengths=lengths,
min_seqlen=min_seqlen,
max_seqlen=max_seqlen,
)
else:
nt = torch.nested.nested_tensor_from_jagged(
values, offsets=offsets, lengths=lengths
)
# when both offsets / lengths are specified, expect non-contiguous
self._validate_nt(
nt,
device,
dtype,
torch.jagged,
requires_grad=False,
dim=3,
batch_size=4,
contiguous=False,
cached_min_seqlen=(min_seqlen if pass_min_max else None),
cached_max_seqlen=(max_seqlen if pass_min_max else None),
base=values,
)
self.assertIs(nt.lengths(), lengths)
# === construct from (values, lengths) ===
values = torch.randn(14, 5, device=device, dtype=dtype)
lengths = torch.tensor([2, 3, 4, 5], device=device)
# compute min / max seqlen
min_seqlen = lengths.min().item()
max_seqlen = lengths.max().item()
if pass_min_max:
nt = torch.nested.nested_tensor_from_jagged(
values, lengths=lengths, min_seqlen=min_seqlen, max_seqlen=max_seqlen
)
else:
nt = torch.nested.nested_tensor_from_jagged(values, lengths=lengths)
# for now, if only lengths is specified, convert to offsets to integrate best with the
# existing kernels
expected_offsets = torch.tensor([0, 2, 5, 9, 14], device=device)
expected_nt = torch.nested.nested_tensor_from_jagged(
values, offsets=expected_offsets
)
self._validate_nt(
nt,
device,
dtype,
torch.jagged,
requires_grad=False,
dim=3,
batch_size=4,
contiguous=True,
cached_min_seqlen=(min_seqlen if pass_min_max else None),
cached_max_seqlen=(max_seqlen if pass_min_max else None),
base=values,
ref_nt=expected_nt,
)
# error case: no offsets or lengths
with self.assertRaisesRegex(
RuntimeError, "At least one of offsets or lengths is required"
):
torch.nested.nested_tensor_from_jagged(values, offsets=None, lengths=None)
with self.assertRaisesRegex(ValueError, "Expected jagged_dim >=1, but got 0."):
torch.nested.nested_tensor_from_jagged(
values, lengths=lengths, jagged_dim=0
)
@onlyCPU
def test_nested_tensor_from_jagged_fx_trace(self, device):
def fn(x, y):
return torch.nested.nested_tensor_from_jagged(x, y)
def user_unwrapped(x, y):
return fn(x, y)
with self.assertRaisesRegex(
RuntimeError,
"torch.nested.nested_tensor_from_jagged does not support tracing with fx.symbolic_trace",
):
torch.fx.symbolic_trace(user_unwrapped)
@dtypes(torch.float, torch.double, torch.half)
@parametrize("dim", range(5))
@parametrize(
"layout",
[torch.strided, torch.jagged],
name_fn=lambda l: f"layout_{str(l).split('.')[1]}",
)
@parametrize("requires_grad", [False, True])
@parametrize("contiguous", [False, True])
def test_as_nested_tensor_from_tensor(
self, device, dtype, dim, layout, requires_grad, contiguous
):
if dim == 0:
t = torch.tensor(3.0, requires_grad=requires_grad)
else:
t = torch.randn(*(3 for _ in range(dim)), requires_grad=requires_grad)
assert t.dim() == dim
if dim < 2:
# 0-1 dim tensors can't be converted to NTs
with self.assertRaisesRegex(
RuntimeError, "Expected tensor argument to have dim"
):
nt = torch.nested.as_nested_tensor(
t, device=device, dtype=dtype, layout=layout
)
return
orig_t = t
if not contiguous:
t = t.transpose(0, 1)
nt = torch.nested.as_nested_tensor(t, device=device, dtype=dtype, layout=layout)
expected_dim = t.dim()
expected_batch_size = t.size(0)
expected_seqlen = t.size(1) if layout == torch.jagged else None
self._validate_nt(
nt,
device,
dtype,
layout,
requires_grad=requires_grad,
dim=dim,
batch_size=expected_batch_size,
contiguous=True,
cached_min_seqlen=expected_seqlen,
cached_max_seqlen=expected_seqlen,
)
if torch.device(device) == t.device and dtype == t.dtype and contiguous:
# should be the non-copying (view) case
self.assertTrue(nt._is_view() and nt._base is t)
# should have equivalent components to construction from unbound tensor list
nt_from_unbind = torch.nested.as_nested_tensor(
list(t.unbind(0)), device=device, dtype=dtype, layout=layout
)
self.assertEqualIgnoringNestedInts(nt, nt_from_unbind)
# ensure call on a NT with the same properties returns the NT directly
nt2 = torch.nested.as_nested_tensor(
nt, device=device, dtype=dtype, layout=layout
)
self.assertTrue(nt is nt2)
# ensure call with device=None uses input tensor device
nt3 = torch.nested.as_nested_tensor(
t.to(device=device, dtype=dtype),
device=None,
dtype=None,
layout=layout,
)
self._validate_nt(
nt3,
device,
dtype,
layout,
requires_grad=requires_grad,
dim=dim,
batch_size=expected_batch_size,
contiguous=True,
cached_min_seqlen=expected_seqlen,
cached_max_seqlen=expected_seqlen,
)
# we don't support conversion between layouts this way atm
other_layout = torch.strided if layout == torch.jagged else torch.jagged
with self.assertRaisesRegex(
RuntimeError, "Converting between nested tensor layouts is not supported"
):
torch.nested.as_nested_tensor(
nt, device=device, dtype=dtype, layout=other_layout
)
if requires_grad:
# make sure gradients flow back into inputs
(nt * 2).backward(torch.ones_like(nt))
self.assertEqual(orig_t.grad, torch.ones_like(orig_t) * 2)
@dtypes(torch.float32)
def test_construction_from_list(self, device, dtype):
from torch.fx.experimental.symbolic_shapes import is_nested_int
# success case: single ragged dim anywhere but the batch dim
for nt_dim in [2, 3, 4]:
for ragged_dim in range(1, nt_dim):
B = 6
shapes = [list(range(3, 3 + nt_dim - 1)) for _ in range(B)]
for b in range(B):
# subtract 1 to convert to component dim space
shapes[b][ragged_dim - 1] = torch.randint(
2, 9, (1,), device=device, dtype=torch.int64
).item()
components = [
torch.randn(shape, device=device, dtype=dtype) for shape in shapes
]
nt = torch.nested.nested_tensor(components, layout=torch.jagged)
self.assertEqual(nt.dim(), nt_dim)
self.assertEqual(nt._ragged_idx, ragged_dim)
for d in range(nt_dim):
self.assertEqual(d == ragged_dim, is_nested_int(nt.shape[d]))
# error case: empty list
with self.assertRaisesRegex(
RuntimeError, "Cannot construct a nested tensor from an empty tensor list"
):
torch.nested.nested_tensor([], layout=torch.jagged)
# error case: list of zero-dim tensors
with self.assertRaisesRegex(
RuntimeError,
"Cannot construct a nested tensor from a list of zero-dim tensors",
):
torch.nested.nested_tensor(
[
torch.tensor(3.0, device=device, dtype=dtype),
torch.tensor(4.0, device=device, dtype=dtype),
torch.tensor(5.0, device=device, dtype=dtype),
],
layout=torch.jagged,
)
# error case: multiple ragged dims
with self.assertRaisesRegex(
RuntimeError,
"Cannot represent given tensor list as a nested tensor with the jagged layout",
):
torch.nested.nested_tensor(
[
torch.randn(2, 3, device=device, dtype=dtype),
torch.randn(4, 5, device=device, dtype=dtype),
],
layout=torch.jagged,
)
# error case: components on multiple devices
if "cuda" in device:
with self.assertRaisesRegex(
RuntimeError,
"When constructing a nested tensor, all tensors in list must be on the same device",
):
torch.nested.nested_tensor(
[
torch.randn(2, 3, device=device, dtype=dtype),
torch.randn(2, 4, device="cpu", dtype=dtype),
],
layout=torch.jagged,
)
# error case: components with multiple dtypes
with self.assertRaisesRegex(
RuntimeError,
"When constructing a nested tensor, all tensors in list must have the same dtype",
):
torch.nested.nested_tensor(
[
torch.randn(2, 3, device=device, dtype=dtype),
torch.randn(2, 4, device=device, dtype=torch.float64),
],
layout=torch.jagged,
)
# error case: components with multiple dims
with self.assertRaisesRegex(
RuntimeError,
"When constructing a nested tensor, all tensors in list must have the same dim",
):
torch.nested.nested_tensor(
[
torch.randn(2, 3, device=device, dtype=dtype),
torch.randn(2, 3, 4, device=device, dtype=dtype),
],
layout=torch.jagged,
)
@dtypes(torch.double, torch.half)
@onlyCUDA
def test_device_dtype_transfer_updates_offsets(self, device, dtype):
for tensor_list in self._get_example_tensor_lists():
orig_device = torch.device("cpu")
orig_dtype = torch.float32
nt = torch.nested.nested_tensor(
tensor_list, layout=torch.jagged, device=orig_device, dtype=orig_dtype
)
self.assertEqual(torch.int64, nt.offsets().dtype)
nt = nt.to(device=device).to(dtype=dtype)
# offsets should still be int64 on the new device
self.assertEqual(nt.values().device, nt.offsets().device)
self.assertEqual(torch.int64, nt.offsets().dtype)
def test_unbind(self, device):
for tensor_list in self._get_example_tensor_lists():
nt = torch.nested.nested_tensor(
tensor_list, layout=torch.jagged, device=device
) # ragged_idx = 1
out = nt.unbind()
self.assertEqual(len(out), len(tensor_list))
for i, t in enumerate(out):
self.assertEqual(t, tensor_list[i])
@parametrize("ragged_idx", [2, 3])
def test_unbind_transpose(self, device, ragged_idx):
for tensor_list in self._get_example_tensor_lists():
nt = torch.nested.nested_tensor(
tensor_list, layout=torch.jagged, device=device
)
if ragged_idx < nt.dim():
nt = nt.transpose(1, ragged_idx) # set ragged_idx
out = nt.unbind()
self.assertEqual(len(out), len(tensor_list))
for i, t in enumerate(out):
self.assertEqual(
t.transpose(0, ragged_idx - 1), tensor_list[i]
) # transpose back each element of result
def test_unbind_transpose_ragged_idx_last_dim(self, device):
for tensor_list in self._get_example_tensor_lists():
nt = torch.nested.nested_tensor(
tensor_list, layout=torch.jagged, device=device
).transpose(1, -1) # set ragged_idx = last dimension
out = nt.unbind()
self.assertEqual(len(out), len(tensor_list))
for i, t in enumerate(out):
self.assertEqual(
t.transpose(0, -1), tensor_list[i]
) # transpose back each element of result
def test_unbind_lengths(self, device):
values = torch.randn(16, 128, device=device)
offsets = torch.tensor([0, 8, 12, 13, 16], device=device)
lengths = torch.tensor([6, 2, 1, 2], device=device)
nt = torch.nested.nested_tensor_from_jagged(
values, offsets=offsets, lengths=lengths
) # 3D nested tensor
tensor_list = []
for i in range(offsets.shape[0] - 1):
tensor_list.append(values[offsets[i] : (offsets[i] + lengths[i])])
out = nt.unbind()
self.assertEqual(len(out), len(tensor_list))
for i, t in enumerate(out):
self.assertEqual(t, tensor_list[i])
def test_unbind_lengths_ragged_idx_1(self, device):
values = torch.randn(16, 8, 128, device=device)
offsets = torch.tensor([0, 8, 12, 13, 16], device=device)
lengths = torch.tensor([6, 2, 1, 2], device=device)
ragged_idx = 1
nt = torch.nested._internal.nested_tensor.NestedTensor(
values, offsets=offsets, lengths=lengths, _ragged_idx=ragged_idx
) # 4D nested tensor
tensor_list = []
for i in range(offsets.shape[0] - 1):
tensor_list.append(values[offsets[i] : (offsets[i] + lengths[i]), :, :])
out = nt.unbind()
self.assertEqual(len(out), len(tensor_list))
for i, t in enumerate(out):
self.assertEqual(t, tensor_list[i])
def test_unbind_lengths_ragged_idx_equals_2_bad_dim(self, device):
values = torch.randn(16, 8, 128, device=device)
offsets = torch.tensor([0, 8, 12, 13, 16], device=device)
lengths = torch.tensor([6, 2, 1, 2], device=device)
ragged_idx = 2
nt = torch.nested._internal.nested_tensor.NestedTensor(
values, offsets=offsets, lengths=lengths, _ragged_idx=ragged_idx
) # 4D nested tensor
self.assertRaisesRegex(
RuntimeError,
r"unbind\(\): nested tensor offsets and lengths.*",
lambda: nt.unbind(),
)
def test_unbind_lengths_ragged_idx_2(self, device):
values = torch.randn(16, 8, 128, device=device)
offsets = torch.tensor([0, 2, 4, 8], device=device)
lengths = torch.tensor([2, 1, 3], device=device)
ragged_idx = 2
nt = torch.nested._internal.nested_tensor.NestedTensor(
values, offsets=offsets, lengths=lengths, _ragged_idx=ragged_idx
) # 4D nested tensor
tensor_list = []
for i in range(offsets.shape[0] - 1):
tensor_list.append(values[:, offsets[i] : (offsets[i] + lengths[i]), :])
out = nt.unbind()
self.assertEqual(len(out), len(tensor_list))
for i, t in enumerate(out):
self.assertEqual(t, tensor_list[i])
def test_unbind_lengths_ragged_idx_3(self, device):
values = torch.randn(16, 8, 128, device=device)
offsets = torch.tensor([0, 100, 128], device=device)
lengths = torch.tensor([50, 28], device=device)
ragged_idx = 3
nt = torch.nested._internal.nested_tensor.NestedTensor(
values, offsets=offsets, lengths=lengths, _ragged_idx=ragged_idx
) # 4D nested tensor
tensor_list = []
for i in range(offsets.shape[0] - 1):
tensor_list.append(values[:, :, offsets[i] : (offsets[i] + lengths[i])])
out = nt.unbind()
self.assertEqual(len(out), len(tensor_list))
for i, t in enumerate(out):
self.assertEqual(t, tensor_list[i])
@skipIfTorchDynamo(
"TorchDynamo raises an error for ragged_idx == 0 earlier than Torch"
)
def test_unbind_lengths_ragged_idx_0(self, device):
values = torch.randn(16, 8, 128, device=device)
offsets = torch.tensor([0, 100, 128], device=device)
lengths = torch.tensor([50, 28], device=device)
ragged_idx = 0
nt = torch.nested._internal.nested_tensor.NestedTensor(
values, offsets=offsets, lengths=lengths, _ragged_idx=ragged_idx
) # 4D nested tensor
tensor_list = []
for i in range(offsets.shape[0] - 1):
tensor_list.append(values[:, :, offsets[i] : (offsets[i] + lengths[i])])
self.assertRaisesRegex(
RuntimeError,
r"unbind\(\): nested tensor.*out of bounds",
lambda: nt.unbind(),
)
def test_narrow(self, device):
starts = torch.tensor([0, 1, 2, 3, 4], device=device, dtype=torch.int64)
lengths = torch.tensor([3, 2, 2, 1, 5], device=device, dtype=torch.int64)
buffer = (
torch.arange(0, 10, device=device, dtype=torch.int64)
.unsqueeze(0)
.expand(5, -1)
.clone()
.detach()
)
nt = torch.nested.narrow(buffer, 1, starts, lengths, layout=torch.jagged)
self.assertTrue(nt._is_view() and nt._base is buffer)
# TODO: Use this approach when unbind is functional
# unbinded_nt = nt.unbind()
# for i in range(starts.shape[0]):
# self.assertEqual(torch.arange(starts[i], starts[i] + lengths[i], device=device, dtype=torch.int64), unbinded_nt[i])
for i in range(starts.shape[0]):
self.assertEqual(
torch.arange(
starts[i], starts[i] + lengths[i], device=device, dtype=torch.int64
),
nt.values()[nt.offsets()[i] : (nt.offsets()[i] + nt.lengths()[i])],
)
def test_njt_cat(self, device):
offsets = torch.tensor([0, 2, 3], device=device, dtype=torch.int64)
values_1 = torch.randn(
3, 2, dtype=torch.float64, device=device, requires_grad=True
)
values_2 = torch.randn(
3, 4, dtype=torch.float64, device=device, requires_grad=True
)
def grad_test_func(values_1, values_2, offsets):
nt_1 = torch.nested.nested_tensor_from_jagged(values_1, offsets)
nt_2 = torch.nested.nested_tensor_from_jagged(values_2, offsets)
nt_3 = torch.cat([nt_1, nt_2], dim=-1)
return nt_3.values()
assert gradcheck(
grad_test_func,
inputs=(values_1, values_2, offsets),
check_batched_grad=False,
)
def test_is_contiguous(self, device):
a = torch.randn(2, 3, requires_grad=True, dtype=torch.float64, device=device)
b = torch.randn(3, 3, requires_grad=True, dtype=torch.float64, device=device)
c = torch.randn(4, 3, requires_grad=True, dtype=torch.float64, device=device)
nt_contiguous = torch.nested.as_nested_tensor([a, b, c], layout=torch.jagged)
starts_nc = torch.tensor([0, 1, 2, 3, 4], device=device, dtype=torch.int64)
lengths_nc = torch.tensor([3, 2, 2, 1, 5], device=device, dtype=torch.int64)
narrow_base = (
torch.arange(0, 10, device=device, dtype=torch.int64)
.unsqueeze(0)
.expand(5, -1)
.clone()
)
nt_noncontiguous = torch.nested.narrow(
narrow_base, 1, starts_nc, lengths_nc, layout=torch.jagged
)
starts_c = torch.tensor([1, 0, 0, 0, 0], device=device, dtype=torch.int64)
lengths_c = torch.tensor([9, 10, 10, 10, 8], device=device, dtype=torch.int64)
nt_contiguous_narrow = torch.nested.narrow(
narrow_base, 1, starts_c, lengths_c, layout=torch.jagged
)
# Test contiguous case
assert nt_contiguous.is_contiguous()
# Test narrow case
assert not nt_noncontiguous.is_contiguous()
assert nt_contiguous_narrow.is_contiguous()
# Test querying by memory_format
self.assertTrue(
nt_contiguous.is_contiguous(memory_format=torch.contiguous_format)
)
self.assertTrue(
not nt_noncontiguous.is_contiguous(memory_format=torch.contiguous_format)
)
self.assertTrue(
nt_contiguous_narrow.is_contiguous(memory_format=torch.contiguous_format)
)
def test_layout_under_torch_dispatch_mode(self):
from torch.testing._internal.logging_tensor import (
capture_logs_with_logging_tensor_mode,
)
nt = random_nt_from_dims(
[2, None, 3], torch.device("cpu"), torch.float32, layout=torch.jagged
)
with capture_logs_with_logging_tensor_mode():
self.assertEqual(nt.layout, torch.jagged)
@skipIfTorchDynamo("Not a suitable test for TorchDynamo")
@parametrize(
"func", [torch.empty_like, torch.randn_like], name_fn=lambda f: f.__name__
)
def test_like_shape(self, func):
nt = random_nt_from_dims(
[2, None, 3], torch.device("cpu"), torch.float32, layout=torch.jagged
)
nt_like = func(nt)
for nt_ub in nt_like.unbind():
t_like = func(nt_ub)
self.assertEqual(nt_ub.shape, t_like.shape)
@skipIfTorchDynamo("Not a suitable test for TorchDynamo")
@parametrize(
"func",
[
torch.empty_like,
torch.full_like,
torch.ones_like,
torch.rand_like,
torch.randint_like,
torch.randn_like,
torch.zeros_like,
],
name_fn=lambda f: f.__name__,
)
def test_like_value(self, func, device):
dtype = torch.float32 if func is not torch.randint_like else torch.int32
for nt in _sample_njts(device=device, dtype=dtype):
extra_kwarg_sets = [{}]
if func is torch.full_like:
extra_kwarg_sets = [{"fill_value": 4.2}]
elif func is torch.randint_like:
extra_kwarg_sets = [{"high": 5}, {"low": 4, "high": 9}]
# only test changing dtype / device from CUDA -> CPU because CUDA might not be
# available when running this test for CPU
change_dtype_device_settings = (
[False, True] if "cuda" in device else [False]
)
for change_dtype_device in change_dtype_device_settings:
if change_dtype_device:
new_dtype = (
torch.float64 if func is not torch.randint_like else torch.int64
)
new_device = "cpu" if "cuda" in device else device
new_layout = torch.strided
for extra_kwargs in extra_kwarg_sets:
extra_kwargs.update(
{
"dtype": new_dtype,
"device": new_device,
"layout": new_layout,
}
)
for extra_kwargs in extra_kwarg_sets:
nt_like = func(nt, **extra_kwargs)
self.assertEqual(nt.shape, nt_like.shape)
if change_dtype_device:
self.assertNotEqual(nt.device, nt_like.device)
self.assertNotEqual(nt.device, nt_like.dtype)
# layout should be ignored since only torch.jagged is supported
self.assertEqual(torch.jagged, nt_like.layout)
else:
self.assertEqual(nt.device, nt_like.device)
self.assertEqual(nt.dtype, nt_like.dtype)
self.assertEqual(nt.layout, nt_like.layout)
self.assertEqual(nt.layout, torch.jagged)
# don't bother trying to compare random or empty values
if func not in [
torch.empty_like,
torch.rand_like,
torch.randn_like,
torch.randint_like,
]:
for nt_ub in nt_like.unbind():
t_like = func(nt_ub, **extra_kwargs)
self.assertEqual(nt_ub, t_like)
def test_noncontiguous_pointwise(self, device):
a = torch.randn(2, 3, 4, requires_grad=True, dtype=torch.float64, device=device)
b = torch.randn(3, 3, 4, requires_grad=True, dtype=torch.float64, device=device)
c = torch.randn(4, 3, 4, requires_grad=True, dtype=torch.float64, device=device)
nt = torch.nested.nested_tensor([a, b, c], layout=torch.jagged)
# transpose ragged dim
transposed = nt.transpose(1, 2)
self.assertFalse(transposed.is_contiguous())
clone = transposed.clone()
def check_nt_equality(x, y):
self.assertEqual(x.values(), y.values())
self.assertEqual(x.offsets(), y.offsets())
self.assertEqual(x._ragged_idx, y._ragged_idx)
self.assertEqual(x.shape, y.shape)
self.assertFalse(clone.is_contiguous())
check_nt_equality(clone, transposed)
clone_contig = transposed.clone(memory_format=torch.contiguous_format)
self.assertTrue(clone_contig.is_contiguous())
check_nt_equality(clone_contig, transposed)
detached = transposed.detach()
self.assertFalse(clone.is_contiguous())
check_nt_equality(detached, transposed)
def test_permute(self, device):
nt = random_nt_from_dims(
[2, None, 3, 5], device, torch.float32, layout=torch.jagged
)
nt_shape = nt.shape
nt_inner_shape = nt.values().shape
with self.assertRaisesRegex(
ValueError,
r"permute\(\): number of dimensions in the tensor input \(4\) "
+ r"does not match the length of the desired ordering of dimensions \(3\).",
):
nt.permute(0, 2, 1)
with self.assertRaisesRegex(
ValueError, r"permute\(\): duplicate dims are not allowed."
):
nt.permute(0, 2, -2, 3)
with self.assertRaisesRegex(
ValueError, "Permute is not supported on the batch dimension for jagged NT"
):
nt.permute(1, 0, 2, 3)
nt_permute = nt.permute(0, 2, 1, -1)
self.assertEqual(
nt_permute.shape, (nt_shape[0], nt_shape[2], nt_shape[1], nt_shape[3])
)
self.assertEqual(
nt_permute.values().shape,
(nt_inner_shape[1], nt_inner_shape[0], nt_inner_shape[2]),
)
self.assertEqual(nt_permute._ragged_idx, 2)
self.assertEqual(nt_permute.permute(0, 2, 1, 3), nt)
def test_to_dtype(self, device):
nt = random_nt_from_dims(
[2, None, 3], device, torch.float32, layout=torch.jagged
)
nt_after = nt.to(torch.float64)
self.assertEqual(torch.float32, nt.dtype)
self.assertEqual(torch.float64, nt_after.dtype)
self.assertEqual(torch.float64, nt_after.values().dtype)
self.assertEqual(torch.int64, nt_after.offsets().dtype)
noncontiguous_nt = nt.transpose(1, 2)
noncontiguous_nt_after = noncontiguous_nt.to(torch.bfloat16)
self.assertEqual(torch.bfloat16, noncontiguous_nt_after.dtype)
self.assertEqual(torch.bfloat16, noncontiguous_nt_after.values().dtype)
self.assertEqual(torch.int64, noncontiguous_nt_after.offsets().dtype)
def test_to_copy(self, device):
nt = torch.nested.nested_tensor(
[
torch.randn(
i + 2, 3, 4, requires_grad=True, dtype=torch.float64, device=device
)
for i in range(3)
],
layout=torch.jagged,
)
nt_copy_dtype = torch.ops.aten._to_copy(nt, dtype=torch.float16)
self.assertEqual(torch.float16, nt_copy_dtype.dtype)
nt_t = nt.transpose(1, 2)
nt_t_copy_dtype = torch.ops.aten._to_copy(nt_t, dtype=torch.float16)
self.assertEqual(torch.float16, nt_t_copy_dtype.dtype)
def test_copy_(self, device):
offsets = torch.tensor([0, 2, 4], device=device)
a = torch.nested.nested_tensor_from_jagged(
torch.zeros(4, 3, device=device), offsets
)
b = torch.nested.nested_tensor_from_jagged(
torch.ones(4, 3, device=device), offsets
)
a.copy_(b)
torch._dynamo.disable(self.assertEqual)(a, b)
offsets_2 = torch.tensor([0, 2, 4], device=device)
c = torch.nested.nested_tensor_from_jagged(
torch.ones(4, 3, device=device), offsets_2
)
# should work even though the nested ints are different due to unbound-based copy
a.copy_(c)
# fail when tensors have different sizes
a = a.transpose(1, 2)
with self.assertRaisesRegex(
RuntimeError,
"expected compatible input and src shapes, but got",
):
a.copy_(b)
# This can't happen in the opinfo tests due to subprocess creation
@unittest.skipIf(
TEST_WITH_ROCM,
"In ROCm, kernel asserts are disabled due to performance overhead",
)
def test_index_put_error(self, device):
import subprocess
with self.subTest():
r = subprocess.call(
[
sys.executable,
"-c",
"""\
import torch
offsets = torch.tensor([0, 2, 5, 7], device='cuda')
lengths = torch.tensor([2, 2, 2], device='cuda')
indices = [
torch.tensor([0, 1, 2], device='cuda'),
torch.tensor([0, 2, 1], device='cuda'),
torch.tensor([0, 0, 0], device='cuda'),
]
a = torch.nested.nested_tensor_from_jagged(
torch.zeros(7, 3, device='cuda'), offsets, lengths
)
a[indices] = 1.0
torch.cuda.synchronize()
""",
]
)
self.assertTrue(r != 0)
@skipIfTorchDynamo("Dynamo doesn't know how to trace prof.events()")
def test_profiler_sequence_nr(self):
with torch.profiler.profile() as prof:
values = torch.randn(4, 6, requires_grad=True)
offsets = torch.tensor([0, 2, 4])
values = values * 2
l = torch.nn.Linear(6, 8)
nt = torch.nested.nested_tensor_from_jagged(values, offsets)
nt = l(nt)
val = nt.values()
loss = val.sum()
loss.backward()
fwd_seq_nrs = []
for evt in prof.events():
if (
"linear" in evt.name.lower()
and "backward" not in evt.name.lower()
and evt.sequence_nr != -1
):
fwd_seq_nrs.append(evt.sequence_nr)
bwd_seq_nrs = []
for evt in prof.events():
if (
"linear" in evt.name.lower()
and "backward" in evt.name.lower()
and "evaluate_function" not in evt.name.lower()
and evt.sequence_nr != -1
):
bwd_seq_nrs.append(evt.sequence_nr)
# There should only be one such event with a sequence number:
# the PythonTLSSnapshot event - but, note that it's not terrible if
# we end up with multiple events with the same sequence number - so we
# could relax this check if it becomes inconvenient to maintain this
# property.
self.assertEqual(len(fwd_seq_nrs), 1)
self.assertEqual(len(bwd_seq_nrs), 1)
self.assertEqual(fwd_seq_nrs[0], bwd_seq_nrs[0])
def test_is_same_size(self, device):
def get_3_tensors():
return [
torch.randn(
i + 2, 3, 4, requires_grad=True, dtype=torch.float64, device=device
)
for i in range(3)
]
nt1, offsets1 = jagged_from_list(get_3_tensors(), None)
nt2, offsets1 = jagged_from_list(get_3_tensors(), offsets1)
nt3, offsets2 = jagged_from_list(get_3_tensors(), None)
nt4, offsets2 = jagged_from_list(get_3_tensors(), offsets2)
def check_size(nt1, nt2, nt3, nt4):
self.assertTrue(torch.ops.aten.is_same_size(nt1, nt2))
self.assertTrue(torch.ops.aten.is_same_size(nt3, nt4))
self.assertFalse(torch.ops.aten.is_same_size(nt1, nt3))
check_size(nt1, nt2, nt3, nt4)
nt1_t, nt2_t, nt3_t, nt4_t = (x.transpose(1, 2) for x in (nt1, nt2, nt3, nt4))
check_size(nt1_t, nt2_t, nt3_t, nt4_t)
@skipIfTorchDynamo("compiles internally")
@unittest.skipIf(IS_WINDOWS, reason="Windows not yet supported for torch.compile")
@skipCUDAIf(not SM70OrLater, "GPU capability is < SM70")
def test_specialize_dynamic_shape(self, device):
values = torch.randn((18, 16), device=device)
offsets = torch.tensor([0, 2, 3, 6, 15, 18], device=device)
like_values = torch.randn_like(values)
# this marks values as dynamic
nt = torch.nested.nested_tensor_from_jagged(values, offsets)
def fn(values, same_size):
# here, the dynamic shape is specialized by same_size's shape
# https://github.com/pytorch/pytorch/issues/127097
# make sure this doesn't error out in torch.compile
return values + same_size
self.assertEqual(
fn(values, like_values),
torch.compile(fn)(values, like_values),
)
@skipIfTorchDynamo("compiles internally")
@unittest.skipIf(IS_WINDOWS, reason="Windows not yet supported for torch.compile")
@skipCUDAIf(not SM70OrLater, "GPU capability is < SM70")
def test_specialize_dynamic_shape_recompile(self, device):
def generate_inp(total_len):
values = torch.randn((total_len, 16), device=device)
offsets = torch.tensor([0, 2, 3, 6, 15, total_len], device=device)
like_values = torch.randn_like(values)
return values, offsets, like_values
def check_results(ref_fn, res_fn, args):
values, offsets, like_values = args
# this may add dynamic shape markings
# goal of this test is to make sure that whatever markings are there,
# we eventually stop recompiling as shape changes.
nt = torch.nested.nested_tensor_from_jagged(values, offsets)
self.assertEqual(ref_fn(values, like_values), res_fn(values, like_values))
def fn(values, same_size):
return values + same_size
compile_counter = torch._dynamo.testing.CompileCounter()
compiled_fn = torch.compile(fn, backend=compile_counter, fullgraph=True)
check_results(fn, compiled_fn, generate_inp(18))
self.assertEqual(compile_counter.frame_count, 1)
check_results(fn, compiled_fn, generate_inp(19))
# we'll probably recompile here with dynamic shapes - it's okay if not though.
frame_count_2 = compile_counter.frame_count
self.assertIn(frame_count_2, [1, 2])
# make sure that by now we've already compiled with dynamic shapes, so additional
# shapes should not trigger additional recompiles.
check_results(fn, compiled_fn, generate_inp(20))
self.assertEqual(compile_counter.frame_count, frame_count_2)
# Note 1: Math fallback doesn't work with bfloat16 on CUDA
# Note 2: ROCm doesn't support flash attention or mem_efficient attention for NT
@unittest.skipIf(
TEST_WITH_ROCM,
"ROCm doesn't support flash attention or mem_efficient attention for NT",
)
@tf32_on_and_off(0.005)
@dtypes(
*(
[torch.float16, torch.bfloat16, torch.float32]
if SM80OrLater
else [torch.float16, torch.float32]
)
)
def test_sdpa(self, device, dtype):
batch_size = 1
emb_dims = 128
n_heads = 8
head_dims = emb_dims // n_heads
sen1 = torch.randn(11, emb_dims, dtype=dtype, device=device)
sen2 = torch.randn(13, emb_dims, dtype=dtype, device=device)
query = torch.nn.Linear(
emb_dims, emb_dims, bias=False, device=device, dtype=dtype
)
key = torch.nn.Linear(
emb_dims, emb_dims, bias=False, device=device, dtype=dtype
)
value = torch.nn.Linear(
emb_dims, emb_dims, bias=False, device=device, dtype=dtype
)
# Simplest case: 1 sentence, no batching
x_d1 = sen1.unsqueeze(0)
x_nt = torch.nested.as_nested_tensor([sen1], layout=torch.jagged)
# See note below for why we detach here.
q_d1 = (
query(x_d1)
.view(batch_size, -1, n_heads, head_dims)
.detach()
.requires_grad_(True)
)
q_d1_t = q_d1.transpose(1, 2)
k_d1 = (
key(x_d1)
.view(batch_size, -1, n_heads, head_dims)
.detach()
.requires_grad_(True)
)
k_d1_t = k_d1.transpose(1, 2)
v_d1 = (
value(x_d1)
.view(batch_size, -1, n_heads, head_dims)
.detach()
.requires_grad_(True)
)
v_d1_t = v_d1.transpose(1, 2)
q_nt = (
query(x_nt)
.view(*x_nt.size()[0:2], n_heads, head_dims)
.detach()
.requires_grad_(True)
)
q_nt_t = q_nt.transpose(1, 2)
k_nt = (
key(x_nt)
.view(*x_nt.size()[0:2], n_heads, head_dims)
.detach()
.requires_grad_(True)
)
k_nt_t = k_nt.transpose(1, 2)
v_nt = (
value(x_nt)
.view(*x_nt.size()[0:2], n_heads, head_dims)
.detach()
.requires_grad_(True)
)
v_nt_t = v_nt.transpose(1, 2)
# High Precision Math Reference
q_d1_f32 = q_d1.to(torch.float32)
k_d1_f32 = k_d1.to(torch.float32)
v_d1_f32 = v_d1.to(torch.float32)
q_d1_f32_t = q_d1_f32.transpose(1, 2)
k_d1_f32_t = k_d1_f32.transpose(1, 2)
v_d1_f32_t = v_d1_f32.transpose(1, 2)
out_ref = torch.ops.aten._scaled_dot_product_attention_math(
q_d1_f32_t, k_d1_f32_t, v_d1_f32_t
)[0]
grads_ref = torch.autograd.grad(out_ref.sum(), (q_d1_f32, k_d1_f32, v_d1_f32))
# Low Precision Math Reference
out_lp_ref = torch.ops.aten._scaled_dot_product_attention_math(
q_d1_t, k_d1_t, v_d1_t
)[0]
grads_lp_ref = torch.autograd.grad(out_lp_ref.sum(), (q_d1, k_d1, v_d1))
# Compute tolerances
output_ref_atol, output_ref_rtol = get_tolerances(out_ref, out_lp_ref)
# fudge factor of 1.7 for smaller GPUs e.g., A2, A16
grad_q_ref_atol, grad_q_ref_rtol = get_tolerances(
grads_ref[0], grads_lp_ref[0], 1.7
)
grad_k_ref_atol, grad_k_ref_rtol = get_tolerances(grads_ref[1], grads_lp_ref[1])
grad_v_ref_atol, grad_v_ref_rtol = get_tolerances(grads_ref[2], grads_lp_ref[2])
grad_atols = [grad_q_ref_atol, grad_k_ref_atol, grad_v_ref_atol]
grad_rtols = [grad_q_ref_rtol, grad_k_ref_rtol, grad_v_ref_rtol]
attn_d1 = torch.nn.functional.scaled_dot_product_attention(
q_d1_t, k_d1_t, v_d1_t
).transpose(1, 2)
attn_nt = torch.nn.functional.scaled_dot_product_attention(
q_nt_t, k_nt_t, v_nt_t
).transpose(1, 2)
self.assertEqual(
attn_d1,
attn_nt.unbind()[0].unsqueeze(0),
atol=output_ref_atol,
rtol=output_ref_rtol,
)
# Simple case: 2 sentences, no extra params
x_d2 = sen2.unsqueeze(0)
x_nt = torch.nested.as_nested_tensor([sen1, sen2], layout=torch.jagged)
# NB: we make sure the leaf tensor we compute gradients for is the view-ed tensor before
# it is transposed. This is because today we cannot backward through view or unbind a
# transposed tensor.
q_d2 = (
query(x_d2)
.view(batch_size, -1, n_heads, head_dims)
.detach()
.requires_grad_(True)
)
q_d2_t = q_d2.transpose(1, 2)
k_d2 = (
key(x_d2)
.view(batch_size, -1, n_heads, head_dims)
.detach()
.requires_grad_(True)
)
k_d2_t = k_d2.transpose(1, 2)
v_d2 = (
value(x_d2)
.view(batch_size, -1, n_heads, head_dims)
.detach()
.requires_grad_(True)
)
v_d2_t = v_d2.transpose(1, 2)
q_nt = (
query(x_nt)
.view(*x_nt.size()[0:2], n_heads, head_dims)
.detach()
.requires_grad_(True)
)
q_nt_t = q_nt.transpose(1, 2)
k_nt = (
key(x_nt)
.view(*x_nt.size()[0:2], n_heads, head_dims)
.detach()
.requires_grad_(True)
)
k_nt_t = k_nt.transpose(1, 2)
v_nt = (
value(x_nt)
.view(*x_nt.size()[0:2], n_heads, head_dims)
.detach()
.requires_grad_(True)
)
v_nt_t = v_nt.transpose(1, 2)
attn_d2 = torch.nn.functional.scaled_dot_product_attention(
q_d2_t, k_d2_t, v_d2_t
).transpose(1, 2)
d1_grads = torch.autograd.grad(attn_d1.sum(), (q_d1, k_d1, v_d1))
d2_grads = torch.autograd.grad(attn_d2.sum(), (q_d2, k_d2, v_d2))
# Simple case 3: batch_size = 1, seq_len = 1
q_3 = torch.randn(1, 8, 16, dtype=dtype, device=device)
q_nt_3 = torch.nested.as_nested_tensor([q_3], layout=torch.jagged)
q_nt_3 = q_nt_3.transpose(1, 2)
attn_out = torch.nn.functional.scaled_dot_product_attention(
q_nt_3, q_nt_3, q_nt_3
)
self.assertEqual(attn_out.shape, q_nt_3.shape)
@parametrize("skip_backward", [True, False])
def check_forward_backward(skip_backward=False):
if not skip_backward:
attn_nt = torch.nn.functional.scaled_dot_product_attention(
q_nt_t, k_nt_t, v_nt_t
).transpose(1, 2)
else:
x_nt.requires_grad = False
q_nt.requires_grad = False
k_nt.requires_grad = False
v_nt.requires_grad = False
tq = q_nt_t.detach()
tk = k_nt_t.detach()
tv = v_nt_t.detach()
with torch.no_grad():
attn_nt = torch.nn.functional.scaled_dot_product_attention(
tq, tk, tv
).transpose(1, 2)
attn_nts = attn_nt.unbind()
self.assertEqual(
attn_d1,
attn_nts[0].unsqueeze(0),
atol=output_ref_atol,
rtol=output_ref_rtol,
)
self.assertEqual(
attn_d2,
attn_nts[1].unsqueeze(0),
atol=output_ref_atol,
rtol=output_ref_rtol,
)
if not skip_backward:
nt_grads = torch.autograd.grad(
attn_nt.values().sum(), (q_nt, k_nt, v_nt)
)
for nt_grad, d1_grad, d2_grad, grad_atol, grad_rtol in zip(
nt_grads, d1_grads, d2_grads, grad_atols, grad_rtols
):
unbound_nt_grads = nt_grad.unbind()
self.assertEqual(
d1_grad,
unbound_nt_grads[0].unsqueeze(0),
atol=grad_atol,
rtol=grad_rtol,
)
self.assertEqual(
d2_grad,
unbound_nt_grads[1].unsqueeze(0),
atol=grad_atol,
rtol=grad_rtol,
)
# Default
check_forward_backward()
# Test dispatcher works by calling only mem-effn and math (as they are safe for all devices)
with torch.backends.cuda.sdp_kernel(
enable_flash=False, enable_mem_efficient=True, enable_math=True
):
check_forward_backward()
# Test math fallback
with torch.backends.cuda.sdp_kernel(
enable_flash=False, enable_mem_efficient=False, enable_math=True
):
# Math fallback doesn't work with bfloat16 on CUDA because
# "group_gemm_dispatch" not implemented for 'BFloat16'
if not (str(device).startswith("cuda") and dtype == torch.bfloat16):
check_forward_backward()
check_cudnn = os.getenv("TORCH_CUDNN_SDPA_NESTED_TENSOR_ENABLED", "0") == "1"
if (
"cuda" in str(device)
and check_cudnn
and (dtype == torch.float16 or dtype == torch.bfloat16)
):
with torch.nn.attention.sdpa_kernel(
torch.nn.attention.SDPBackend.CUDNN_ATTENTION
):
check_forward_backward()
@skipIfTorchDynamo("SDPA test compiles internally")
@unittest.skipIf(IS_WINDOWS, reason="Windows not yet supported for torch.compile")
@skipCUDAIf(not SM70OrLater, "GPU capability is < SM70")
# Guarding with sqrt() doesn't work on ROCm?
@skipCUDAIfRocm
@onlyCUDA
@dtypes(
*(
[torch.float16, torch.bfloat16, torch.float32]
if SM80OrLater
else [torch.float16, torch.float32]
)
)
def test_sdpa_compile(self, device, dtype):
batch_size = 1
emb_dims = 1024
n_heads = 8
head_dims = emb_dims // n_heads
sen1 = torch.randn(11, emb_dims, dtype=dtype, device=device)
sen2 = torch.randn(13, emb_dims, dtype=dtype, device=device)
query = torch.nn.Linear(
emb_dims, emb_dims, bias=False, device=device, dtype=dtype
)
key = torch.nn.Linear(
emb_dims, emb_dims, bias=False, device=device, dtype=dtype
)
value = torch.nn.Linear(
emb_dims, emb_dims, bias=False, device=device, dtype=dtype
)
# Simplest case: 1 sentence, no batching
x_d1 = sen1.unsqueeze(0)
x_d2 = sen2.unsqueeze(0)
x_nt = torch.nested.as_nested_tensor([sen1, sen2], layout=torch.jagged)
q_d1 = query(x_d1).view(batch_size, -1, n_heads, head_dims).transpose(1, 2)
k_d1 = key(x_d1).view(batch_size, -1, n_heads, head_dims).transpose(1, 2)
v_d1 = value(x_d1).view(batch_size, -1, n_heads, head_dims).transpose(1, 2)
q_d2 = query(x_d2).view(batch_size, -1, n_heads, head_dims).transpose(1, 2)
k_d2 = key(x_d2).view(batch_size, -1, n_heads, head_dims).transpose(1, 2)
v_d2 = value(x_d2).view(batch_size, -1, n_heads, head_dims).transpose(1, 2)
q_nt = (
query(x_nt)
.view(*x_nt.size()[0:2], n_heads, head_dims)
.detach()
.transpose(1, 2)
)
k_nt = (
key(x_nt)
.view(*x_nt.size()[0:2], n_heads, head_dims)
.detach()
.transpose(1, 2)
)
v_nt = (
value(x_nt)
.view(*x_nt.size()[0:2], n_heads, head_dims)
.detach()
.transpose(1, 2)
)
# High Precision Math Reference
q_d1_f32 = q_d1.to(torch.float32)
k_d1_f32 = k_d1.to(torch.float32)
v_d1_f32 = v_d1.to(torch.float32)
out_ref = torch.ops.aten._scaled_dot_product_attention_math(
q_d1_f32, k_d1_f32, v_d1_f32
)[0]
# Low Precision Math Reference
out_lp_ref = torch.ops.aten._scaled_dot_product_attention_math(
q_d1, k_d1, v_d1
)[0]
output_ref_atol, output_ref_rtol = get_tolerances(
out_ref, out_lp_ref, fudge_factor=2
)
attn_d1 = torch.nn.functional.scaled_dot_product_attention(
q_d1, k_d1, v_d1
).transpose(1, 2)
attn_d2 = torch.nn.functional.scaled_dot_product_attention(
q_d2, k_d2, v_d2
).transpose(1, 2)
compiled_sdpa = torch.compile(torch.nn.functional.scaled_dot_product_attention)
attn_nt = compiled_sdpa(q_nt, k_nt, v_nt).transpose(1, 2)
attn_nts = attn_nt.unbind()
self.assertEqual(
attn_d1,
attn_nts[0].unsqueeze(0),
atol=output_ref_atol,
rtol=output_ref_rtol,
)
self.assertEqual(
attn_d2,
attn_nts[1].unsqueeze(0),
atol=output_ref_atol,
rtol=output_ref_rtol,
)
@dtypes(torch.float32, torch.double, torch.half)
def test_sdpa_with_constant_sequence_length(self, device, dtype):
# shape (B, P*, S, D)
# B: batch size
# P*: ragged number of prompts
# S: (constant) sequence length
# D: embedding size
query = random_nt_from_dims(
[4, None, 8, 10],
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=True,
)
key = random_nt_from_similar(query)
value = random_nt_from_similar(query)
output = F.scaled_dot_product_attention(query, key, value)
self.assertTrue(isinstance(output, NestedTensor))
output.values().sum().backward()
query_dense = query.detach().clone().requires_grad_(True)
# should be equivalent to just running the buffers through
output_dense = F.scaled_dot_product_attention(
query_dense.values(), key.values(), value.values()
)
torch._dynamo.disable(self.assertEqual)(output._values, output_dense)
output_dense.sum().backward()
torch._dynamo.disable(self.assertEqual)(query.grad, query_dense.grad)
@onlyCUDA
@unittest.skipIf(
not PLATFORM_SUPPORTS_FUSED_ATTENTION,
"Platform doesn't support flash or mem-efficient attention",
)
@dtypes(
*(
[torch.float16, torch.bfloat16, torch.float32]
if SM80OrLater
else [torch.float16, torch.float32]
)
)
def test_sdpa_with_packed_in_proj(self, device, dtype):
# shape (B, *, D)
input_packed = random_nt_from_dims(
[5, None, 10], device=device, dtype=dtype, layout=torch.jagged
)
# Do input projection.
num_heads = 2
# should be multiple of 4 for efficient kernels (e.g. flash / mem-efficient)
head_dim = 8
qkv_linear = torch.nn.Linear(10, num_heads * head_dim * 3).to(
device=device, dtype=dtype
)
def in_proj(input_packed, qkv_linear=qkv_linear):
qkv_post_proj = qkv_linear(input_packed)
# these are non-contiguous to trigger _is_safe_to_get_storage_as_tensor()
q, k, v = qkv_post_proj.chunk(3, dim=-1)
q = q.unflatten(-1, [num_heads, head_dim]).transpose(-2, -3)
k = k.unflatten(-1, [num_heads, head_dim]).transpose(-2, -3)
v = v.unflatten(-1, [num_heads, head_dim]).transpose(-2, -3)
return q, k, v
q, k, v = in_proj(input_packed)
output = F.scaled_dot_product_attention(q, k, v, attn_mask=None)
# compare to individually running unbound components through
for in_component, out_component in zip(
input_packed.unbind(), output.transpose(-2, -3).unbind()
):
q, k, v = in_proj(in_component)
out = F.scaled_dot_product_attention(q, k, v).transpose(-2, -3)
# Low Precision Math Reference
out_lp_ref = torch.ops.aten._scaled_dot_product_attention_math(q, k, v)[
0
].transpose(-2, -3)
output_ref_atol, output_ref_rtol = get_tolerances(
out, out_lp_ref, fudge_factor=2
)
self.assertEqual(
out, out_component, atol=output_ref_atol, rtol=output_ref_rtol
)
@skipIfTorchDynamo("SDPA test compiles internally")
@unittest.skipIf(IS_WINDOWS, reason="Windows not yet supported for torch.compile")
@skipCUDAIf(not SM70OrLater, "GPU capability is < SM70")
# mha_varlen_fwd not supported on ROCm
@skipCUDAIfRocm
@onlyCUDA
@dtypes(
*(
[torch.float16, torch.bfloat16, torch.float32]
if SM80OrLater
else [torch.float16, torch.float32]
)
)
def test_sdpa_backwards(self, device, dtype):
values = torch.randn(9, 3, 256, requires_grad=True, device=device, dtype=dtype)
offsets = torch.tensor([0, 1, 3, 5, 9], device=device, dtype=torch.int64)
@torch.compile
def f(values, offsets):
nt = convert_jagged_to_nested_tensor(values, offsets, max_length=4)
nt = nt.transpose(-2, -3)
# purposefully graph break to trigger view replay for subclass view input
torch.tensor(1).item()
output = F.scaled_dot_product_attention(nt, nt, nt).transpose(-2, -3)
return convert_nt_to_jagged(output)
output = f(values, offsets)
output.sum().backward()
self.assertEqual(values.grad, torch.ones_like(values))
@unittest.skipIf(
not PLATFORM_SUPPORTS_FUSED_ATTENTION,
"Platform doesn't support flash or mem-efficient attention",
)
@skipCUDAIf(not SM70OrLater, "GPU capability is < SM70")
@skipCUDAIfRocm
@onlyCUDA
@skipIfTorchDynamo()
@unittest.skipIf(IS_WINDOWS, reason="Windows not yet supported for torch.compile")
def test_sdpa_autocast(self, device):
def fn_nt(values32, values16, offsets):
nt32 = convert_jagged_to_nested_tensor(values32, offsets, max_length=16)
nt16 = convert_jagged_to_nested_tensor(values16, offsets, max_length=16)
nt32 = nt32.transpose(1, 2)
nt16 = nt16.transpose(1, 2)
return F.scaled_dot_product_attention(nt32, nt16, nt32)
def fn_dense(x32, x16):
x32 = x32.view(8, 16, 4, 16).transpose(1, 2)
x16 = x16.view(8, 16, 4, 16).transpose(1, 2)
return F.scaled_dot_product_attention(x32, x16, x32)
values32 = torch.randn((8 * 16, 4, 16), device=device, dtype=torch.float32)
values16 = torch.randn((8 * 16, 4, 16), device=device, dtype=torch.float16)
offsets = torch.arange(0, 8 * 16 + 1, 16, device=device, dtype=torch.int32)
x32 = values32.clone()
x16 = values16.clone()
with torch.autocast(device_type="cuda", dtype=torch.float16):
out_dense_eager = fn_dense(x32, x16)
out_dense_compiled = torch.compile(fn_dense)(x32, x16)
out_nt_eager = fn_nt(values32, values16, offsets)
out_nt_compiled = torch.compile(fn_nt)(values32, values16, offsets)
self.assertEqual(out_dense_eager, out_dense_compiled)
self.assertEqual(
out_dense_eager.transpose(1, 2),
out_nt_eager.values().transpose(0, 1).view(8, 16, 4, 16),
)
self.assertEqual(
out_dense_eager.transpose(1, 2),
out_nt_compiled.values().transpose(0, 1).view(8, 16, 4, 16),
)
def get_values():
return tuple(
x.detach().clone().requires_grad_(True) for x in (values32, values16)
)
v32_dense_eager, v16_dense_eager = get_values()
v32_dense_compile, v16_dense_compile = get_values()
v32_nt_eager, v16_nt_eager = get_values()
v32_nt_compile, v16_nt_compile = get_values()
with torch.autocast(device_type="cuda", dtype=torch.float16):
loss_dense_eager = fn_dense(v32_dense_eager, v16_dense_eager).sum()
loss_dense_compile = torch.compile(fn_dense)(
v32_dense_compile, v16_dense_compile
).sum()
loss_nt_eager = fn_nt(v32_nt_eager, v16_nt_eager, offsets).values().sum()
loss_nt_compile = (
torch.compile(fn_nt)(v32_nt_compile, v16_nt_compile, offsets)
.values()
.sum()
)
loss_dense_eager.backward()
loss_dense_compile.backward()
loss_nt_eager.backward()
loss_nt_compile.backward()
self.assertEqual(v32_dense_eager.grad, v32_dense_compile.grad)
self.assertEqual(v32_dense_eager.grad, v32_nt_eager.grad, atol=1e-4, rtol=1e-4)
self.assertEqual(
v32_dense_eager.grad, v32_nt_compile.grad, atol=1e-4, rtol=1e-4
)
self.assertEqual(v16_dense_eager.grad, v16_dense_compile.grad)
self.assertEqual(v16_dense_eager.grad, v16_nt_eager.grad, atol=1e-5, rtol=5e-3)
self.assertEqual(
v16_dense_eager.grad, v16_nt_compile.grad, atol=1e-5, rtol=5e-3
)
@unittest.skipIf(
not PLATFORM_SUPPORTS_FUSED_ATTENTION,
"Platform doesn't support flash or mem-efficient attention",
)
@skipCUDAIf(not SM70OrLater, "GPU capability is < SM70")
@skipCUDAIfRocm
@onlyCUDA
@skipIfTorchDynamo()
def test_sdpa_flop_counter(self, device):
from torch.utils.flop_counter import FlopCounterMode
def get_flops(nt):
flop_counter = FlopCounterMode(display=False)
with flop_counter:
ret = torch.nn.functional.scaled_dot_product_attention(nt, nt, nt)
ret.values().sum().backward()
return flop_counter.get_total_flops()
values = torch.randn(
(8 * 16, 4, 16), requires_grad=True, device=device, dtype=torch.float16
)
offsets = torch.arange(0, 8 * 16 + 1, 16, device=device, dtype=torch.int32)
nt = convert_jagged_to_nested_tensor(values, offsets, max_length=16).transpose(
1, 2
)
values_meta = torch.randn(
(8 * 16, 4, 16), requires_grad=True, device="meta", dtype=torch.float16
)
offsets_meta = torch.arange(0, 8 * 16 + 1, 16, device="meta", dtype=torch.int32)
nt_meta = convert_jagged_to_nested_tensor(
values_meta, offsets_meta, max_length=16
).transpose(1, 2)
self.assertEqual(get_flops(nt), get_flops(nt_meta))
@skipIfTorchDynamo()
def test_nested_tensor_activation_checkpoint(self, device):
values = torch.randn(
9, 3, 256, requires_grad=True, device=device, dtype=torch.float32
)
lengths = torch.tensor([1, 2, 3, 3], device=device, dtype=torch.int64)
offsets = F.pad(lengths, pad=(1, 0)).cumsum(dim=0)
def fn(values, offsets):
nt = convert_jagged_to_nested_tensor(values, offsets, max_length=4)
return convert_nt_to_jagged(nt).sum()
checkpoint(fn, values, offsets, use_reentrant=False).backward()
self.assertIsNotNone(values.grad)
context_fn = partial(
create_selective_checkpoint_contexts, [torch.ops.aten.cumsum.default]
)
values.grad = None
def fn(values, lengths):
offsets = F.pad(lengths, pad=(1, 0)).cumsum(dim=0)
nt = convert_jagged_to_nested_tensor(values, offsets, max_length=4)
return convert_nt_to_jagged(nt).sum()
checkpoint(
fn, values, lengths, use_reentrant=False, context_fn=context_fn
).backward()
self.assertIsNotNone(values.grad)
# Internally-defined NT use cases are lifted to here for maximum test realism.
# TODO: Remove these when ViewNestedFromBuffer, etc. are deprecated.
@skipCUDAIfRocm # not needed
@skipIfTorchDynamo("compiles internally")
@unittest.skipIf(IS_WINDOWS, reason="Windows not yet supported for torch.compile")
@skipCUDAIf(not SM70OrLater, "GPU capability is < SM70")
@parametrize("use_legacy_api", [True, False])
@skipCPUIf(True, "SPDA Math NT fallback causes failure: see issue #133644")
@unittest.skipIf(
"RelWithAssert" in torch.__config__.show(),
"failing in debug build, see https://github.com/pytorch/pytorch/pull/165158 for context",
)
def test_dummy_mha_with_nt(self, device, use_legacy_api):
bs = 3
d1 = 2
d2 = 4
d3 = 16
n_heads = 2
d_head = d3 // n_heads
max_length_1 = 10
max_length_2 = 20
torch.manual_seed(0)
class mha(torch.nn.Module):
def __init__(self, use_legacy_api) -> None:
super().__init__()
torch.manual_seed(0)
self.linear = torch.nn.Linear(d2, d3, device=device)
self.use_legacy_api = use_legacy_api
def forward(self, query, value, offsets):
value = self.linear(value)
if self.use_legacy_api:
key = convert_jagged_to_nested_tensor_legacy(
value, offsets, max_length_1
)
value = convert_jagged_to_nested_tensor_legacy(
value, offsets, max_length_2
)
query = convert_dense_to_nested_tensor_legacy(query)
else:
key = convert_jagged_to_nested_tensor(value, offsets, max_length_1)
value = convert_jagged_to_nested_tensor(
value, offsets, max_length_2
)
query = convert_dense_to_nested_tensor(query)
q = query.view(bs, -1, n_heads, d_head).transpose(1, 2)
k = key.view(bs, -1, n_heads, d_head).transpose(1, 2)
v = value.view(bs, -1, n_heads, d_head).transpose(1, 2)
with torch.nn.attention.sdpa_kernel(
[
torch.nn.attention.SDPBackend.FLASH_ATTENTION,
torch.nn.attention.SDPBackend.EFFICIENT_ATTENTION,
]
):
attn_output = torch.nn.functional.scaled_dot_product_attention(
q,
k,
v,
attn_mask=None,
dropout_p=0.0,
is_causal=False,
)
attn_output = attn_output.transpose(1, 2)
if self.use_legacy_api:
attn_output = convert_nt_to_jagged_legacy(attn_output)
else:
attn_output = convert_nt_to_jagged(attn_output)
return attn_output, key._max_seqlen, value._max_seqlen
query = torch.rand(bs, d1, d3, device=device)
value = torch.rand(30, d2, requires_grad=True, device=device)
# total_length must > than max_length otherwise flash_attn backward will fail
offsets = torch.tensor([0, 2, 3, 30], device=device)
m = mha(use_legacy_api)
symbolic_traced: torch.fx.GraphModule = torch.fx.symbolic_trace(m)
m = torch.compile(symbolic_traced)
attn_output, cached_key_max_seqlen, cached_value_max_seqlen = m(
query, value, offsets
)
loss = attn_output.sum()
# Check that NT can be fx traced and torch.compile, and backward works
loss.backward()
# Check that value.requires_grad is not lost after tracing and compiling
value_grad = value.grad # save for comparison later
self.assertIsNotNone(value_grad)
# check that max_seqlen is cached properly
self.assertEqual(cached_key_max_seqlen, max_length_1)
self.assertEqual(cached_value_max_seqlen, max_length_2)
# check if the output is numerically equivalent with the eager mode
m_eager = mha(use_legacy_api)
value.grad = None
attn_output_eager, _, _ = m_eager(query, value, offsets)
attn_output_eager.sum().backward()
self.assertTrue(torch.allclose(attn_output_eager, attn_output))
self.assertTrue(torch.allclose(value_grad, value.grad))
# Helper function to generate random query, key, value NJTs in (B, n_heads, *, D) format.
# If noncontig_with_holes is True, the results will be non-contiguous with holes (i.e. have
# both offsets and lengths specified).
def _rand_qkv(self, device, dtype, noncontig_with_holes=False, q_and_kv_match=True):
batch_size = 8
n_heads = 8
D = 16
def _rand_nt(noncontig_with_holes=noncontig_with_holes):
sentence_lengths = [random.randint(2, 1023) for _ in range(batch_size - 1)]
total = sum(sentence_lengths)
# shape (B, *, D_total) where D_total = n_heads * D
nt = torch.nested.nested_tensor(
[
torch.randn(l, n_heads * D, device=device, dtype=dtype)
for l in sentence_lengths
],
layout=torch.jagged,
)
if noncontig_with_holes:
nt = torch.nested.nested_tensor_from_jagged(
nt._values,
nt._offsets,
# -1 to introduce holes
lengths=nt._offsets.diff() - 1,
jagged_dim=nt._ragged_idx,
min_seqlen=nt._min_seqlen,
max_seqlen=nt._max_seqlen,
)
return nt
query = _rand_nt()
if q_and_kv_match:
key = torch.randn_like(query)
value = torch.randn_like(query)
else:
key = _rand_nt()
value = torch.randn_like(key)
# shape (B, *, D_total) -> (B, n_heads, *, D)
query = (
query.unflatten(-1, [n_heads, D]).transpose(1, 2).detach().requires_grad_()
)
key = key.unflatten(-1, [n_heads, D]).transpose(1, 2).detach().requires_grad_()
value = (
value.unflatten(-1, [n_heads, D]).transpose(1, 2).detach().requires_grad_()
)
return query, key, value
@dtypes(torch.float32)
def test_apply_(self, device, dtype):
nt = random_nt_from_dims(
[5, None, 10],
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=True,
)
def f(x):
return x * 2
if device != "cpu":
with self.assertRaisesRegex(
TypeError, "apply_ is only implemented on CPU tensors"
):
nt.apply_(f)
return
before = nt._values.detach().clone()
nt.apply_(f)
expected = f(before)
self.assertEqual(expected, nt._values)
# apply_ should swap values in-place without appending to autograd graph
self.assertIsNone(nt.grad)
self.assertIsNone(nt._values.grad_fn)
@onlyCUDA
@dtypes(torch.float64, torch.float32, torch.half)
@parametrize(
"contiguity",
["noncontig_transposed", "noncontig_with_holes"],
name_fn=lambda c: c,
)
def test_noncontiguous_to(self, device, dtype, contiguity):
# Dense tensors preserve non-contiguity through to() calls (i.e. strides are
# preserved). Test for the analogous behavior for NJTs:
# 1. non-contiguous transposed
# 2. non-contiguous with holes
if contiguity == "noncontig_transposed":
nt = random_nt_from_dims(
[3, None, 5, 2],
device=device,
dtype=dtype,
layout=torch.jagged,
).transpose(-3, -2)
elif contiguity == "noncontig_with_holes":
nt = torch.nested.nested_tensor_from_jagged(
values=torch.randn(10, 3, device=device, dtype=dtype),
offsets=torch.tensor([0, 3, 7, 10], device=device, dtype=torch.int64),
# these lengths specify holes
lengths=torch.tensor([1, 2, 3], device=device, dtype=torch.int64),
)
else:
raise ValueError("invalid contiguity specified for test_noncontiguous_to()")
# test dtype conversion
dtype_conversions = {
torch.float32: torch.half,
torch.float64: torch.float32,
torch.half: torch.float32,
}
other_dtype = dtype_conversions[dtype]
nt2 = nt.to(dtype=other_dtype)
self.assertEqual(nt2.dtype, other_dtype)
self.assertEqual(nt.is_contiguous(), nt2.is_contiguous())
self.assertEqual(nt._values.is_contiguous(), nt2._values.is_contiguous())
self.assertEqual(nt.shape, nt2.shape)
# expect no change for offsets / lengths
self.assertEqual(nt._offsets, nt2._offsets)
self.assertEqual(nt._lengths, nt2._lengths)
# test device conversion
other_device = torch.device("cpu")
nt3 = nt.to(device=other_device)
self.assertEqual(nt3.device, other_device)
self.assertEqual(nt.is_contiguous(), nt3.is_contiguous())
self.assertEqual(nt._values.is_contiguous(), nt3._values.is_contiguous())
self.assertEqual(nt.shape, nt3.shape)
# expect device change for offsets / lengths
self.assertEqual(nt3._offsets.device, other_device)
if nt._lengths is not None:
self.assertEqual(nt3._lengths.device, other_device)
@dtypes(torch.float32)
def test_autograd_function_with_None_grad(self, device, dtype):
class MyFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, inp):
ctx.save_for_backward(inp)
out1 = inp + 1
out2 = inp * 2
return out1, out2
@staticmethod
def backward(ctx, grad_out1, grad_out2):
(inp,) = ctx.saved_tensors
return grad_out1 + grad_out2
f = MyFunction.apply
nt = random_nt_from_dims(
[5, None, 10],
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=True,
)
# Only use one of the autograd.Function outputs downstream so that the grad
# for the other output is None. We're testing that the engine can allocate
# correctly-shaped (NJT) zeros for the grad of the other output in this case.
(out1, _) = f(nt)
out1.backward(torch.ones_like(out1))
@dtypes(torch.float64, torch.float32, torch.half)
def test_jagged_padded_dense_conversion_kernels(self, device, dtype):
values = torch.randn(10, 5, device=device, dtype=dtype)
offsets = torch.tensor([0, 1, 3, 8, 10], device=device, dtype=torch.int64)
max_length = offsets.diff().max().item()
padding_value = 1.3
# convert jagged -> padded dense
padded = torch.ops.aten._jagged_to_padded_dense_forward(
values, [offsets], [max_length], padding_value
)
batch_size = offsets.shape[0] - 1
expected_padded_shape = (batch_size, max_length, values.shape[-1])
self.assertEqual(padded.shape, expected_padded_shape)
# convert padded dense -> jagged
total_L = values.shape[0]
output_jagged = torch.ops.aten._padded_dense_to_jagged_forward(
padded, [offsets], total_L
)
# should be equivalent to the original values
self.assertEqual(values, output_jagged)
# success case: truncate to max length as needed
trunc_max_length = max_length - 1
trunc_padded = torch.ops.aten._jagged_to_padded_dense_forward(
values, [offsets], [trunc_max_length], padding_value
)
self.assertEqual(padded[:, :trunc_max_length, :], trunc_padded)
# specific to CPU impls
if device == "cpu":
# error case: multiple offsets on cpu since CPU kernels don't support more now
with self.assertRaisesRegex(
RuntimeError, "only a single jagged dim is supported"
):
torch.ops.aten._jagged_to_padded_dense_forward(
values, [offsets, offsets], [max_length, max_length], padding_value
)
with self.assertRaisesRegex(
RuntimeError, "only a single jagged dim is supported"
):
torch.ops.aten._padded_dense_to_jagged_forward(
padded, [offsets, offsets], total_L
)
# error case: > 1D offsets
offsets2d = offsets.unsqueeze(-1)
with self.assertRaisesRegex(RuntimeError, "expected 1D offsets"):
torch.ops.aten._jagged_to_padded_dense_forward(
values, [offsets2d], [max_length], padding_value
)
with self.assertRaisesRegex(RuntimeError, "expected 1D offsets"):
torch.ops.aten._padded_dense_to_jagged_forward(
padded, [offsets2d], total_L
)
# error case: final offset != total_L
offsets_wrong = offsets.detach().clone()
offsets_wrong[-1] = total_L + 1
with self.assertRaisesRegex(
RuntimeError, "final offset should match total_L value"
):
torch.ops.aten._padded_dense_to_jagged_forward(
padded, [offsets_wrong], total_L
)
# error case: 1D padded input
padded_wrong = padded.flatten().detach().clone()
with self.assertRaisesRegex(RuntimeError, "expected padded dim >= 2"):
torch.ops.aten._padded_dense_to_jagged_forward(
padded_wrong, [offsets], total_L
)
# error case: batch item has length > max length
# max_length is 5 above; 7 here
offsets_wrong = torch.tensor(
[0, 1, 8, 9, 10], device=device, dtype=torch.int64
)
with self.assertRaisesRegex(RuntimeError, "found batch item of length"):
torch.ops.aten._padded_dense_to_jagged_forward(
padded, [offsets_wrong], total_L
)
@dtypes(torch.float32)
@skipIfTorchDynamo("Test compiles internally")
@unittest.skipIf(
sys.version_info >= (3, 12), "torch.compile is not supported on python 3.12+"
)
@unittest.skipIf(IS_WINDOWS, reason="Windows not yet supported for torch.compile")
@skipCUDAIf(not SM70OrLater, "GPU capability is < SM70")
@skipCUDAIfRocm
def test_compile_preserves_metadata_cache(self, device, dtype):
# shape (B, *, D)
nt = random_nt_from_dims(
[4, None, 3, 16],
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=True,
)
# expect min / max seqlen to be stored here
cache = dict(nt._metadata_cache)
@torch.compile
def f(nt):
q = nt.transpose(-3, -2)
output = F.scaled_dot_product_attention(q, q, q).transpose(-3, -2)
return output
output = f(nt)
output.backward(torch.ones_like(output))
self.assertEqual(output._metadata_cache, cache)
@dtypes(torch.float32)
@skipIfTorchDynamo("Test compiles internally")
@unittest.skipIf(
sys.version_info >= (3, 12), "torch.compile is not supported on python 3.12+"
)
@unittest.skipIf(IS_WINDOWS, reason="Windows not yet supported for torch.compile")
@skipCUDAIf(not SM70OrLater, "GPU capability is < SM70")
@skipCUDAIfRocm
def test_compile_with_dynamic_max_seq_len(self, device, dtype):
# shape (B, *, D)
# max seq len: 18
nt = torch.nested.nested_tensor(
[
torch.randn(2, 5),
torch.randn(3, 5),
torch.randn(18, 5),
],
layout=torch.jagged,
)
# max seq len: 19
nt2 = torch.nested.nested_tensor(
[
torch.randn(2, 5),
torch.randn(3, 5),
torch.randn(19, 5),
],
layout=torch.jagged,
)
def f(nt):
# TODO: Replace with public API when we can use @properties
return torch.ones_like(nt) * nt._get_max_seqlen()
for dynamic in [False, True, None]:
self.assertFalse(_recompiles_for_inputs(f, (nt,), (nt2,), dynamic=dynamic))
@dtypes(torch.float32)
@skipIfTorchDynamo("Test compiles internally")
@unittest.skipIf(
sys.version_info >= (3, 12), "torch.compile is not supported on python 3.12+"
)
@unittest.skipIf(IS_WINDOWS, reason="Windows not yet supported for torch.compile")
@skipCUDAIf(not SM70OrLater, "GPU capability is < SM70")
@skipCUDAIfRocm
def test_compile_with_dynamic_min_seq_len(self, device, dtype):
# shape (B, *, D)
# min seq len: 7
nt = torch.nested.nested_tensor(
[
torch.randn(7, 5),
torch.randn(8, 5),
torch.randn(9, 5),
],
layout=torch.jagged,
)
# min seq len: 8
nt2 = torch.nested.nested_tensor(
[
torch.randn(8, 5),
torch.randn(9, 5),
torch.randn(10, 5),
],
layout=torch.jagged,
)
def f(nt):
# TODO: Replace with public API when we can use @properties
return torch.ones_like(nt) * nt._get_min_seqlen()
for dynamic in [False, True, None]:
self.assertFalse(_recompiles_for_inputs(f, (nt,), (nt2,), dynamic=dynamic))
@dtypes(torch.float32)
@skipIfTorchDynamo("Test compiles internally")
@unittest.skipIf(
sys.version_info >= (3, 12), "torch.compile is not supported on python 3.12+"
)
@unittest.skipIf(IS_WINDOWS, reason="Windows not yet supported for torch.compile")
@skipCUDAIf(not SM70OrLater, "GPU capability is < SM70")
@skipCUDAIfRocm
def test_compile_with_propagated_dynamic_max_seq_len(self, device, dtype):
# shape (B, *, D)
# max seq len: 18
nt = torch.nested.nested_tensor(
[
torch.randn(2, 5),
torch.randn(3, 5),
torch.randn(18, 5),
],
layout=torch.jagged,
)
# max seq len: 19
nt2 = torch.nested.nested_tensor(
[
torch.randn(2, 5),
torch.randn(3, 5),
torch.randn(19, 5),
],
layout=torch.jagged,
)
def f(nt):
nt2 = nt.sin() + 1
# TODO: Replace with public API when we can use @properties
return torch.ones_like(nt2) * nt2._get_max_seqlen()
ref = f(nt)
output = torch.compile(f, fullgraph=True, dynamic=False)(nt)
self.assertEqual(ref, output)
for dynamic in [False, True, None]:
self.assertFalse(_recompiles_for_inputs(f, (nt,), (nt2,), dynamic=dynamic))
def test_dropout_inference_mode(self, device):
seq_len = 32
embed_dim = 128
nt = torch.nested.nested_tensor(
[
torch.randn(11, seq_len, embed_dim, device=device),
torch.randn(11, seq_len, embed_dim, device=device),
],
layout=torch.jagged,
device=device,
)
with torch.inference_mode():
torch.nn.functional.dropout(nt, p=0.05)
@dtypes(torch.float32, torch.double, torch.half)
def test_unbind_backward(self, device, dtype):
nt = torch.nested.nested_tensor(
[
torch.randn(2, 4, device=device),
torch.randn(5, 4, device=device),
torch.randn(3, 4, device=device),
],
layout=torch.jagged,
requires_grad=True,
)
a, b, c = nt.unbind()
b.sum().backward()
@torch._dynamo.disable
def check(nt):
expected_grad = torch.zeros_like(nt)
expected_grad.unbind()[1].add_(1.0)
self.assertEqual(nt.grad, expected_grad)
check(nt)
@dtypes(torch.float32, torch.double, torch.half, torch.bool)
@parametrize("nt_dim", [2, 3, 4])
@parametrize("requires_grad", [False, True])
def test_to_padded_tensor(self, device, dtype, nt_dim, requires_grad):
if dtype is torch.bool and requires_grad:
# grads not supported for bool
return
if nt_dim == 2:
post_seq_len_shape = ()
elif nt_dim == 3:
post_seq_len_shape = (10,)
elif nt_dim == 4:
post_seq_len_shape = (9, 10)
nt = torch.nested.nested_tensor(
[
(
torch.randint(
2, (n, *post_seq_len_shape), device=device, dtype=dtype
)
if dtype is torch.bool
else torch.randn(n, *post_seq_len_shape, device=device, dtype=dtype)
)
for n in range(2, 9)
],
layout=torch.jagged,
requires_grad=requires_grad,
)
PADDING_VAL = 4.2
expected_padded = nt._values.new_full((7, 8, *post_seq_len_shape), PADDING_VAL)
for i, component in enumerate(nt.unbind()):
expected_padded[i, : component.shape[0]].copy_(component)
padded = nt.to_padded_tensor(PADDING_VAL)
self.assertEqual(expected_padded, padded)
# convert padded dense -> NJT
from torch.nested._internal.nested_tensor import nested_from_padded
nt2 = nested_from_padded(padded, nt.offsets())
self.assertEqual(nt, nt2)
if requires_grad and dtype is not torch.bool:
# ensure gradients flow through conversions
nt2.backward(torch.ones_like(nt2))
self.assertEqual(nt.grad, torch.ones_like(nt))
# blows up due to test parametrization otherwise
@torch._dynamo.utils.disable_cache_limit()
@skipIfTorchDynamo("SDPA test compiles internally")
@unittest.skipIf(IS_WINDOWS, reason="Windows not yet supported for torch.compile")
@skipCUDAIf(not SM70OrLater, "GPU capability is < SM70")
@skipCUDAIfRocm
@dtypes(torch.float32, torch.double, torch.half)
@parametrize("nt_dim", [2, 3, 4])
@parametrize("requires_grad", [False, True])
def test_to_padded_tensor_compile(self, device, dtype, nt_dim, requires_grad):
if dtype is torch.bool and requires_grad:
# grads not supported for bool
return
if nt_dim == 2:
post_seq_len_shape = ()
elif nt_dim == 3:
post_seq_len_shape = (10,)
elif nt_dim == 4:
post_seq_len_shape = (9, 10)
nt = torch.nested.nested_tensor(
[
(
torch.randint(
2, (n, *post_seq_len_shape), device=device, dtype=dtype
)
if dtype is torch.bool
else torch.randn(n, *post_seq_len_shape, device=device, dtype=dtype)
)
for n in range(2, 9)
],
layout=torch.jagged,
requires_grad=requires_grad,
)
def f(x):
return x.sin() + 1
from torch.nested._internal.nested_tensor import nested_from_padded
@torch.compile(fullgraph=True)
def g(nt):
def _g(nt):
PADDING_VAL = 4.2
padded = nt.to_padded_tensor(PADDING_VAL)
padded = f(padded)
# NB: sum_S must be specified to use the lowering for dense -> jagged
# and get full fusion
return nested_from_padded(
padded, nt.offsets(), sum_S=nt.values().shape[0]
)
# NB: use checkpointing to force fusion
return torch.utils.checkpoint.checkpoint(_g, nt, use_reentrant=False)
expected_output = f(nt)
if requires_grad:
expected_output.backward(torch.ones_like(expected_output))
expected_grad = nt.grad.detach().clone()
nt.grad = None
from torch._inductor.utils import run_and_get_code
compiled_output, generated_code = run_and_get_code(g, nt)
if requires_grad:
compiled_output.backward(torch.ones_like(compiled_output))
compiled_grad = nt.grad.detach().clone()
self.assertEqual(compiled_grad, expected_grad, rtol=1e-3, atol=1e-3)
self.assertEqual(compiled_output, expected_output, rtol=1e-3, atol=1e-3)
# === Verify that computation fusion happens. ===
# Fallback op call -> fusion didn't happen.
fallback_op_calls_present = any(
"torch.ops.aten._padded_dense_to_jagged_forward.default("
in generated_code[i]
or "torch.ops.aten._jagged_to_padded_dense_forward.default("
in generated_code[i]
for i in range(len(generated_code))
)
# NB: Fusion isn't supported on CPU.
self.assertEqual("cuda" in device, not fallback_op_calls_present)
for i in range(len(generated_code)):
# Examine buffer construction lines in the generated code to determine
# whether fusion occurred. If fusion happens, a 3D buffer with shape
# (B, max_seqlen, D) should never be materialized.
buffer_constructions = [
line.strip()
for line in generated_code[i].split("\n")
if "empty_strided_cuda(" in line
]
buffer_dims = [
# buffer dim == number of elements in the tensor size tuple arg
len(ast.parse(t).body[0].value.args[0].elts)
for t in buffer_constructions
]
if "cuda" in device:
self.assertFalse(any(d == 3 for d in buffer_dims))
@dtypes(torch.float32)
@skipIfTorchDynamo("Test compiles internally")
@unittest.skipIf(
sys.version_info >= (3, 12), "torch.compile is not supported on python 3.12+"
)
@unittest.skipIf(IS_WINDOWS, reason="Windows not yet supported for torch.compile")
@skipCUDAIf(not SM70OrLater, "GPU capability is < SM70")
@skipCUDAIfRocm
def test_compile_padded_dense_conversion_preserves_metadata_cache(
self, device, dtype
):
# shape (B, *, D)
nt = random_nt_from_dims(
[4, None, 3, 16],
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=True,
)
# expect min / max seqlen to be stored here
cache = dict(nt._metadata_cache)
@torch.compile
def g(nt):
padded = nt.to_padded_tensor(0.3)
intermediate = padded.sin() + 1
from torch.nested._internal.nested_tensor import nested_from_padded
return nested_from_padded(
intermediate,
nt.offsets(),
min_seqlen=nt._min_seqlen,
max_seqlen=nt._max_seqlen,
sum_S=nt.values().shape[0],
)
output = g(nt)
output.backward(torch.ones_like(output))
self.assertEqual(output._metadata_cache, cache)
# See https://github.com/pytorch/pytorch/issues/128649
@dtypes(torch.float32)
def test_composite_op_in_inference_mode(self, device, dtype):
# expect view
nt = random_nt_from_dims(
[4, None, 48],
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=True,
)
with torch.inference_mode():
output = nt.reshape([4, -1, 3, 16])
self.assertEqual(output.shape, (4, nt.shape[1], 3, 16))
self.assertTrue(output._is_view())
# expect copy
nt = random_nt_from_dims(
[4, None, 3, 16],
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=True,
).transpose(-1, -2)
with torch.inference_mode():
output = nt.reshape([4, -1, 48])
self.assertEqual(output.shape, (4, nt.shape[1], 48))
self.assertFalse(output._is_view())
@dtypes(torch.float32)
def test_composite_op_with_custom_mode(self, device, dtype):
from torch.utils._python_dispatch import TorchDispatchMode
# simple passthrough TorchDispatchMode
class CustomDispatchMode(TorchDispatchMode):
def __torch_dispatch__(self, func, types, args=..., kwargs=None):
return func(*args, **kwargs)
nt = random_nt_from_dims(
[4, None, 2, 3],
device=device,
dtype=dtype,
layout=torch.jagged,
requires_grad=True,
)
with CustomDispatchMode():
res = nt.reshape(4, -1, 6)
self.assertEqual(res.shape, (4, nt.shape[1], 6))
@skipIfTorchDynamo("compiles internally")
@unittest.skipIf(IS_WINDOWS, reason="Windows not yet supported for torch.compile")
@skipCUDAIf(not SM70OrLater, "GPU capability is < SM70")
@dtypes(torch.float32)
@torch._dynamo.config.patch(capture_dynamic_output_shape_ops=True)
@torch._dynamo.config.patch(capture_scalar_outputs=True)
def test_broadcast_shapes_on_in_graph_constructed_njt(self, device, dtype):
# Tests that a guard isn't wrongly installed on a freshly-created nested int when
# broadcast_shapes() is used on NJT shapes.
# See https://github.com/pytorch/pytorch/issues/145874 for more context.
nt = torch.nested.nested_tensor(
[
torch.randn(2),
torch.randn(3),
torch.randn(4),
],
layout=torch.jagged,
device=device,
dtype=dtype,
)
values = nt._values.detach().clone()
offsets = nt._offsets.detach().clone()
@torch.compile(fullgraph=True)
def f(values, offsets):
nt = torch.nested.nested_tensor_from_jagged(values, offsets)
# NB: torch.where() utilizes broadcast_shapes() underneath
return torch.where(nt > 0.0, torch.ones_like(nt), torch.zeros_like(nt))
output = f(values, offsets)
self.assertTrue(output.is_nested)
self.assertEqual(nt.shape[:-1], output.shape[:-1])
for nt_component, output_component in zip(nt.unbind(), output.unbind()):
self.assertEqual(nt_component.shape, output_component.shape)
# The following lists specify skips and xfails for particular SampleInputs. Note that
# these are attempted to be matched from top to bottom and only one at most will
# be matched, so order matters! The guiding general principle here should be one
# xfail / skip per bug if at all possible :)
FORWARD_SKIPS_AND_XFAILS = [
# not implemented
XFailRule(
error_type=NotImplementedError,
op_match_fn=lambda device, op: op.full_name
in {
# unary
# needs log_sigmoid_forward, which returns a tuple
"nn.functional.logsigmoid",
"nn.functional.prelu",
# needs rrelu_with_noise
"nn.functional.rrelu",
# binary
"__rsub__",
"complex",
"floor_divide",
"polar",
"rsub",
# reduction
"count_nonzero",
"linalg.vector_norm",
"nansum",
"std",
"std.unbiased",
"var",
"var.unbiased",
"hash_tensor",
},
name="not_implemented",
),
# expected: torch.where() support has some limitations
# 1. condition must be an NJT
# 2. no dense tensors of higher dim than the NJT
XFailRule(
error_type=ValueError,
error_msg="expected condition to be a jagged layout NestedTensor",
op_match_fn=lambda device, op: op.full_name == "where",
sample_match_fn=lambda device, sample: not sample.kwargs["condition"].is_nested,
),
XFailRule(
error_type=ValueError,
error_msg="broadcasting nested tensors with dense tensors of equal or higher dim",
op_match_fn=lambda device, op: op.full_name == "where",
sample_match_fn=lambda device, sample: (
(
not sample.input.is_nested
and sample.input.dim() >= sample.kwargs["condition"].dim()
)
or (
not sample.kwargs["other"].is_nested
and sample.kwargs["other"].dim() >= sample.kwargs["condition"].dim()
)
),
),
# expected: masked ops don't support jagged layout
XFailRule(
error_type=ValueError,
error_msg="expects strided",
op_match_fn=lambda device, op: op.full_name
in {
"masked.amax",
"masked.amin",
"masked.argmax",
"masked.argmin",
"masked.logsumexp",
"masked.mean",
"masked.norm",
"masked.prod",
"masked.std",
"masked.sum",
"masked.var",
},
name="no_masked_jagged_support",
),
# Op doesn't support lengths being present
XFailRule(
error_type=ValueError,
error_msg="expected input to be a contiguous jagged layout NestedTensor",
op_match_fn=lambda device, op: (op.full_name == "nn.functional.linear"),
sample_match_fn=lambda device, sample: (sample.input._lengths is not None),
name="no_linear_noncontig_holes_support",
),
# nanmean sometimes hits an unimplemented nansum() path and other times hits an
# unimplemented sum() path
XFailRule(
error_type=NotImplementedError,
op_match_fn=lambda device, op: (op.full_name == "nanmean"),
sample_match_fn=lambda device, sample: (
not (
"noncontig_holes" in sample.name
and "dim" in sample.kwargs
and (
(
isinstance(sample.kwargs["dim"], int)
and sample.kwargs["dim"] == sample.input._ragged_idx
)
or (
isinstance(sample.kwargs["dim"], (tuple, list))
and sample.input._ragged_idx in sample.kwargs["dim"]
)
)
)
),
name="nansum_unimplemented",
),
# expected: reducing across the ragged dimension is not supported for non-contiguous
# nested tensors with holes
XFailRule(
error_type=RuntimeError,
error_msg=(
"reducing across the ragged dimension is not supported for non-contiguous "
"nested tensors with holes"
),
op_match_fn=lambda device, op: (
# min.reduction_with_dim and max.reduction_with_dim aren't associated with
# ReductionOpInfo entries sadly even though they're reductions
isinstance(op, ReductionOpInfo) or "reduction_with_dim" in op.full_name
),
sample_match_fn=lambda device, sample: (
"noncontig_holes" in sample.name
and "dim" in sample.kwargs
and (
(
isinstance(sample.kwargs["dim"], int)
and sample.kwargs["dim"] == sample.input._ragged_idx
)
or (
isinstance(sample.kwargs["dim"], (tuple, list))
and sample.input._ragged_idx in sample.kwargs["dim"]
)
)
),
name="ragged_dim_reduction_noncontig_holes",
),
# expected: index_put() doesn't work on non-contiguous NJTs without ragged dimension indices
XFailRule(
error_type=RuntimeError,
error_msg="If ragged dimension is not part of indices, this only works on contiguous NJTs",
op_match_fn=lambda device, op: (op.full_name == "index_put"),
sample_match_fn=lambda device, sample: (
not sample.input.is_contiguous()
and len(sample.kwargs["indices"]) - 1 < sample.input._ragged_idx
),
name="index_put_noncontig_holes_no_ragged_dim_indices",
),
# select() only supports dim=0 for non-contiguous with holes NJTs for now
XFailRule(
op_match_fn=lambda device, op: (op.full_name == "select"),
sample_match_fn=lambda device, sample: (
sample.kwargs["dim"] != 0 and "noncontig_holes" in sample.name
),
name="unsupported_select_on_non_batch_dim_with_noncontig_holes",
),
# these don't work on non-contiguous NJTs yet
XFailRule(
error_type=ValueError,
error_msg="expected self to be a contiguous jagged layout NestedTensor",
op_match_fn=lambda device, op: (
op.full_name
in {
"chunk",
"masked_select",
"narrow",
"split",
"split_with_sizes",
"squeeze",
}
),
sample_match_fn=lambda device, sample: (
sample.input._lengths is not None or sample.input._ragged_idx != 1
),
name="missing_noncontig_support",
),
# these don't work on the ragged dim yet
XFailRule(
error_type=RuntimeError,
error_msg="not supported for NestedTensor on ragged dim",
op_match_fn=lambda device, op: (
op.full_name
in {
"chunk",
"narrow",
"select",
"split",
}
),
sample_match_fn=lambda device, sample: "ragged_dim" in sample.name,
name="ragged_dim_unsupported",
),
XFailRule(
error_type=RuntimeError,
# error comes from usage of view() in the decomp
error_msg="does not support ragged_idx != 1 except when",
op_match_fn=lambda device, op: (op.full_name == "unflatten"),
sample_match_fn=lambda device, sample: "noncontig_transposed" in sample.name,
name="unflatten_ragged_dim_unsupported",
),
# these don't work on the batch dim yet
XFailRule(
error_type=RuntimeError,
error_msg="not supported for NestedTensor on dim=0",
op_match_fn=lambda device, op: (
op.full_name
in {
"narrow",
"split",
"split_with_sizes",
"unsqueeze",
}
),
sample_match_fn=lambda device, sample: "batch_dim" in sample.name,
name="batch_dim_unsupported",
),
XFailRule(
error_type=RuntimeError,
# error comes from usage of view() in the decomp
error_msg="cannot view shape",
op_match_fn=lambda device, op: (op.full_name == "unflatten"),
sample_match_fn=lambda device, sample: "batch_dim" in sample.name,
name="unflatten_batch_dim_unsupported",
),
# expected: bmm / matmul sometimes use a to_padded_tensor() fallback which isn't
# supported for non-contig NJTs with holes
XFailRule(
error_type=RuntimeError,
error_msg="not supported for nested tensors with holes",
op_match_fn=lambda device, op: (op.full_name in {"bmm", "matmul"}),
sample_match_fn=lambda device, sample: (
"noncontig_holes" in sample.name
# "other" is the name for the matmul arg and "mat2" is the name for the bmm arg
and sample.input.dim()
== sample.kwargs.get("other", sample.kwargs.get("mat2")).dim()
),
name="mm_noncontig_holes",
),
# some jiterator op failures due to unsupported jagged layout
XFailRule(
error_type=RuntimeError,
error_msg="unsupported tensor layout",
op_match_fn=lambda device, op: op.full_name
in {
"jiterator_binary",
"jiterator_binary_return_by_ref",
"jiterator_unary",
},
name="no_jiterator_jagged_support",
),
# Bug when broadcasting a binary op with non-contiguous with holes NJT + dense
# tensor with 1 in ragged dim.
XFailRule(
error_type=RuntimeError,
error_msg="cannot call binary pointwise function .* with inputs of shapes",
op_match_fn=lambda device, op: (isinstance(op, BinaryUfuncInfo)),
sample_match_fn=lambda device, sample: (
"noncontig_holes" in sample.name
and "broadcasting 1 over ragged" in sample.name
),
name="binary_noncontig_holes_broadcasting_1_over_ragged",
),
]
BACKWARD_SKIPS_AND_XFAILS = [
# segfaults, so skip. It's trying to use the NST logic for NJT
SkipRule(
op_match_fn=lambda device, op: op.full_name == "split_with_sizes",
name="split_with_sizes_backward_segfault",
),
*FORWARD_SKIPS_AND_XFAILS,
# Backwards is generally broken for non-contiguous NJTs with holes. Rather than
# determine the exceptions in detail, just skip for now. Fix is to ensure
# that summing over gradients during backwards after broadcasting takes into
# account holes / lengths.
SkipRule(
op_match_fn=lambda device, op: (
isinstance(op, BinaryUfuncInfo)
or op.full_name in {"mean", "where", "unsqueeze"}
),
sample_match_fn=lambda device, sample: ("noncontig_holes" in sample.name),
name="broken_noncontig_holes_backward",
),
# mean(): need to examine backwards formula
XFailRule(
error_type=RuntimeError,
error_msg="SymIntArrayRef expected to contain only concrete integers",
op_match_fn=lambda device, op: (op.full_name in {"mean"}),
sample_match_fn=lambda device, sample: (
"full reduction" not in sample.name
and "normal dim reduction" not in sample.name
),
name="broken_mean_backward",
),
# RuntimeError: expand(): cannot expand shape (3, 3, 1, j44) -> [3, 3, 7, j44]
# with noncontig transposed inputs to mean()
XFailRule(
error_type=RuntimeError,
error_msg="cannot expand shape",
op_match_fn=lambda device, op: (op.full_name == "mean"),
sample_match_fn=lambda device, sample: (
"normal dim reduction" in sample.name
and "noncontig_transposed" in sample.name
),
name="broken_mean_backward2",
),
# unsqueeze() backward tries to call squeeze with noncontig transposed,
# but that's not supported
XFailRule(
error_type=ValueError,
error_msg="expected self to be a contiguous jagged layout NestedTensor",
op_match_fn=lambda device, op: (op.full_name == "unsqueeze"),
sample_match_fn=lambda device, sample: (
"noncontig_transposed" in sample.name or "ragged_dim" in sample.name
),
name="broken_unsqueeze_backward",
),
# RuntimeError: view(): cannot view shape (3, j62, 1, 7, 3) as [3, j58, 7, 3]
# with unflatten()
XFailRule(
error_type=RuntimeError,
error_msg="cannot view shape",
op_match_fn=lambda device, op: (op.full_name in {"unflatten"}),
sample_match_fn=lambda device, sample: ("noncontig_holes" in sample.name),
name="broken_unflatten_backward",
),
# sum() backward is not implemented for non-full reductions
XFailRule(
error_type=NotImplementedError,
error_msg="aten._nested_sum_backward.default",
op_match_fn=lambda device, op: (op.full_name == "sum"),
sample_match_fn=lambda device, sample: ("full reduction" not in sample.name),
name="broken_sum_backward",
),
# squeeze(): invalid gradient shape; need to check formula
XFailRule(
error_type=RuntimeError,
error_msg="returned an invalid gradient at index 0",
op_match_fn=lambda device, op: (op.full_name == "squeeze"),
sample_match_fn=lambda device, sample: (
sample.name == "5D_contig_with_seqlen_cache: normal_dim"
and sample.kwargs["dim"] == 3
),
name="broken_squeeze_backward",
),
# sgn() / masked_select(): backwards formulas don't work at all
XFailRule(
error_type=RuntimeError,
error_msg="NestedTensor does not support directly calling torch.ops.aten.size",
op_match_fn=lambda device, op: (op.full_name in {"sgn", "masked_select"}),
name="broken_sgn_masked_select_backward",
),
# select(): grad_output is an NJT for non-batch-dim operation
XFailRule(
error_type=ValueError,
error_msg="expected grad_output to be a tensor",
op_match_fn=lambda device, op: (op.full_name == "select"),
sample_match_fn=lambda device, sample: ("batch_dim" not in sample.name),
name="broken_select_backward",
),
# prod(): completely broken in every way
XFailRule(
op_match_fn=lambda device, op: (op.full_name == "prod"),
name="broken_prod_backward",
),
# pow() / float_power(): use where() underneath; broken for (NT, T) broadcasting cases
XFailRule(
error_type=ValueError,
error_msg="expected condition to be a jagged layout NestedTensor",
op_match_fn=lambda device, op: (op.full_name in {"pow", "float_power"}),
sample_match_fn=lambda device, sample: ("(NT, T)" in sample.name),
name="broken_pow_backward",
),
# __rpow__() backward is also broken, but for the reverse (T, NT) broadcasting cases
XFailRule(
error_type=ValueError,
error_msg="expected condition to be a jagged layout NestedTensor",
op_match_fn=lambda device, op: (op.full_name == "__rpow__"),
sample_match_fn=lambda device, sample: ("(T, NT)" in sample.name),
name="broken_rpow_backward",
),
# linear(): some formula problem when bias is used; seems to be platform-specific
# (fails locally but not in CI)
SkipRule(
# result2.use_count() <= 1 INTERNAL ASSERT FAILED
op_match_fn=lambda device, op: (op.full_name == "nn.functional.linear"),
sample_match_fn=lambda device, sample: ("with bias" in sample.name),
name="broken_linear_backward",
),
# narrow(): unimplemented backward
XFailRule(
error_type=RuntimeError,
error_msg="derivative for aten::narrow is not implemented",
op_match_fn=lambda device, op: (op.full_name == "narrow"),
name="broken_narrow_backward",
),
# min / max: need factory function support for ragged dim reductions
# where the output is dense but sizes still contain a nested int
XFailRule(
error_type=RuntimeError,
error_msg="SymIntArrayRef expected to contain only concrete integers",
op_match_fn=lambda device, op: (
op.full_name in {"max.reduction_with_dim", "min.reduction_with_dim"}
),
sample_match_fn=lambda device, sample: ("ragged dim" in sample.name),
name="broken_min_max_reduction_with_dim_backward_on_ragged_dim",
),
# copysign(): formula is broken for (T, NT) broadcasting
XFailRule(
error_type=RuntimeError,
error_msg="SymIntArrayRef expected to contain only concrete integers",
op_match_fn=lambda device, op: (op.full_name == "copysign"),
sample_match_fn=lambda device, sample: ("(T, NT)" in sample.name),
name="broken_copysign_backward",
),
# amin() / amax(): broken in a host of ways I don't think it's a good use of time
# to try to sift through
SkipRule(
op_match_fn=lambda device, op: (op.full_name in {"amin", "amax"}),
name="broken_amin_amax_backward",
),
XFailRule(
error_type=RuntimeError,
error_msg="reducing across the ragged dimension is not supported for non-contiguous",
op_match_fn=lambda device, op: (
isinstance(op, BinaryUfuncInfo)
# doesn't happen for these ops for some reason
and op.full_name
not in {"copysign", "max.binary", "maximum", "min.binary", "minimum"}
),
sample_match_fn=lambda device, sample: (
"(NT, T) broadcasting all 1s" in sample.name
and "noncontig_holes" in sample.name
),
name="binary_noncontig_holes_ragged_dim_reduction",
),
XFailRule(
error_type=RuntimeError,
error_msg="reducing across the ragged dimension is not supported for non-contiguous",
op_match_fn=lambda device, op: (op.full_name == "nn.functional.rms_norm"),
sample_match_fn=lambda device, sample: (sample.input._lengths is not None),
name="rms_norm_noncontig_holes_ragged_dim_reduction",
),
# expected: autodiff on complex dtype is not supported
XFailRule(
error_type=RuntimeError,
error_msg=(
"_nested_view_from_jagged does not support automatic differentiation "
"for outputs with complex dtype"
),
op_match_fn=lambda device, op: (op.full_name in {"cdouble", "cfloat", "chalf"}),
name="no_complex_autodiff",
),
# Bug: need to use the correct nested int in the return shape
XFailRule(
error_type=RuntimeError,
error_msg="Function CloneBackward0 returned an invalid gradient",
op_match_fn=lambda device, op: (op.full_name == "clone"),
sample_match_fn=lambda device, sample: (
sample.kwargs.get("memory_format", None) == torch.contiguous_format
),
name="clone_wrong_nested_int_for_gradient",
),
# some min / max ops use masked_fill_ underneath sometimes, which isn't implemented
XFailRule(
error_type=NotImplementedError,
error_msg="aten.masked_fill_.Scalar",
op_match_fn=lambda device, op: (
op.full_name
in {"max.binary", "min.binary", "minimum", "maximum", "copysign"}
),
name="unimplemented_masked_fill",
),
]
COMPILE_FORWARD_SKIPS_AND_XFAILS = [
*FORWARD_SKIPS_AND_XFAILS,
# Bug: cross-device conversions with to() result in new nested ints within compile only
XFailRule(
error_type=AssertionError,
error_msg="The values for attribute 'shape' do not match",
op_match_fn=lambda device, op: (op.full_name == "to"),
sample_match_fn=lambda device, sample: ("-> cpu" in sample.name),
name="cross_device_transfer_wrong_nested_int_in_compile",
),
# clone() -> preserve format on an non-contiguous NJT with holes currently uses
# unbind(), leading to data-dependent expression. Should be fixed via torch._check()
XFailRule(
error_type=torch._dynamo.exc.Unsupported,
# Ne(u1, u0) (unhinted: Ne(u1, u0)). (Size-like symbols: u1, u0)
error_msg="Could not guard on data-dependent expression",
op_match_fn=lambda device, op: (op.full_name == "clone"),
sample_match_fn=lambda device, sample: (
"noncontig_holes" in sample.name
and sample.kwargs.get("memory_format", None) == torch.contiguous_format
),
name="clone_unbind_data_dependency",
),
# chunk(): broken in several ways on the batch dim; revisit after similar
# data-dependency issues are handled for narrow()
SkipRule(
op_match_fn=lambda device, op: (op.full_name == "chunk"),
sample_match_fn=lambda device, sample: ("batch_dim" in sample.name),
name="broken_chunk_compile_backward_on_batch_dim",
),
# select on batch dim currently uses unbind(), leading to data-dependent error in
# torch.compile that needs to be addressed via torch._check()
XFailRule(
error_type=torch._dynamo.exc.InternalTorchDynamoError,
error_msg="Pending unbacked symbols",
op_match_fn=lambda device, op: (op.full_name == "select"),
sample_match_fn=lambda device, sample: ("batch_dim" in sample.name),
name="broken_select_backward_unbacked",
),
]
COMPILE_BACKWARD_SKIPS_AND_XFAILS = [
# non-contiguous with holes inputs + torch.compile doesn't work great today; need
# torch._check() statements. Skip these and handle them later.
SkipRule(
op_match_fn=lambda device, op: True,
sample_match_fn=lambda device, sample: ("noncontig_holes" in sample.name),
name="noncontig_holes_data_dependency",
),
# mean(): weird bug
XFailRule(
error_type=torch._dynamo.exc.BackendCompilerFailed,
error_msg="'NestedIntNode' object has no attribute 'sub'",
op_match_fn=lambda device, op: (op.full_name == "mean"),
sample_match_fn=lambda device, sample: (
"full reduction" not in sample.name
and "normal dim reduction" not in sample.name
),
name="broken_mean_compile_backward",
),
# min() / max(): weird bug
XFailRule(
error_type=AttributeError,
error_msg="'NestedIntNode' object has no attribute 'add'",
op_match_fn=lambda device, op: (
op.full_name in {"max.reduction_with_dim", "min.reduction_with_dim"}
),
sample_match_fn=lambda device, sample: ("ragged dim" in sample.name),
name="broken_min_max_compile_backward",
),
# to() fails with data-dependent guards OR Unknown layout in record_stream_any_impl;
# need to fix with torch._check(), etc.
XFailRule(
op_match_fn=lambda device, op: (op.full_name == "to"),
sample_match_fn=lambda device, sample: ("-> cpu" in sample.name),
name="to_data_dependency",
),
# copysign(): formula is broken for (T, NT) broadcasting
XFailRule(
error_type=AttributeError,
error_msg="'NestedIntNode' object has no attribute 'add'",
op_match_fn=lambda device, op: (op.full_name == "copysign"),
sample_match_fn=lambda device, sample: ("(T, NT)" in sample.name),
name="broken_copysign_compile_backward",
),
# in compile, these complex ops use view_as_real(), which isn't implemented
XFailRule(
error_type=NotImplementedError,
error_msg="aten.view_as_real.default",
op_match_fn=lambda device, op: (op.full_name in {"cdouble", "cfloat", "chalf"}),
name="unimplemented_view_as_real",
),
*COMPILE_FORWARD_SKIPS_AND_XFAILS,
*BACKWARD_SKIPS_AND_XFAILS,
]
COMPARE_TENSOR_COMPONENT_EQUALITY = {
# masked_select is expected to output a different shape
"masked_select",
}
# OpInfo-based NJT tests. These tests utilize an NJT-specific op_db generated from the standard
# op_db. Note that certain tradeoffs were made wrt coverage vs. time spent running tests:
# * All tests run with dtype=torch.float32 only
| TestNestedTensorSubclass |
python | pypa__hatch | src/hatch/config/model.py | {
"start": 13575,
"end": 14338
} | class ____(LazilyParsedConfig):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._field_location = FIELD_TO_PARSE
@property
def location(self):
if self._field_location is FIELD_TO_PARSE:
if "location" in self.raw_data:
location = self.raw_data["location"]
if not isinstance(location, str):
self.raise_error("must be a string")
self._field_location = location
else:
self.raise_error("required field")
return self._field_location
@location.setter
def location(self, value):
self.raw_data["location"] = value
self._field_location = FIELD_TO_PARSE
| ProjectConfig |
python | numba__numba | numba/core/withcontexts.py | {
"start": 3980,
"end": 16343
} | class ____(WithContext):
"""Creates a contextmanager to be used inside jitted functions to enter
*object-mode* for using interpreter features. The body of the with-context
is lifted into a function that is compiled in *object-mode*. This
transformation process is limited and cannot process all possible
Python code. However, users can wrap complicated logic in another
Python function, which will then be executed by the interpreter.
Use this as a function that takes keyword arguments only.
The argument names must correspond to the output variables from the
with-block. Their respective values can be:
1. strings representing the expected types; i.e. ``"float32"``.
2. compile-time bound global or nonlocal variables referring to the
expected type. The variables are read at compile time.
When exiting the with-context, the output variables are converted
to the expected nopython types according to the annotation. This process
is the same as passing Python objects into arguments of a nopython
function.
Example::
import numpy as np
from numba import njit, objmode, types
def bar(x):
# This code is executed by the interpreter.
return np.asarray(list(reversed(x.tolist())))
# Output type as global variable
out_ty = types.intp[:]
@njit
def foo():
x = np.arange(5)
y = np.zeros_like(x)
with objmode(y='intp[:]', z=out_ty): # annotate return type
# this region is executed by object-mode.
y += bar(x)
z = y
return y, z
.. note:: Known limitations:
- with-block cannot use incoming list objects.
- with-block cannot use incoming function objects.
- with-block cannot ``yield``, ``break``, ``return`` or ``raise`` \
such that the execution will leave the with-block immediately.
- with-block cannot contain `with` statements.
- random number generator states do not synchronize; i.e. \
nopython-mode and object-mode uses different RNG states.
.. note:: When used outside of no-python mode, the context-manager has no
effect.
.. warning:: This feature is experimental. The supported features may
change with or without notice.
"""
is_callable = True
def _legalize_args(
self, func_ir, args, kwargs, loc, func_globals, func_closures
):
"""
Legalize arguments to the context-manager
Parameters
----------
func_ir: FunctionIR
args: tuple
Positional arguments to the with-context call as IR nodes.
kwargs: dict
Keyword arguments to the with-context call as IR nodes.
loc: numba.core.ir.Loc
Source location of the with-context call.
func_globals: dict
The globals dictionary of the calling function.
func_closures: dict
The resolved closure variables of the calling function.
"""
if args:
raise errors.CompilerError(
"objectmode context doesn't take any positional arguments",
)
typeanns = {}
def report_error(varname, msg, loc):
raise errors.CompilerError(
f"Error handling objmode argument {varname!r}. {msg}",
loc=loc,
)
for k, v in kwargs.items():
if isinstance(v, ir.Const) and isinstance(v.value, str):
typeanns[k] = sigutils._parse_signature_string(v.value)
elif isinstance(v, ir.FreeVar):
try:
v = func_closures[v.name]
except KeyError:
report_error(
varname=k,
msg=f"Freevar {v.name!r} is not defined.",
loc=loc,
)
typeanns[k] = v
elif isinstance(v, ir.Global):
try:
v = func_globals[v.name]
except KeyError:
report_error(
varname=k,
msg=f"Global {v.name!r} is not defined.",
loc=loc,
)
typeanns[k] = v
elif isinstance(v, ir.Expr) and v.op == "getattr":
try:
base_obj = func_ir.infer_constant(v.value)
typ = getattr(base_obj, v.attr)
except (errors.ConstantInferenceError, AttributeError):
report_error(
varname=k,
msg="Getattr cannot be resolved at compile-time.",
loc=loc,
)
else:
typeanns[k] = typ
else:
report_error(
varname=k,
msg=(
"The value must be a compile-time constant either as "
"a non-local variable or a getattr expression that "
"refers to a Numba type."
),
loc=loc,
)
# Legalize the types for objmode
for name, typ in typeanns.items():
self._legalize_arg_type(name, typ, loc)
return typeanns
def _legalize_arg_type(self, name, typ, loc):
"""Legalize the argument type
Parameters
----------
name: str
argument name.
typ: numba.core.types.Type
argument type.
loc: numba.core.ir.Loc
source location for error reporting.
"""
if getattr(typ, "reflected", False):
msgbuf = [
"Objmode context failed.",
f"Argument {name!r} is declared as "
f"an unsupported type: {typ}.",
"Reflected types are not supported.",
]
raise errors.CompilerError(" ".join(msgbuf), loc=loc)
def mutate_with_body(
self,
func_ir,
blocks,
blk_start,
blk_end,
body_blocks,
dispatcher_factory,
extra,
):
cellnames = func_ir.func_id.func.__code__.co_freevars
closures = func_ir.func_id.func.__closure__
func_globals = func_ir.func_id.func.__globals__
if closures is not None:
# Resolve free variables
func_closures = {}
for cellname, closure in zip(cellnames, closures):
try:
cellval = closure.cell_contents
except ValueError as e:
# empty cell will raise
if str(e) != "Cell is empty":
raise
else:
func_closures[cellname] = cellval
else:
# Missing closure object
func_closures = {}
args = extra["args"] if extra else ()
kwargs = extra["kwargs"] if extra else {}
typeanns = self._legalize_args(
func_ir=func_ir,
args=args,
kwargs=kwargs,
loc=blocks[blk_start].loc,
func_globals=func_globals,
func_closures=func_closures,
)
vlt = func_ir.variable_lifetime
inputs, outputs = find_region_inout_vars(
blocks=blocks,
livemap=vlt.livemap,
callfrom=blk_start,
returnto=blk_end,
body_block_ids=set(body_blocks),
)
# Determine types in the output tuple
def strip_var_ver(x):
return x.split(".", 1)[0]
stripped_outs = list(map(strip_var_ver, outputs))
# Verify that only outputs are annotated
extra_annotated = set(typeanns) - set(stripped_outs)
if extra_annotated:
msg = (
"Invalid type annotation on non-outgoing variables: {}."
"Suggestion: remove annotation of the listed variables"
)
raise errors.TypingError(msg.format(extra_annotated))
# Verify that all outputs are annotated
# Note on "$cp" variable:
# ``transforms.consolidate_multi_exit_withs()`` introduces the variable
# for the control-point to determine the correct exit block. This
# variable crosses the with-region boundary. Thus, it will be consider
# an output variable leaving the lifted with-region.
typeanns["$cp"] = types.int32
not_annotated = set(stripped_outs) - set(typeanns)
if not_annotated:
msg = (
"Missing type annotation on outgoing variable(s): {0}\n\n"
"Example code: with objmode({1}='<"
"add_type_as_string_here>')\n"
)
stable_ann = sorted(not_annotated)
raise errors.TypingError(msg.format(stable_ann, stable_ann[0]))
# Get output types
outtup = types.Tuple([typeanns[v] for v in stripped_outs])
lifted_blks = {k: blocks[k] for k in body_blocks}
_mutate_with_block_callee(
lifted_blks, blk_start, blk_end, inputs, outputs
)
lifted_ir = func_ir.derive(
blocks=lifted_blks,
arg_names=tuple(inputs),
arg_count=len(inputs),
force_non_generator=True,
)
dispatcher = dispatcher_factory(
lifted_ir, objectmode=True, output_types=outtup
)
newblk = _mutate_with_block_caller(
dispatcher,
blocks,
blk_start,
blk_end,
inputs,
outputs,
)
blocks[blk_start] = newblk
_clear_blocks(blocks, body_blocks)
return dispatcher
def __call__(self, *args, **kwargs):
# No effect when used in pure-python
return self
objmode_context = _ObjModeContextType()
def _bypass_with_context(blocks, blk_start, blk_end, forwardvars):
"""Given the starting and ending block of the with-context,
replaces the head block with a new block that jumps to the end.
*blocks* is modified inplace.
"""
sblk = blocks[blk_start]
scope = sblk.scope
loc = sblk.loc
newblk = ir.Block(scope=scope, loc=loc)
for k, v in forwardvars.items():
newblk.append(
ir.Assign(
value=scope.get_exact(k), target=scope.get_exact(v), loc=loc
)
)
newblk.append(ir.Jump(target=blk_end, loc=loc))
blocks[blk_start] = newblk
def _mutate_with_block_caller(
dispatcher, blocks, blk_start, blk_end, inputs, outputs
):
"""Make a new block that calls into the lifeted with-context.
Parameters
----------
dispatcher : Dispatcher
blocks : dict[ir.Block]
blk_start, blk_end : int
labels of the starting and ending block of the context-manager.
inputs: sequence[str]
Input variable names
outputs: sequence[str]
Output variable names
"""
sblk = blocks[blk_start]
scope = sblk.scope
loc = sblk.loc
newblock = ir.Block(scope=scope, loc=loc)
ir_utils.fill_block_with_call(
newblock=newblock,
callee=dispatcher,
label_next=blk_end,
inputs=inputs,
outputs=outputs,
)
return newblock
def _mutate_with_block_callee(blocks, blk_start, blk_end, inputs, outputs):
"""Mutate *blocks* for the callee of a with-context.
Parameters
----------
blocks : dict[ir.Block]
blk_start, blk_end : int
labels of the starting and ending block of the context-manager.
inputs: sequence[str]
Input variable names
outputs: sequence[str]
Output variable names
"""
if not blocks:
raise errors.NumbaValueError("No blocks in with-context block")
head_blk = min(blocks)
temp_blk = blocks[head_blk]
scope = temp_blk.scope
loc = temp_blk.loc
blocks[blk_start] = ir_utils.fill_callee_prologue(
block=ir.Block(scope=scope, loc=loc),
inputs=inputs,
label_next=head_blk,
)
blocks[blk_end] = ir_utils.fill_callee_epilogue(
block=ir.Block(scope=scope, loc=loc),
outputs=outputs,
)
| _ObjModeContextType |
python | tornadoweb__tornado | tornado/test/httpserver_test.py | {
"start": 44597,
"end": 45625
} | class ____(AsyncHTTPTestCase):
def get_app(self):
return Application([("/", HelloWorldRequestHandler)])
def get_httpserver_options(self):
return dict(max_header_size=1024)
def test_small_headers(self):
response = self.fetch("/", headers={"X-Filler": "a" * 100})
response.rethrow()
self.assertEqual(response.body, b"Hello world")
def test_large_headers(self):
with ExpectLog(gen_log, "Unsatisfiable read", required=False):
try:
self.fetch("/", headers={"X-Filler": "a" * 1000}, raise_error=True)
self.fail("did not raise expected exception")
except HTTPError as e:
# 431 is "Request Header Fields Too Large", defined in RFC
# 6585. However, many implementations just close the
# connection in this case, resulting in a missing response.
if e.response is not None:
self.assertIn(e.response.code, (431, 599))
| MaxHeaderSizeTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/fixtures/mypy.py | {
"start": 710,
"end": 8786
} | class ____(TestBase):
__requires__ = ("no_sqlalchemy2_stubs",)
@config.fixture(scope="function")
def per_func_cachedir(self):
yield from self._cachedir()
@config.fixture(scope="class")
def cachedir(self):
yield from self._cachedir()
def _cachedir(self):
# as of mypy 0.971 i think we need to keep mypy_path empty
mypy_path = ""
with tempfile.TemporaryDirectory() as cachedir:
with open(
Path(cachedir) / "plain_mypy_config.cfg", "w"
) as config_file:
config_file.write(
f"""
[mypy]\n
show_error_codes = True\n
{mypy_path}
disable_error_code = var-annotated,no-untyped-call
[mypy-sqlalchemy.*]
ignore_errors = True
"""
)
yield cachedir
@config.fixture()
def mypy_runner(self, cachedir):
from mypy import api
def run(path, use_cachedir=None):
if use_cachedir is None:
use_cachedir = cachedir
args = [
"--strict",
"--raise-exceptions",
"--cache-dir",
use_cachedir,
"--config-file",
os.path.join(use_cachedir, "plain_mypy_config.cfg"),
]
# mypy as of 0.990 is more aggressively blocking messaging
# for paths that are in sys.path, and as pytest puts currdir,
# test/ etc in sys.path, just copy the source file to the
# tempdir we are working in so that we don't have to try to
# manipulate sys.path and/or guess what mypy is doing
filename = os.path.basename(path)
test_program = os.path.join(use_cachedir, filename)
if path != test_program:
shutil.copyfile(path, test_program)
args.append(test_program)
# I set this locally but for the suite here needs to be
# disabled
os.environ.pop("MYPY_FORCE_COLOR", None)
stdout, stderr, exitcode = api.run(args)
return stdout, stderr, exitcode
return run
@config.fixture
def mypy_typecheck_file(self, mypy_runner):
def run(path):
expected_messages = self._collect_messages(path)
stdout, stderr, exitcode = mypy_runner(path)
self._check_output(
path, expected_messages, stdout, stderr, exitcode
)
return run
@staticmethod
def file_combinations(dirname):
if os.path.isabs(dirname):
path = dirname
else:
caller_path = inspect.stack()[1].filename
path = os.path.join(os.path.dirname(caller_path), dirname)
files = list(Path(path).glob("**/*.py"))
for extra_dir in config.options.mypy_extra_test_paths:
if extra_dir and os.path.isdir(extra_dir):
files.extend((Path(extra_dir) / dirname).glob("**/*.py"))
return files
def _collect_messages(self, path):
expected_messages = []
expected_re = re.compile(r"\s*# EXPECTED(_MYPY)?(_RE)?(_TYPE)?: (.+)")
py_ver_re = re.compile(r"^#\s*PYTHON_VERSION\s?>=\s?(\d+\.\d+)")
with open(path) as file_:
current_assert_messages = []
for num, line in enumerate(file_, 1):
m = py_ver_re.match(line)
if m:
major, _, minor = m.group(1).partition(".")
if sys.version_info < (int(major), int(minor)):
config.skip_test(
"Requires python >= %s" % (m.group(1))
)
continue
m = expected_re.match(line)
if m:
is_mypy = bool(m.group(1))
is_re = bool(m.group(2))
is_type = bool(m.group(3))
expected_msg = re.sub(r"# noqa[:]? ?.*", "", m.group(4))
if is_type:
is_mypy = is_re = True
expected_msg = f'Revealed type is "{expected_msg}"'
# use_or_syntax
# https://github.com/python/mypy/blob/304997bfb85200fb521ac727ee0ce3e6085e5278/mypy/options.py#L368 # noqa: E501
expected_msg = re.sub(
r"Optional\[(.*?)\]",
lambda m: f"{m.group(1)} | None",
expected_msg,
)
current_assert_messages.append(
(is_mypy, is_re, expected_msg.strip())
)
elif current_assert_messages:
expected_messages.extend(
(num, is_mypy, is_re, expected_msg)
for (
is_mypy,
is_re,
expected_msg,
) in current_assert_messages
)
current_assert_messages[:] = []
return expected_messages
def _check_output(
self, path, expected_messages, stdout: str, stderr, exitcode
):
not_located = []
filename = os.path.basename(path)
if expected_messages:
# mypy 0.990 changed how return codes work, so don't assume a
# 1 or a 0 return code here, could be either depending on if
# errors were generated or not
output = []
raw_lines = stdout.split("\n")
while raw_lines:
e = raw_lines.pop(0)
if re.match(r".+\.py:\d+: error: .*", e):
output.append(("error", e))
elif re.match(
r".+\.py:\d+: note: +(?:Possible overload|def ).*", e
):
while raw_lines:
ol = raw_lines.pop(0)
if not re.match(r".+\.py:\d+: note: +def .*", ol):
raw_lines.insert(0, ol)
break
elif re.match(
r".+\.py:\d+: note: .*(?:perhaps|suggestion)", e, re.I
):
pass
elif re.match(r".+\.py:\d+: note: .*", e):
output.append(("note", e))
for num, is_mypy, is_re, msg in expected_messages:
msg = msg.replace("'", '"')
prefix = "[SQLAlchemy Mypy plugin] " if not is_mypy else ""
for idx, (typ, errmsg) in enumerate(output):
if is_re:
if re.match(
rf".*{filename}\:{num}\: {typ}\: {prefix}{msg}",
errmsg,
):
break
elif (
f"{filename}:{num}: {typ}: {prefix}{msg}"
in errmsg.replace("'", '"')
):
break
else:
not_located.append(msg)
continue
del output[idx]
if not_located:
missing = "\n".join(not_located)
print("Couldn't locate expected messages:", missing, sep="\n")
if output:
extra = "\n".join(msg for _, msg in output)
print("Remaining messages:", extra, sep="\n")
assert False, "expected messages not found, see stdout"
if output:
print(f"{len(output)} messages from mypy were not consumed:")
print("\n".join(msg for _, msg in output))
assert False, "errors and/or notes remain, see stdout"
else:
if exitcode != 0:
print(stdout, stderr, sep="\n")
eq_(exitcode, 0, msg=stdout)
| MypyTest |
python | tqdm__tqdm | tqdm/contrib/telegram.py | {
"start": 2815,
"end": 5008
} | class ____(tqdm_auto):
"""
Standard `tqdm.auto.tqdm` but also sends updates to a Telegram Bot.
May take a few seconds to create (`__init__`).
- create a bot <https://core.telegram.org/bots#6-botfather>
- copy its `{token}`
- add the bot to a chat and send it a message such as `/start`
- go to <https://api.telegram.org/bot`{token}`/getUpdates> to find out
the `{chat_id}`
- paste the `{token}` & `{chat_id}` below
>>> from tqdm.contrib.telegram import tqdm, trange
>>> for i in tqdm(iterable, token='{token}', chat_id='{chat_id}'):
... ...
"""
def __init__(self, *args, **kwargs):
"""
Parameters
----------
token : str, required. Telegram token
[default: ${TQDM_TELEGRAM_TOKEN}].
chat_id : str, required. Telegram chat ID
[default: ${TQDM_TELEGRAM_CHAT_ID}].
See `tqdm.auto.tqdm.__init__` for other parameters.
"""
if not kwargs.get('disable'):
kwargs = kwargs.copy()
self.tgio = TelegramIO(
kwargs.pop('token', getenv('TQDM_TELEGRAM_TOKEN')),
kwargs.pop('chat_id', getenv('TQDM_TELEGRAM_CHAT_ID')))
super().__init__(*args, **kwargs)
def display(self, **kwargs):
super().display(**kwargs)
fmt = self.format_dict
if fmt.get('bar_format', None):
fmt['bar_format'] = fmt['bar_format'].replace(
'<bar/>', '{bar:10u}').replace('{bar}', '{bar:10u}')
else:
fmt['bar_format'] = '{l_bar}{bar:10u}{r_bar}'
self.tgio.write(self.format_meter(**fmt))
def clear(self, *args, **kwargs):
super().clear(*args, **kwargs)
if not self.disable:
self.tgio.write("")
def close(self):
if self.disable:
return
super().close()
if not (self.leave or (self.leave is None and self.pos == 0)):
self.tgio.delete()
def ttgrange(*args, **kwargs):
"""Shortcut for `tqdm.contrib.telegram.tqdm(range(*args), **kwargs)`."""
return tqdm_telegram(range(*args), **kwargs)
# Aliases
tqdm = tqdm_telegram
trange = ttgrange
| tqdm_telegram |
python | scrapy__scrapy | scrapy/utils/request.py | {
"start": 3595,
"end": 3701
} | class ____(Protocol):
def fingerprint(self, request: Request) -> bytes: ...
| RequestFingerprinterProtocol |
python | lazyprogrammer__machine_learning_examples | unsupervised_class3/autoencoder_theano.py | {
"start": 427,
"end": 2942
} | class ____:
def __init__(self, D, M):
# represents a batch of training data
self.X = T.matrix('X')
# input -> hidden
self.W = theano.shared(np.random.randn(D, M) * np.sqrt(2.0 / M))
self.b = theano.shared(np.zeros(M))
# hidden -> output
self.V = theano.shared(np.random.randn(M, D) * np.sqrt(2.0 / D))
self.c = theano.shared(np.zeros(D))
# construct the reconstruction
self.Z = T.nnet.relu(self.X.dot(self.W) + self.b)
self.X_hat = T.nnet.sigmoid(self.Z.dot(self.V) + self.c)
# compute the cost
self.cost = T.sum(
T.nnet.binary_crossentropy(
output=self.X_hat,
target=self.X,
)
)
# define the updates
params = [self.W, self.b, self.V, self.c]
grads = T.grad(self.cost, params)
# rmsprop
decay = 0.9
learning_rate = 0.001
# for rmsprop
cache = [theano.shared(np.ones_like(p.get_value())) for p in params]
new_cache = [decay*c + (1-decay)*g*g for p, c, g in zip(params, cache, grads)]
updates = [
(c, new_c) for c, new_c in zip(cache, new_cache)
] + [
(p, p - learning_rate*g/T.sqrt(new_c + 1e-10)) for p, new_c, g in zip(params, new_cache, grads)
]
# now define callable functions
self.train_op = theano.function(
inputs=[self.X],
outputs=self.cost,
updates=updates
)
self.predict = theano.function(
inputs=[self.X],
outputs=self.X_hat
)
def fit(self, X, epochs=30, batch_sz=64):
costs = []
n_batches = len(X) // batch_sz
print("n_batches:", n_batches)
for i in range(epochs):
print("epoch:", i)
np.random.shuffle(X)
for j in range(n_batches):
batch = X[j*batch_sz:(j+1)*batch_sz]
c = self.train_op(batch)
c /= batch_sz # just debugging
costs.append(c)
if j % 100 == 0:
print("iter: %d, cost: %.3f" % (j, c))
plt.plot(costs)
plt.show()
def main():
X, Y = util.get_mnist()
model = Autoencoder(784, 300)
model.fit(X)
# plot reconstruction
done = False
while not done:
i = np.random.choice(len(X))
x = X[i]
im = model.predict([x]).reshape(28, 28)
plt.subplot(1,2,1)
plt.imshow(x.reshape(28, 28), cmap='gray')
plt.title("Original")
plt.subplot(1,2,2)
plt.imshow(im, cmap='gray')
plt.title("Reconstruction")
plt.show()
ans = input("Generate another?")
if ans and ans[0] in ('n' or 'N'):
done = True
if __name__ == '__main__':
main()
| Autoencoder |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-appsflyer/source_appsflyer/source.py | {
"start": 11306,
"end": 11636
} | class ____(RawDataMixin, IncrementalAppsflyerStream):
cursor_field = "install_time"
def path(
self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None
) -> str:
return f"raw-data/export/app/{self.app_id}/installs_report/v5"
| Installs |
python | PrefectHQ__prefect | src/prefect/logging/highlighters.py | {
"start": 86,
"end": 413
} | class ____(RegexHighlighter):
"""Apply style to log levels."""
base_style = "level."
highlights: list[str] = [
r"(?P<debug_level>DEBUG)",
r"(?P<info_level>INFO)",
r"(?P<warning_level>WARNING)",
r"(?P<error_level>ERROR)",
r"(?P<critical_level>CRITICAL)",
]
| LevelHighlighter |
python | google__jax | tests/source_mapper_test.py | {
"start": 4508,
"end": 5335
} | class ____(jtu.JaxTestCase):
def test_hlo_parser(self):
source_map = hlo._parse_hlo_new_format(HLO_EXAMPLE.split("\n"))
print(source_map)
self.assertLen(source_map.sources, 1)
self.assertEqual(source_map.sources[0], "<embedded module>")
mappings = source_map.mappings
constant_line_idx = -1
for i, line in enumerate(HLO_EXAMPLE.split("\n")):
if r"ROOT %constant" in line:
constant_line_idx = i
break
line_mappings = mappings[constant_line_idx]
gen_col, file_idx, src_line, _ = line_mappings[0]
self.assertEqual(
file_idx, 0
) # "<embedded module>" is the first and only used source
self.assertEqual(src_line, 152) # 153 - 1
self.assertEqual(gen_col, 2)
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| HLOParserTest |
python | ray-project__ray | python/ray/tests/accelerators/mock_dpctl_2.py | {
"start": 124,
"end": 271
} | class ____:
def __init__(self, info):
pass
@property
def name(self):
return "Intel(R) Data Center GPU Max 1100"
| SyclDevice |
python | paramiko__paramiko | tests/test_transport.py | {
"start": 38416,
"end": 38834
} | class ____(TransportTest):
_auth_handler_class = AuthOnlyHandler
def setUp(self):
# Copypasta (Transport init is load-bearing)
self.socks = LoopSocket()
self.sockc = LoopSocket()
self.sockc.link(self.socks)
# New class who dis
self.tc = ServiceRequestingTransport(self.sockc)
self.ts = ServiceRequestingTransport(self.socks)
| ServiceRequestingTransportTest |
python | PyCQA__pylint | tests/functional/r/regression_02/regression_5408.py | {
"start": 309,
"end": 360
} | class ____:
inner_class = MyInnerClass
| MySubClass |
python | pypa__pip | src/pip/_internal/distributions/base.py | {
"start": 274,
"end": 1830
} | class ____(metaclass=abc.ABCMeta):
"""A base class for handling installable artifacts.
The requirements for anything installable are as follows:
- we must be able to determine the requirement name
(or we can't correctly handle the non-upgrade case).
- for packages with setup requirements, we must also be able
to determine their requirements without installing additional
packages (for the same reason as run-time dependencies)
- we must be able to create a Distribution object exposing the
above metadata.
- if we need to do work in the build tracker, we must be able to generate a unique
string to identify the requirement in the build tracker.
"""
def __init__(self, req: InstallRequirement) -> None:
super().__init__()
self.req = req
@abc.abstractproperty
def build_tracker_id(self) -> str | None:
"""A string that uniquely identifies this requirement to the build tracker.
If None, then this dist has no work to do in the build tracker, and
``.prepare_distribution_metadata()`` will not be called."""
raise NotImplementedError()
@abc.abstractmethod
def get_metadata_distribution(self) -> BaseDistribution:
raise NotImplementedError()
@abc.abstractmethod
def prepare_distribution_metadata(
self,
build_env_installer: BuildEnvironmentInstaller,
build_isolation: bool,
check_build_deps: bool,
) -> None:
raise NotImplementedError()
| AbstractDistribution |
python | dask__dask | dask/_task_spec.py | {
"start": 10780,
"end": 15069
} | class ____:
key: KeyType
_dependencies: frozenset
__slots__ = tuple(__annotations__)
def ref(self):
return Alias(self.key)
def copy(self):
raise NotImplementedError
@property
def data_producer(self) -> bool:
return False
@property
def dependencies(self) -> frozenset:
return self._dependencies
@property
def block_fusion(self) -> bool:
return False
def _verify_values(self, values: tuple | dict) -> None:
if not self.dependencies:
return
if missing := set(self.dependencies) - set(values):
raise RuntimeError(f"Not enough arguments provided: missing keys {missing}")
def __call__(self, values) -> Any:
raise NotImplementedError("Not implemented")
def __eq__(self, value: object) -> bool:
if type(value) is not type(self):
return False
from dask.tokenize import tokenize
return tokenize(self) == tokenize(value)
@property
def is_coro(self) -> bool:
return False
def __sizeof__(self) -> int:
all_slots = self.get_all_slots()
return sum(sizeof(getattr(self, sl)) for sl in all_slots) + sys.getsizeof(
type(self)
)
def substitute(
self, subs: dict[KeyType, KeyType | GraphNode], key: KeyType | None = None
) -> GraphNode:
"""Substitute a dependency with a new value. The new value either has to
be a new valid key or a GraphNode to replace the dependency entirely.
The GraphNode will not be mutated but instead a shallow copy will be
returned. The substitution will be performed eagerly.
Parameters
----------
subs : dict[KeyType, KeyType | GraphNode]
The mapping describing the substitutions to be made.
key : KeyType | None, optional
The key of the new GraphNode object. If None provided, the key of
the old one will be reused.
"""
raise NotImplementedError
@staticmethod
def fuse(*tasks: GraphNode, key: KeyType | None = None) -> GraphNode:
"""Fuse a set of tasks into a single task.
The tasks are fused into a single task that will execute the tasks in a
subgraph. The internal tasks are no longer accessible from the outside.
All provided tasks must form a valid subgraph that will reduce to a
single key. If multiple outputs are possible with the provided tasks, an
exception will be raised.
The tasks will not be rewritten but instead a new Task will be created
that will merely reference the old task objects. This way, Task objects
may be reused in multiple fused tasks.
Parameters
----------
key : KeyType | None, optional
The key of the new Task object. If None provided, the key of the
final task will be used.
See also
--------
GraphNode.substitute : Easier substitution of dependencies
"""
if any(t.key is None for t in tasks):
raise ValueError("Cannot fuse tasks with missing keys")
if len(tasks) == 1:
return tasks[0].substitute({}, key=key)
all_keys = set()
all_deps: set[KeyType] = set()
for t in tasks:
all_deps.update(t.dependencies)
all_keys.add(t.key)
external_deps = tuple(sorted(all_deps - all_keys, key=hash))
leafs = all_keys - all_deps
if len(leafs) > 1:
raise ValueError(f"Cannot fuse tasks with multiple outputs {leafs}")
outkey = leafs.pop()
return Task(
key or outkey,
_execute_subgraph,
{t.key: t for t in tasks},
outkey,
external_deps,
*(TaskRef(k) for k in external_deps),
_data_producer=any(t.data_producer for t in tasks),
)
@classmethod
@lru_cache
def get_all_slots(cls):
slots = list()
for c in cls.mro():
slots.extend(getattr(c, "__slots__", ()))
# Interestingly, sorting this causes the nested containers to pickle
# more efficiently
return sorted(set(slots))
_no_deps: frozenset = frozenset()
| GraphNode |
python | allegroai__clearml | clearml/backend_api/services/v2_23/workers.py | {
"start": 26542,
"end": 29519
} | class ____(NonStrictDataModel):
"""
:param id: Worker ID
:type id: str
:param name: Worker name
:type name: str
:param running_time: Task running time
:type running_time: int
:param last_iteration: Last task iteration
:type last_iteration: int
"""
_schema = {
"properties": {
"id": {"description": "Worker ID", "type": ["string", "null"]},
"last_iteration": {
"description": "Last task iteration",
"type": ["integer", "null"],
},
"name": {"description": "Worker name", "type": ["string", "null"]},
"running_time": {
"description": "Task running time",
"type": ["integer", "null"],
},
},
"type": "object",
}
def __init__(
self,
id: Optional[str] = None,
name: Optional[str] = None,
running_time: Optional[int] = None,
last_iteration: Optional[int] = None,
**kwargs: Any
) -> None:
super(CurrentTaskEntry, self).__init__(**kwargs)
self.id = id
self.name = name
self.running_time = running_time
self.last_iteration = last_iteration
@schema_property("id")
def id(self) -> Optional[str]:
return self._property_id
@id.setter
def id(self, value: Optional[str]) -> None:
if value is None:
self._property_id = None
return
self.assert_isinstance(value, "id", six.string_types)
self._property_id = value
@schema_property("name")
def name(self) -> Optional[str]:
return self._property_name
@name.setter
def name(self, value: Optional[str]) -> None:
if value is None:
self._property_name = None
return
self.assert_isinstance(value, "name", six.string_types)
self._property_name = value
@schema_property("running_time")
def running_time(self) -> Optional[int]:
return self._property_running_time
@running_time.setter
def running_time(self, value: Optional[int]) -> None:
if value is None:
self._property_running_time = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "running_time", six.integer_types)
self._property_running_time = value
@schema_property("last_iteration")
def last_iteration(self) -> Optional[int]:
return self._property_last_iteration
@last_iteration.setter
def last_iteration(self, value: Optional[int]) -> None:
if value is None:
self._property_last_iteration = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "last_iteration", six.integer_types)
self._property_last_iteration = value
| CurrentTaskEntry |
python | marshmallow-code__marshmallow | tests/test_decorators.py | {
"start": 3917,
"end": 7876
} | class ____:
def test_pass_original_single(self):
class MySchema(Schema):
foo = fields.Raw()
@post_load(pass_original=True)
def post_load(self, data, original_data, **kwargs):
ret = data.copy()
ret["_post_load"] = original_data["sentinel"]
return ret
@post_dump(pass_original=True)
def post_dump(self, data, obj, **kwargs):
ret = data.copy()
ret["_post_dump"] = obj["sentinel"]
return ret
schema = MySchema(unknown=EXCLUDE)
datum = {"foo": 42, "sentinel": 24}
item_loaded = schema.load(datum)
assert item_loaded["foo"] == 42
assert item_loaded["_post_load"] == 24
item_dumped = schema.dump(datum)
assert item_dumped["foo"] == 42
assert item_dumped["_post_dump"] == 24
def test_pass_original_many(self):
class MySchema(Schema):
foo = fields.Raw()
@post_load(pass_collection=True, pass_original=True)
def post_load(self, data, original, many, **kwargs):
if many:
ret = []
for item, orig_item in zip(data, original, strict=True):
item["_post_load"] = orig_item["sentinel"]
ret.append(item)
else:
ret = data.copy()
ret["_post_load"] = original["sentinel"]
return ret
@post_dump(pass_collection=True, pass_original=True)
def post_dump(self, data, original, many, **kwargs):
if many:
ret = []
for item, orig_item in zip(data, original, strict=True):
item["_post_dump"] = orig_item["sentinel"]
ret.append(item)
else:
ret = data.copy()
ret["_post_dump"] = original["sentinel"]
return ret
schema = MySchema(unknown=EXCLUDE)
data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}]
items_loaded = schema.load(data, many=True)
assert items_loaded == [
{"foo": 42, "_post_load": 24},
{"foo": 424, "_post_load": 242},
]
test_values = [e["_post_load"] for e in items_loaded]
assert test_values == [24, 242]
items_dumped = schema.dump(data, many=True)
assert items_dumped == [
{"foo": 42, "_post_dump": 24},
{"foo": 424, "_post_dump": 242},
]
# Also check load/dump of single item
datum = {"foo": 42, "sentinel": 24}
item_loaded = schema.load(datum, many=False)
assert item_loaded == {"foo": 42, "_post_load": 24}
item_dumped = schema.dump(datum, many=False)
assert item_dumped == {"foo": 42, "_post_dump": 24}
def test_decorated_processor_inheritance():
class ParentSchema(Schema):
@post_dump
def inherited(self, item, **kwargs):
item["inherited"] = "inherited"
return item
@post_dump
def overridden(self, item, **kwargs):
item["overridden"] = "base"
return item
@post_dump
def deleted(self, item, **kwargs):
item["deleted"] = "retained"
return item
class ChildSchema(ParentSchema):
@post_dump
def overridden(self, item, **kwargs):
item["overridden"] = "overridden"
return item
deleted = None # type: ignore[assignment]
parent_dumped = ParentSchema().dump({})
assert parent_dumped == {
"inherited": "inherited",
"overridden": "base",
"deleted": "retained",
}
child_dumped = ChildSchema().dump({})
assert child_dumped == {"inherited": "inherited", "overridden": "overridden"}
| TestPassOriginal |
python | spack__spack | lib/spack/spack/vendor/jinja2/nodes.py | {
"start": 25066,
"end": 25654
} | class ____(Expr):
"""Get an attribute or item from an expression and prefer the item."""
fields = ("node", "arg", "ctx")
node: Expr
arg: Expr
ctx: str
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
if self.ctx != "load":
raise Impossible()
eval_ctx = get_eval_context(self, eval_ctx)
try:
return eval_ctx.environment.getitem(
self.node.as_const(eval_ctx), self.arg.as_const(eval_ctx)
)
except Exception as e:
raise Impossible() from e
| Getitem |
python | bokeh__bokeh | src/bokeh/models/glyph.py | {
"start": 3013,
"end": 3317
} | class ____(XYGlyph):
''' Base class of glyphs with `x` and `y` coordinate attributes and
a connected topology.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@abstract
| ConnectedXYGlyph |
python | astropy__astropy | astropy/coordinates/tests/test_representation_methods.py | {
"start": 12187,
"end": 16795
} | class ____(ShapeSetup):
def test_broadcast_to(self):
s0_broadcast = np.broadcast_to(self.s0, (3, 6, 7))
s0_diff = s0_broadcast.differentials["s"]
assert type(s0_broadcast) is type(self.s0)
assert s0_broadcast.shape == (3, 6, 7)
assert s0_diff.shape == s0_broadcast.shape
assert np.all(s0_broadcast.lon == self.s0.lon)
assert np.all(s0_broadcast.lat == self.s0.lat)
assert np.all(s0_broadcast.distance == self.s0.distance)
assert np.may_share_memory(s0_broadcast.lon, self.s0.lon)
assert np.may_share_memory(s0_broadcast.lat, self.s0.lat)
assert np.may_share_memory(s0_broadcast.distance, self.s0.distance)
s1_broadcast = np.broadcast_to(self.s1, shape=(3, 6, 7))
s1_diff = s1_broadcast.differentials["s"]
assert s1_broadcast.shape == (3, 6, 7)
assert s1_diff.shape == s1_broadcast.shape
assert np.all(s1_broadcast.lat == self.s1.lat)
assert np.all(s1_broadcast.lon == self.s1.lon)
assert np.all(s1_broadcast.distance == self.s1.distance)
assert s1_broadcast.distance.shape == (3, 6, 7)
assert np.may_share_memory(s1_broadcast.lat, self.s1.lat)
assert np.may_share_memory(s1_broadcast.lon, self.s1.lon)
assert np.may_share_memory(s1_broadcast.distance, self.s1.distance)
# A final test that "may_share_memory" equals "does_share_memory"
# Do this on a copy, to keep self.s0 unchanged.
sc = self.s0.copy()
assert not np.may_share_memory(sc.lon, self.s0.lon)
assert not np.may_share_memory(sc.lat, self.s0.lat)
sc_broadcast = np.broadcast_to(sc, (3, 6, 7))
assert np.may_share_memory(sc_broadcast.lon, sc.lon)
# Can only write to copy, not to broadcast version.
sc.lon[0, 0] = 22.0 * u.hourangle
assert np.all(sc_broadcast.lon[:, 0, 0] == 22.0 * u.hourangle)
def test_atleast_1d(self):
s00 = self.s0.ravel()[0]
assert s00.ndim == 0
s00_1d = np.atleast_1d(s00)
assert s00_1d.ndim == 1
assert np.all(representation_equal(s00[np.newaxis], s00_1d))
assert np.may_share_memory(s00_1d.lon, s00.lon)
def test_atleast_2d(self):
s0r = self.s0.ravel()
assert s0r.ndim == 1
s0r_2d = np.atleast_2d(s0r)
assert s0r_2d.ndim == 2
assert np.all(representation_equal(s0r[np.newaxis], s0r_2d))
assert np.may_share_memory(s0r_2d.lon, s0r.lon)
def test_atleast_3d(self):
assert self.s0.ndim == 2
s0_3d, s1_3d = np.atleast_3d(self.s0, self.s1)
assert s0_3d.ndim == s1_3d.ndim == 3
assert np.all(representation_equal(self.s0[:, :, np.newaxis], s0_3d))
assert np.all(representation_equal(self.s1[:, :, np.newaxis], s1_3d))
assert np.may_share_memory(s0_3d.lon, self.s0.lon)
def test_move_axis(self):
# Goes via transpose so works without __array_function__ as well.
s0_10 = np.moveaxis(self.s0, 0, 1)
assert s0_10.shape == (self.s0.shape[1], self.s0.shape[0])
assert np.all(representation_equal(self.s0.T, s0_10))
assert np.may_share_memory(s0_10.lon, self.s0.lon)
def test_roll_axis(self):
# Goes via transpose so works without __array_function__ as well.
s0_10 = np.rollaxis(self.s0, 1)
assert s0_10.shape == (self.s0.shape[1], self.s0.shape[0])
assert np.all(representation_equal(self.s0.T, s0_10))
assert np.may_share_memory(s0_10.lon, self.s0.lon)
def test_fliplr(self):
s0_lr = np.fliplr(self.s0)
assert np.all(representation_equal(self.s0[:, ::-1], s0_lr))
assert np.may_share_memory(s0_lr.lon, self.s0.lon)
def test_rot90(self):
s0_270 = np.rot90(self.s0, 3)
assert np.all(representation_equal(self.s0.T[:, ::-1], s0_270))
assert np.may_share_memory(s0_270.lon, self.s0.lon)
def test_roll(self):
s0r = np.roll(self.s0, 1, axis=0)
assert np.all(representation_equal(s0r[1:], self.s0[:-1]))
assert np.all(representation_equal(s0r[0], self.s0[-1]))
def test_delete(self):
s0d = np.delete(self.s0, [2, 3], axis=0)
assert np.all(representation_equal(s0d[:2], self.s0[:2]))
assert np.all(representation_equal(s0d[2:], self.s0[4:]))
@pytest.mark.parametrize("attribute", ["shape", "ndim", "size"])
def test_shape_attribute_functions(self, attribute):
function = getattr(np, attribute)
result = function(self.s0)
assert result == getattr(self.s0, attribute)
| TestShapeFunctions |
python | Netflix__metaflow | metaflow/plugins/pypi/pip.py | {
"start": 709,
"end": 1538
} | class ____(Exception):
"Wrapper for pip package resolve errors."
def __init__(self, error):
self.error = error
try:
# Parse the package spec from error message:
# ERROR: ERROR: Could not find a version that satisfies the requirement pkg==0.0.1 (from versions: none)
# ERROR: No matching distribution found for pkg==0.0.1
self.package_spec = re.search(
"ERROR: No matching distribution found for (.*)", self.error
)[1]
self.package_name = re.match("\w*", self.package_spec)[0]
except Exception:
pass
METADATA_FILE = "{prefix}/.pip/metadata"
INSTALLATION_MARKER = "{prefix}/.pip/id"
# TODO:
# 1. Support local dirs, non-wheel like packages
# 2. Support protected indices
| PipPackageNotFound |
python | neetcode-gh__leetcode | python/0707-design-linked-list.py | {
"start": 119,
"end": 1863
} | class ____:
def __init__(self):
self.left = ListNode(0)
self.right = ListNode(0)
self.left.next = self.right
self.right.prev = self.left
def get(self, index: int) -> int:
cur = self.left.next
while cur and index > 0:
cur = cur.next
index -= 1
if cur and cur != self.right and index == 0:
return cur.val
return -1
def addAtHead(self, val: int) -> None:
node, prev, next = ListNode(val), self.left, self.left.next
node.next, node.prev = next, prev
next.prev = node
prev.next = node
def addAtTail(self, val: int) -> None:
node, prev, next = ListNode(val), self.right.prev, self.right
node.next, node.prev = next, prev
next.prev = node
prev.next = node
def addAtIndex(self, index: int, val: int) -> None:
next = self.left.next
while next and index > 0:
next = next.next
index -= 1
if next and index == 0:
node, prev = ListNode(val), next.prev
node.next, node.prev = next, prev
next.prev = node
prev.next = node
def deleteAtIndex(self, index: int) -> None:
node = self.left.next
while node and index > 0:
node = node.next
index -= 1
if node and node != self.right and index == 0:
node.prev.next = node.next
node.next.prev = node.prev
# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)
| MyLinkedList |
python | MTrajK__coding-problems | Other/running_median.py | {
"start": 573,
"end": 2859
} | class ____:
def __init__(self, is_min=True):
self.data = []
self.is_min = is_min
def push(self, el):
if not self.is_min:
el = -el
heapq.heappush(self.data, el)
def pop(self):
el = heapq.heappop(self.data)
if not self.is_min:
el = -el
return el
def peek(self):
el = self.data[0]
if not self.is_min:
el = -el
return el
def count(self):
return len(self.data)
def running_median(stream):
left_heap = PriorityQueue(False) # Max Priority Queue
right_heap = PriorityQueue() # Min Priority Queue
# left_heap will have always same number of elements or 1 element more than right_heap
for number in stream:
if left_heap.count() == 0:
# enters here only for the first element of the streen
left_heap.push(number)
# balance the heaps
elif left_heap.count() > right_heap.count():
# in this case the right_heap should get a new element (so both heaps will have same number of elements)
if left_heap.peek() > number:
# move an element from left to right heap
right_heap.push(left_heap.pop())
left_heap.push(number)
else:
right_heap.push(number)
else:
# in this case the left_heap should get a new element (so the left_heap will have 1 more element)
if right_heap.peek() < number:
# move an element from right to left heap
left_heap.push(right_heap.pop())
right_heap.push(number)
else:
left_heap.push(number)
if left_heap.count() > right_heap.count():
# if left_heap is bigger then odd elements from the stream are processed
# because left_heap is bigger ONLY BY 1 element from right_heap (n + n + 1 = 2n + 1)
print(left_heap.peek())
else:
# both heaps have same length, so the count from the elements is even (n + n = 2n)
print((left_heap.peek() + right_heap.peek())/2)
###########
# Testing #
###########
# Test 1
# Correct result => 2 1.5 2 3.5 2 2 2
running_median([2, 1, 5, 7, 2, 0, 5]) | PriorityQueue |
python | eth-brownie__brownie | brownie/_gui/console.py | {
"start": 107,
"end": 420
} | class ____(ToggleButton):
def __init__(self, parent):
super().__init__(parent, "Console", "c")
self.console = self.root.main.console
def toggle_on(self):
self.console.config(height=3)
return True
def toggle_off(self):
self.console.config(height=1)
| ConsoleButton |
python | pytorch__pytorch | torchgen/api/types/types.py | {
"start": 4746,
"end": 5082
} | class ____(CType):
elem: CType
def cpp_type(self, *, strip_ref: bool = False) -> str:
# Do not pass `strip_ref` recursively.
return f"::std::optional<{self.elem.cpp_type()}>"
def remove_const_ref(self) -> CType:
return OptionalCType(self.elem.remove_const_ref())
@dataclass(frozen=True)
| OptionalCType |
python | ray-project__ray | python/ray/train/examples/pytorch/torch_data_prefetch_benchmark/auto_pipeline_for_host_to_device_data_transfer.py | {
"start": 239,
"end": 621
} | class ____(nn.Module):
def __init__(self, in_d, hidden):
# output dim = 1
super(Net, self).__init__()
dims = [in_d] + hidden + [1]
self.layers = nn.ModuleList(
[nn.Linear(dims[i - 1], dims[i]) for i in range(len(dims))]
)
def forward(self, x):
for layer in self.layers:
x = layer(x)
return x
| Net |
python | openai__openai-python | src/openai/types/audio/transcription.py | {
"start": 872,
"end": 1373
} | class ____(BaseModel):
input_tokens: int
"""Number of input tokens billed for this request."""
output_tokens: int
"""Number of output tokens generated."""
total_tokens: int
"""Total number of tokens used (input + output)."""
type: Literal["tokens"]
"""The type of the usage object. Always `tokens` for this variant."""
input_token_details: Optional[UsageTokensInputTokenDetails] = None
"""Details about the input tokens billed for this request."""
| UsageTokens |
python | tensorflow__tensorflow | third_party/xla/xla/backends/cpu/testlib/elemental_kernel_emitter_test.py | {
"start": 6971,
"end": 8863
} | class ____(parameterized.TestCase):
def test_elemental_comparision_kernel_emitter(self, op_def, shape, dtype):
[direction, np_op] = op_def
is_unsigned = np.issubdtype(dtype, np.unsignedinteger)
value_range = (0.0, 20.0) if is_unsigned else (-10.0, 10.0)
lhs_np = create_input(value_range, shape, dtype, shuffle=True)
rhs_np = create_input(value_range, shape, dtype, shuffle=True)
lhs_literal = create_literal(lhs_np)
rhs_literal = create_literal(rhs_np)
output_literal = create_literal(np.ndarray(shape, dtype=np.bool))
lhs_param = HloInstruction.create_parameter(0, lhs_literal.shape(), "lhs")
rhs_param = HloInstruction.create_parameter(1, rhs_literal.shape(), "rhs")
hlo_op = HloInstruction.create_compare(
output_literal.shape(), lhs_param, rhs_param, direction
)
hlo_module, buffer_assignment = utilities.build_hlo_module(
hlo_op, lhs_param, rhs_param
)
jit_compiler = testlib_cpu.JitCompiler(hlo_module.get_config())
emitter = testlib_cpu.ElementalKernelEmitter(
hlo_module.get_root_instruction(),
buffer_assignment,
jit_compiler.get_target_machine(),
)
runner = testlib_cpu.KernelRunner.create(
emitter.emit_kernel_definition(), jit_compiler
)
runner.call([lhs_literal, rhs_literal, output_literal])
np.testing.assert_equal(
np.asarray(output_literal),
np_op(lhs_np, rhs_np),
)
@parameterized.product(
input_dimensions=[(4,), (4, 3), (4, 3, 10)],
dtype=[
np.dtype(np.uint8),
np.dtype(np.uint16),
np.dtype(np.uint32),
np.dtype(np.uint64),
np.dtype(np.int8),
np.dtype(np.int16),
np.dtype(np.int32),
np.dtype(np.int64),
np.dtype(np.float16),
np.dtype(np.float32),
np.dtype(np.float64),
],
)
| ElementalComparisonKernelRunnerTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefaultClass3.py | {
"start": 1432,
"end": 1481
} | class ____[T1 = str, T4 = dict[T1, T2]]: ...
| ClassJ |
python | pytorch__pytorch | torch/ao/nn/quantized/modules/conv.py | {
"start": 16624,
"end": 21181
} | class ____(_ConvNd):
r"""Applies a 2D convolution over a quantized input signal composed of
several quantized input planes.
For details on input arguments, parameters, and implementation see
:class:`~torch.nn.Conv2d`.
.. note::
Only `zeros` is supported for the :attr:`padding_mode` argument.
.. note::
Only `torch.quint8` is supported for the input data type.
Attributes:
weight (Tensor): packed tensor derived from the learnable weight
parameter.
scale (Tensor): scalar for the output scale
zero_point (Tensor): scalar for the output zero point
See :class:`~torch.nn.Conv2d` for other attributes.
Examples::
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
>>> # With square kernels and equal stride
>>> m = nn.quantized.Conv2d(16, 33, 3, stride=2)
>>> # non-square kernels and unequal stride and with padding
>>> m = nn.quantized.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
>>> # non-square kernels and unequal stride and with padding and dilation
>>> m = nn.quantized.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1))
>>> input = torch.randn(20, 16, 50, 100)
>>> # quantize input to quint8
>>> # xdoctest: +SKIP
>>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
>>> output = m(q_input)
"""
_FLOAT_MODULE: ClassVar[type[nn.Conv2d]] = nn.Conv2d
_NNIQAT_CONV_BN_MODULE: ClassVar[Optional[type[nn.Module]]] = nniqat.ConvBn2d
_NNI_CONV_RELU_MODULE: ClassVar[Optional[type[nn.Module]]] = nni.ConvReLU2d
_NNI_CONV_ADD_MODULE: ClassVar[type[nni.ConvAdd2d]] = nni.ConvAdd2d
_NNI_CONV_ADD_RELU_MODULE: ClassVar[type[nni.ConvAddReLU2d]] = nni.ConvAddReLU2d
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
dilation=1,
groups=1,
bias=True,
padding_mode="zeros",
device=None,
dtype=None,
):
factory_kwargs = {"device": device, "dtype": dtype}
kernel_size = _pair(kernel_size)
stride = _pair(stride)
padding = _pair(padding)
dilation = _pair(dilation)
# Subclasses of _ConvNd need to call _init rather than __init__. See
# discussion on PR #49702
super()._init(
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation,
False,
_pair(0),
groups,
bias,
padding_mode,
**factory_kwargs,
)
def _get_name(self):
return "QuantizedConv2d"
def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None:
if self.padding_mode == "zeros":
self._packed_params = torch.ops.quantized.conv2d_prepack(
w, b, self.stride, self.padding, self.dilation, self.groups
)
else:
self._packed_params = torch.ops.quantized.conv2d_prepack(
w, b, self.stride, _pair(0), self.dilation, self.groups
)
def _weight_bias(self):
return self._packed_params.unpack()
def weight(self):
return self._weight_bias()[0]
def bias(self):
return self._weight_bias()[1]
def forward(self, input):
# Temporarily using len(shape) instead of ndim due to JIT issue
# https://github.com/pytorch/pytorch/issues/23890
if len(input.shape) != 4:
raise ValueError("Input shape must be `(N, C, H, W)`!")
if self.padding_mode != "zeros":
_reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
input = F.pad(
input, _reversed_padding_repeated_twice, mode=self.padding_mode
)
return ops.quantized.conv2d(
input, self._packed_params, self.scale, self.zero_point
)
@classmethod
def from_float(cls, mod, use_precomputed_fake_quant=False): # type: ignore[override]
r"""Creates a quantized module from a float module or qparams_dict.
Args:
mod (Module): a float module, either produced by torch.ao.quantization
utilities or provided by the user
"""
return _ConvNd.from_float(
cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant
)
| Conv2d |
python | html5lib__html5lib-python | html5lib/html5parser.py | {
"start": 2188,
"end": 14726
} | class ____(object):
"""HTML parser
Generates a tree structure from a stream of (possibly malformed) HTML.
"""
def __init__(self, tree=None, strict=False, namespaceHTMLElements=True, debug=False):
"""
:arg tree: a treebuilder class controlling the type of tree that will be
returned. Built in treebuilders can be accessed through
html5lib.treebuilders.getTreeBuilder(treeType)
:arg strict: raise an exception when a parse error is encountered
:arg namespaceHTMLElements: whether or not to namespace HTML elements
:arg debug: whether or not to enable debug mode which logs things
Example:
>>> from html5lib.html5parser import HTMLParser
>>> parser = HTMLParser() # generates parser with etree builder
>>> parser = HTMLParser('lxml', strict=True) # generates parser with lxml builder which is strict
"""
# Raise an exception on the first error encountered
self.strict = strict
self.debug = debug
if tree is None:
tree = treebuilders.getTreeBuilder("etree")
elif isinstance(tree, str):
tree = treebuilders.getTreeBuilder(tree)
self.tree = tree(namespaceHTMLElements)
self.errors = []
self.phases = {name: cls(self, self.tree) for name, cls in
_phases.items()}
def _parse(self, stream, innerHTML=False, container="div", scripting=False, **kwargs):
self.innerHTMLMode = innerHTML
self.container = container
self.scripting = scripting
self.tokenizer = _tokenizer.HTMLTokenizer(stream, parser=self, **kwargs)
self.reset()
try:
self.mainLoop()
except _ReparseException:
self.reset()
self.mainLoop()
def reset(self):
self.tree.reset()
self.firstStartTag = False
self.errors = []
self.log = [] # only used with debug mode
# "quirks" / "limited quirks" / "no quirks"
self.compatMode = "no quirks"
if self.innerHTMLMode:
self.innerHTML = self.container.lower()
if self.innerHTML in cdataElements:
self.tokenizer.state = self.tokenizer.rcdataState
elif self.innerHTML in rcdataElements:
self.tokenizer.state = self.tokenizer.rawtextState
elif self.innerHTML == 'plaintext':
self.tokenizer.state = self.tokenizer.plaintextState
else:
# state already is data state
# self.tokenizer.state = self.tokenizer.dataState
pass
self.phase = self.phases["beforeHtml"]
self.phase.insertHtmlElement()
self.resetInsertionMode()
else:
self.innerHTML = False # pylint:disable=redefined-variable-type
self.phase = self.phases["initial"]
self.lastPhase = None
self.beforeRCDataPhase = None
self.framesetOK = True
@property
def documentEncoding(self):
"""Name of the character encoding that was used to decode the input stream, or
:obj:`None` if that is not determined yet
"""
if not hasattr(self, 'tokenizer'):
return None
return self.tokenizer.stream.charEncoding[0].name
def isHTMLIntegrationPoint(self, element):
if (element.name == "annotation-xml" and
element.namespace == namespaces["mathml"]):
return ("encoding" in element.attributes and
element.attributes["encoding"].translate(
asciiUpper2Lower) in
("text/html", "application/xhtml+xml"))
else:
return (element.namespace, element.name) in htmlIntegrationPointElements
def isMathMLTextIntegrationPoint(self, element):
return (element.namespace, element.name) in mathmlTextIntegrationPointElements
def mainLoop(self):
CharactersToken = tokenTypes["Characters"]
SpaceCharactersToken = tokenTypes["SpaceCharacters"]
StartTagToken = tokenTypes["StartTag"]
EndTagToken = tokenTypes["EndTag"]
CommentToken = tokenTypes["Comment"]
DoctypeToken = tokenTypes["Doctype"]
ParseErrorToken = tokenTypes["ParseError"]
type_names = {value: key for key, value in tokenTypes.items()}
debug = self.debug
for token in self.tokenizer:
prev_token = None
new_token = token
while new_token is not None:
prev_token = new_token
currentNode = self.tree.openElements[-1] if self.tree.openElements else None
currentNodeNamespace = currentNode.namespace if currentNode else None
currentNodeName = currentNode.name if currentNode else None
type = new_token["type"]
if type == ParseErrorToken:
self.parseError(new_token["data"], new_token.get("datavars", {}))
new_token = None
else:
if (len(self.tree.openElements) == 0 or
currentNodeNamespace == self.tree.defaultNamespace or
(self.isMathMLTextIntegrationPoint(currentNode) and
((type == StartTagToken and
token["name"] not in frozenset(["mglyph", "malignmark"])) or
type in (CharactersToken, SpaceCharactersToken))) or
(currentNodeNamespace == namespaces["mathml"] and
currentNodeName == "annotation-xml" and
type == StartTagToken and
token["name"] == "svg") or
(self.isHTMLIntegrationPoint(currentNode) and
type in (StartTagToken, CharactersToken, SpaceCharactersToken))):
phase = self.phase
else:
phase = self.phases["inForeignContent"]
if debug:
info = {"type": type_names[type]}
if type in (StartTagToken, EndTagToken):
info["name"] = new_token['name']
self.log.append((self.tokenizer.state.__name__,
self.phase.__class__.__name__,
phase.__class__.__name__,
"process" + info["type"],
info))
if type == CharactersToken:
new_token = phase.processCharacters(new_token)
elif type == SpaceCharactersToken:
new_token = phase.processSpaceCharacters(new_token)
elif type == StartTagToken:
new_token = phase.processStartTag(new_token)
elif type == EndTagToken:
new_token = phase.processEndTag(new_token)
elif type == CommentToken:
new_token = phase.processComment(new_token)
elif type == DoctypeToken:
new_token = phase.processDoctype(new_token)
if (type == StartTagToken and prev_token["selfClosing"] and
not prev_token["selfClosingAcknowledged"]):
self.parseError("non-void-element-with-trailing-solidus",
{"name": prev_token["name"]})
# When the loop finishes it's EOF
reprocess = True
phases = []
while reprocess:
phases.append(self.phase)
reprocess = self.phase.processEOF()
if reprocess:
assert self.phase not in phases
def parse(self, stream, *args, **kwargs):
"""Parse a HTML document into a well-formed tree
:arg stream: a file-like object or string containing the HTML to be parsed
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element).
:arg scripting: treat noscript elements as if JavaScript was turned on
:returns: parsed tree
Example:
>>> from html5lib.html5parser import HTMLParser
>>> parser = HTMLParser()
>>> parser.parse('<html><body><p>This is a doc</p></body></html>')
<Element u'{http://www.w3.org/1999/xhtml}html' at 0x7feac4909db0>
"""
self._parse(stream, False, None, *args, **kwargs)
return self.tree.getDocument()
def parseFragment(self, stream, *args, **kwargs):
"""Parse a HTML fragment into a well-formed tree fragment
:arg container: name of the element we're setting the innerHTML
property if set to None, default to 'div'
:arg stream: a file-like object or string containing the HTML to be parsed
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element)
:arg scripting: treat noscript elements as if JavaScript was turned on
:returns: parsed tree
Example:
>>> from html5lib.html5libparser import HTMLParser
>>> parser = HTMLParser()
>>> parser.parseFragment('<b>this is a fragment</b>')
<Element u'DOCUMENT_FRAGMENT' at 0x7feac484b090>
"""
self._parse(stream, True, *args, **kwargs)
return self.tree.getFragment()
def parseError(self, errorcode="XXX-undefined-error", datavars=None):
# XXX The idea is to make errorcode mandatory.
if datavars is None:
datavars = {}
self.errors.append((self.tokenizer.stream.position(), errorcode, datavars))
if self.strict:
raise ParseError(E[errorcode] % datavars)
def adjustMathMLAttributes(self, token):
adjust_attributes(token, adjustMathMLAttributes)
def adjustSVGAttributes(self, token):
adjust_attributes(token, adjustSVGAttributes)
def adjustForeignAttributes(self, token):
adjust_attributes(token, adjustForeignAttributesMap)
def reparseTokenNormal(self, token):
# pylint:disable=unused-argument
self.parser.phase()
def resetInsertionMode(self):
# The name of this method is mostly historical. (It's also used in the
# specification.)
last = False
newModes = {
"select": "inSelect",
"td": "inCell",
"th": "inCell",
"tr": "inRow",
"tbody": "inTableBody",
"thead": "inTableBody",
"tfoot": "inTableBody",
"caption": "inCaption",
"colgroup": "inColumnGroup",
"table": "inTable",
"head": "inBody",
"body": "inBody",
"frameset": "inFrameset",
"html": "beforeHead"
}
for node in self.tree.openElements[::-1]:
nodeName = node.name
new_phase = None
if node == self.tree.openElements[0]:
assert self.innerHTML
last = True
nodeName = self.innerHTML
# Check for conditions that should only happen in the innerHTML
# case
if nodeName in ("select", "colgroup", "head", "html"):
assert self.innerHTML
if not last and node.namespace != self.tree.defaultNamespace:
continue
if nodeName in newModes:
new_phase = self.phases[newModes[nodeName]]
break
elif last:
new_phase = self.phases["inBody"]
break
self.phase = new_phase
def parseRCDataRawtext(self, token, contentType):
# Generic RCDATA/RAWTEXT Parsing algorithm
assert contentType in ("RAWTEXT", "RCDATA")
self.tree.insertElement(token)
if contentType == "RAWTEXT":
self.tokenizer.state = self.tokenizer.rawtextState
else:
self.tokenizer.state = self.tokenizer.rcdataState
self.originalPhase = self.phase
self.phase = self.phases["text"]
| HTMLParser |
python | django__django | tests/admin_views/test_autocomplete_view.py | {
"start": 2061,
"end": 14744
} | class ____(AdminViewBasicTestCase):
as_view_args = {"admin_site": site}
opts = {
"app_label": Answer._meta.app_label,
"model_name": Answer._meta.model_name,
"field_name": "question",
}
factory = RequestFactory()
url = reverse_lazy("autocomplete_admin:autocomplete")
@classmethod
def setUpTestData(cls):
cls.user = User.objects.create_user(
username="user",
password="secret",
email="user@example.com",
is_staff=True,
)
super().setUpTestData()
def test_success(self):
q = Question.objects.create(question="Is this a question?")
request = self.factory.get(self.url, {"term": "is", **self.opts})
request.user = self.superuser
response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
self.assertEqual(response.status_code, 200)
data = json.loads(response.text)
self.assertEqual(
data,
{
"results": [{"id": str(q.pk), "text": q.question}],
"pagination": {"more": False},
},
)
def test_custom_to_field(self):
q = Question.objects.create(question="Is this a question?")
request = self.factory.get(
self.url,
{"term": "is", **self.opts, "field_name": "question_with_to_field"},
)
request.user = self.superuser
response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
self.assertEqual(response.status_code, 200)
data = json.loads(response.text)
self.assertEqual(
data,
{
"results": [{"id": str(q.uuid), "text": q.question}],
"pagination": {"more": False},
},
)
def test_custom_to_field_permission_denied(self):
Question.objects.create(question="Is this a question?")
request = self.factory.get(
self.url,
{"term": "is", **self.opts, "field_name": "question_with_to_field"},
)
request.user = self.user
with self.assertRaises(PermissionDenied):
AutocompleteJsonView.as_view(**self.as_view_args)(request)
def test_custom_to_field_custom_pk(self):
q = Question.objects.create(question="Is this a question?")
opts = {
"app_label": Question._meta.app_label,
"model_name": Question._meta.model_name,
"field_name": "related_questions",
}
request = self.factory.get(self.url, {"term": "is", **opts})
request.user = self.superuser
response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
self.assertEqual(response.status_code, 200)
data = json.loads(response.text)
self.assertEqual(
data,
{
"results": [{"id": str(q.big_id), "text": q.question}],
"pagination": {"more": False},
},
)
def test_to_field_resolution_with_mti(self):
"""
to_field resolution should correctly resolve for target models using
MTI. Tests for single and multi-level cases.
"""
tests = [
(Employee, WorkHour, "employee"),
(Manager, Bonus, "recipient"),
]
for Target, Remote, related_name in tests:
with self.subTest(
target_model=Target, remote_model=Remote, related_name=related_name
):
o = Target.objects.create(
name="Frida Kahlo", gender=2, code="painter", alive=False
)
opts = {
"app_label": Remote._meta.app_label,
"model_name": Remote._meta.model_name,
"field_name": related_name,
}
request = self.factory.get(self.url, {"term": "frida", **opts})
request.user = self.superuser
response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
self.assertEqual(response.status_code, 200)
data = json.loads(response.text)
self.assertEqual(
data,
{
"results": [{"id": str(o.pk), "text": o.name}],
"pagination": {"more": False},
},
)
def test_to_field_resolution_with_fk_pk(self):
p = Parent.objects.create(name="Bertie")
c = PKChild.objects.create(parent=p, name="Anna")
opts = {
"app_label": Toy._meta.app_label,
"model_name": Toy._meta.model_name,
"field_name": "child",
}
request = self.factory.get(self.url, {"term": "anna", **opts})
request.user = self.superuser
response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
self.assertEqual(response.status_code, 200)
data = json.loads(response.text)
self.assertEqual(
data,
{
"results": [{"id": str(c.pk), "text": c.name}],
"pagination": {"more": False},
},
)
def test_field_does_not_exist(self):
request = self.factory.get(
self.url, {"term": "is", **self.opts, "field_name": "does_not_exist"}
)
request.user = self.superuser
with self.assertRaises(PermissionDenied):
AutocompleteJsonView.as_view(**self.as_view_args)(request)
def test_field_no_related_field(self):
request = self.factory.get(
self.url, {"term": "is", **self.opts, "field_name": "answer"}
)
request.user = self.superuser
with self.assertRaises(PermissionDenied):
AutocompleteJsonView.as_view(**self.as_view_args)(request)
def test_field_does_not_allowed(self):
request = self.factory.get(
self.url, {"term": "is", **self.opts, "field_name": "related_questions"}
)
request.user = self.superuser
with self.assertRaises(PermissionDenied):
AutocompleteJsonView.as_view(**self.as_view_args)(request)
def test_limit_choices_to(self):
# Answer.question_with_to_field defines limit_choices_to to "those not
# starting with 'not'".
q = Question.objects.create(question="Is this a question?")
Question.objects.create(question="Not a question.")
request = self.factory.get(
self.url,
{"term": "is", **self.opts, "field_name": "question_with_to_field"},
)
request.user = self.superuser
response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
self.assertEqual(response.status_code, 200)
data = json.loads(response.text)
self.assertEqual(
data,
{
"results": [{"id": str(q.uuid), "text": q.question}],
"pagination": {"more": False},
},
)
def test_must_be_logged_in(self):
response = self.client.get(self.url, {"term": "", **self.opts})
self.assertEqual(response.status_code, 200)
self.client.logout()
response = self.client.get(self.url, {"term": "", **self.opts})
self.assertEqual(response.status_code, 302)
def test_has_view_or_change_permission_required(self):
"""
Users require the change permission for the related model to the
autocomplete view for it.
"""
request = self.factory.get(self.url, {"term": "is", **self.opts})
request.user = self.user
with self.assertRaises(PermissionDenied):
AutocompleteJsonView.as_view(**self.as_view_args)(request)
for permission in ("view", "change"):
with self.subTest(permission=permission):
self.user.user_permissions.clear()
p = Permission.objects.get(
content_type=ContentType.objects.get_for_model(Question),
codename="%s_question" % permission,
)
self.user.user_permissions.add(p)
request.user = User.objects.get(pk=self.user.pk)
response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
self.assertEqual(response.status_code, 200)
def test_search_use_distinct(self):
"""
Searching across model relations use QuerySet.distinct() to avoid
duplicates.
"""
q1 = Question.objects.create(question="question 1")
q2 = Question.objects.create(question="question 2")
q2.related_questions.add(q1)
q3 = Question.objects.create(question="question 3")
q3.related_questions.add(q1)
request = self.factory.get(self.url, {"term": "question", **self.opts})
request.user = self.superuser
class DistinctQuestionAdmin(QuestionAdmin):
search_fields = ["related_questions__question", "question"]
with model_admin(Question, DistinctQuestionAdmin):
response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
self.assertEqual(response.status_code, 200)
data = json.loads(response.text)
self.assertEqual(len(data["results"]), 3)
def test_missing_search_fields(self):
class EmptySearchAdmin(QuestionAdmin):
search_fields = []
with model_admin(Question, EmptySearchAdmin):
msg = "EmptySearchAdmin must have search_fields for the autocomplete_view."
with self.assertRaisesMessage(Http404, msg):
site.autocomplete_view(
self.factory.get(self.url, {"term": "", **self.opts})
)
def test_get_paginator(self):
"""Search results are paginated."""
class PKOrderingQuestionAdmin(QuestionAdmin):
ordering = ["pk"]
Question.objects.bulk_create(
Question(question=str(i)) for i in range(PAGINATOR_SIZE + 10)
)
# The first page of results.
request = self.factory.get(self.url, {"term": "", **self.opts})
request.user = self.superuser
with model_admin(Question, PKOrderingQuestionAdmin):
response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
self.assertEqual(response.status_code, 200)
data = json.loads(response.text)
self.assertEqual(
data,
{
"results": [
{"id": str(q.pk), "text": q.question}
for q in Question.objects.all()[:PAGINATOR_SIZE]
],
"pagination": {"more": True},
},
)
# The second page of results.
request = self.factory.get(self.url, {"term": "", "page": "2", **self.opts})
request.user = self.superuser
with model_admin(Question, PKOrderingQuestionAdmin):
response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
self.assertEqual(response.status_code, 200)
data = json.loads(response.text)
self.assertEqual(
data,
{
"results": [
{"id": str(q.pk), "text": q.question}
for q in Question.objects.all()[PAGINATOR_SIZE:]
],
"pagination": {"more": False},
},
)
def test_serialize_result(self):
class AutocompleteJsonSerializeResultView(AutocompleteJsonView):
def serialize_result(self, obj, to_field_name):
return {
**super().serialize_result(obj, to_field_name),
"posted": str(obj.posted),
}
Question.objects.create(question="Question 1", posted=datetime.date(2021, 8, 9))
Question.objects.create(question="Question 2", posted=datetime.date(2021, 8, 7))
request = self.factory.get(self.url, {"term": "question", **self.opts})
request.user = self.superuser
response = AutocompleteJsonSerializeResultView.as_view(**self.as_view_args)(
request
)
self.assertEqual(response.status_code, 200)
data = json.loads(response.text)
self.assertEqual(
data,
{
"results": [
{"id": str(q.pk), "text": q.question, "posted": str(q.posted)}
for q in Question.objects.order_by("-posted")
],
"pagination": {"more": False},
},
)
@override_settings(ROOT_URLCONF="admin_views.urls")
| AutocompleteJsonViewTests |
python | getsentry__sentry | src/flagpole/__init__.py | {
"start": 1999,
"end": 2334
} | class ____(Exception):
pass
@functools.cache
def load_json_schema() -> dict[str, Any]:
path = os.path.join(os.path.dirname(__file__), "flagpole-schema.json")
with open(path, "rb") as json_file:
data = orjson.loads(json_file.read())
return data
@dataclasses.dataclass(frozen=True)
| InvalidFeatureFlagConfiguration |
python | langchain-ai__langchain | libs/core/langchain_core/prompts/structured.py | {
"start": 715,
"end": 6005
} | class ____(ChatPromptTemplate):
"""Structured prompt template for a language model."""
schema_: dict | type
"""Schema for the structured prompt."""
structured_output_kwargs: dict[str, Any] = Field(default_factory=dict)
def __init__(
self,
messages: Sequence[MessageLikeRepresentation],
schema_: dict | type[BaseModel] | None = None,
*,
structured_output_kwargs: dict[str, Any] | None = None,
template_format: PromptTemplateFormat = "f-string",
**kwargs: Any,
) -> None:
"""Create a structured prompt template.
Args:
messages: sequence of messages.
schema_: schema for the structured prompt.
structured_output_kwargs: additional kwargs for structured output.
template_format: template format for the prompt.
"""
schema_ = schema_ or kwargs.pop("schema", None)
if not schema_:
err_msg = (
"Must pass in a non-empty structured output schema. Received: "
f"{schema_}"
)
raise ValueError(err_msg)
structured_output_kwargs = structured_output_kwargs or {}
for k in set(kwargs).difference(get_pydantic_field_names(self.__class__)):
structured_output_kwargs[k] = kwargs.pop(k)
super().__init__(
messages=messages,
schema_=schema_,
structured_output_kwargs=structured_output_kwargs,
template_format=template_format,
**kwargs,
)
@classmethod
def get_lc_namespace(cls) -> list[str]:
"""Get the namespace of the LangChain object.
For example, if the class is `langchain.llms.openai.OpenAI`, then the
namespace is `["langchain", "llms", "openai"]`
Returns:
The namespace of the LangChain object.
"""
return cls.__module__.split(".")
@classmethod
def from_messages_and_schema(
cls,
messages: Sequence[MessageLikeRepresentation],
schema: dict | type,
**kwargs: Any,
) -> ChatPromptTemplate:
"""Create a chat prompt template from a variety of message formats.
Examples:
Instantiation from a list of message templates:
```python
from langchain_core.prompts import StructuredPrompt
class OutputSchema(BaseModel):
name: str
value: int
template = StructuredPrompt(
[
("human", "Hello, how are you?"),
("ai", "I'm doing well, thanks!"),
("human", "That's good to hear."),
],
OutputSchema,
)
```
Args:
messages: Sequence of message representations.
A message can be represented using the following formats:
1. `BaseMessagePromptTemplate`
2. `BaseMessage`
3. 2-tuple of `(message type, template)`; e.g.,
`("human", "{user_input}")`
4. 2-tuple of `(message class, template)`
5. A string which is shorthand for `("human", template)`; e.g.,
`"{user_input}"`
schema: A dictionary representation of function call, or a Pydantic model.
**kwargs: Any additional kwargs to pass through to
`ChatModel.with_structured_output(schema, **kwargs)`.
Returns:
A structured prompt template
"""
return cls(messages, schema, **kwargs)
@override
def __or__(
self,
other: Runnable[Any, Other]
| Callable[[Iterator[Any]], Iterator[Other]]
| Callable[[AsyncIterator[Any]], AsyncIterator[Other]]
| Callable[[Any], Other]
| Mapping[str, Runnable[Any, Other] | Callable[[Any], Other] | Any],
) -> RunnableSerializable[dict, Other]:
return self.pipe(other)
def pipe(
self,
*others: Runnable[Any, Other]
| Callable[[Iterator[Any]], Iterator[Other]]
| Callable[[AsyncIterator[Any]], AsyncIterator[Other]]
| Callable[[Any], Other]
| Mapping[str, Runnable[Any, Other] | Callable[[Any], Other] | Any],
name: str | None = None,
) -> RunnableSerializable[dict, Other]:
"""Pipe the structured prompt to a language model.
Args:
others: The language model to pipe the structured prompt to.
name: The name of the pipeline.
Returns:
A RunnableSequence object.
Raises:
NotImplementedError: If the first element of `others`
is not a language model.
"""
if (others and isinstance(others[0], BaseLanguageModel)) or hasattr(
others[0], "with_structured_output"
):
return RunnableSequence(
self,
others[0].with_structured_output(
self.schema_, **self.structured_output_kwargs
),
*others[1:],
name=name,
)
msg = "Structured prompts need to be piped to a language model."
raise NotImplementedError(msg)
| StructuredPrompt |
python | getsentry__sentry | src/sentry/api/bases/organization.py | {
"start": 7098,
"end": 7311
} | class ____(OrganizationPermission):
scope_map = {
"GET": ["event:read", "event:write", "event:admin"],
"POST": ["event:read", "event:write", "event:admin"],
}
| OrganizationDataExportPermission |
python | dagster-io__dagster | examples/docs_projects/project_ml/src/project_ml/defs/types.py | {
"start": 395,
"end": 577
} | class ____(TypedDict):
test_accuracy: float
predictions: list[int]
labels: list[int]
classification_report: dict[str, Any]
model_info: dict[str, str]
| EvaluationResult |
python | getsentry__sentry | tests/sentry/integrations/github_enterprise/test_webhooks.py | {
"start": 697,
"end": 11263
} | class ____(APITestCase):
def setUp(self) -> None:
self.url = "/extensions/github-enterprise/webhook/"
self.metadata = {
"url": "35.232.149.196",
"id": "2",
"name": "test-app",
"webhook_secret": "b3002c3e321d4b7880360d397db2ccfd",
"private_key": "private_key",
"verify_ssl": True,
}
def test_get(self) -> None:
response = self.client.get(self.url)
assert response.status_code == 405
def test_unknown_host_event(self) -> None:
# No integration defined in the database, so event should be rejected
# because we can't find metadata and secret for it
response = self.client.post(
path=self.url,
data=PUSH_EVENT_EXAMPLE_INSTALLATION,
content_type="application/json",
HTTP_X_GITHUB_EVENT="push",
HTTP_X_GITHUB_ENTERPRISE_HOST="99.99.99.99",
HTTP_X_GITHUB_DELIVERY=str(uuid4()),
)
assert response.status_code == 400
def test_unregistered_event(self) -> None:
response = self.client.post(
path=self.url,
data=PUSH_EVENT_EXAMPLE_INSTALLATION,
content_type="application/json",
HTTP_X_GITHUB_EVENT="UnregisteredEvent",
HTTP_X_GITHUB_ENTERPRISE_HOST="35.232.149.196",
HTTP_X_HUB_SIGNATURE="sha1=56a3df597e02adbc17fb617502c70e19d96a6136",
HTTP_X_GITHUB_DELIVERY=str(uuid4()),
)
assert response.status_code == 204
@patch("sentry.integrations.github_enterprise.webhook.get_installation_metadata")
def test_missing_payload(self, mock_installation: MagicMock) -> None:
mock_installation.return_value = self.metadata
response = self.client.post(
path=self.url,
content_type="application/json",
HTTP_X_GITHUB_EVENT="push",
HTTP_X_GITHUB_ENTERPRISE_HOST="35.232.149.196",
HTTP_X_HUB_SIGNATURE="sha1=33521abeaaf9a57c2abf486e0ccd54d23cf36fec",
HTTP_X_GITHUB_DELIVERY=str(uuid4()),
)
assert response.status_code == 400
assert b"Webhook payload not found" in response.content
@patch("sentry.integrations.github_enterprise.webhook.get_installation_metadata")
def test_missing_github_event_header(self, mock_installation: MagicMock) -> None:
mock_installation.return_value = self.metadata
response = self.client.post(
path=self.url,
data=PUSH_EVENT_EXAMPLE_INSTALLATION,
content_type="application/json",
HTTP_X_GITHUB_ENTERPRISE_HOST="35.232.149.196",
HTTP_X_HUB_SIGNATURE="sha1=33521abeaaf9a57c2abf486e0ccd54d23cf36fec",
HTTP_X_GITHUB_DELIVERY=str(uuid4()),
)
assert response.status_code == 400
assert b"Missing X-GitHub-Event header" in response.content
@patch("sentry.integrations.github_enterprise.webhook.get_installation_metadata")
def test_invalid_json(self, mock_installation: MagicMock) -> None:
mock_installation.return_value = self.metadata
response = self.client.post(
path=self.url,
data=b'{"some_key": "value"', # missing closing bracket
content_type="application/json",
HTTP_X_GITHUB_ENTERPRISE_HOST="35.232.149.196",
HTTP_X_HUB_SIGNATURE="sha1=33521abeaaf9a57c2abf486e0ccd54d23cf36fec",
HTTP_X_GITHUB_DELIVERY=str(uuid4()),
)
assert response.status_code == 400
@patch("sentry.integrations.github_enterprise.webhook.get_installation_metadata")
def test_invalid_signature_event(self, mock_installation: MagicMock) -> None:
mock_installation.return_value = self.metadata
response = self.client.post(
path=self.url,
data=PUSH_EVENT_EXAMPLE_INSTALLATION,
content_type="application/json",
HTTP_X_GITHUB_EVENT="push",
HTTP_X_GITHUB_ENTERPRISE_HOST="35.232.149.196",
HTTP_X_HUB_SIGNATURE="sha1=33521abeaaf9a57c2abf486e0ccd54d23cf36fec",
HTTP_X_GITHUB_DELIVERY=str(uuid4()),
)
assert response.status_code == 401
assert b"Provided signature does not match the computed body signature" in response.content
@patch("sentry.integrations.github_enterprise.webhook.get_installation_metadata")
def test_malformed_signature_too_short_sha1(self, mock_installation: MagicMock) -> None:
mock_installation.return_value = self.metadata
response = self.client.post(
path=self.url,
data=PUSH_EVENT_EXAMPLE_INSTALLATION,
content_type="application/json",
HTTP_X_GITHUB_EVENT="push",
HTTP_X_GITHUB_ENTERPRISE_HOST="35.232.149.196",
HTTP_X_HUB_SIGNATURE="sha1=33521a2abfcf36fec", # hash is too short
HTTP_X_GITHUB_DELIVERY=str(uuid4()),
)
assert response.status_code == 400
assert b"Signature value does not match the expected format" in response.content
@patch("sentry.integrations.github_enterprise.webhook.get_installation_metadata")
def test_malformed_signature_no_value_sha1(self, mock_installation: MagicMock) -> None:
mock_installation.return_value = self.metadata
response = self.client.post(
path=self.url,
data=PUSH_EVENT_EXAMPLE_INSTALLATION,
content_type="application/json",
HTTP_X_GITHUB_EVENT="push",
HTTP_X_GITHUB_ENTERPRISE_HOST="35.232.149.196",
HTTP_X_HUB_SIGNATURE="sha1=",
HTTP_X_GITHUB_DELIVERY=str(uuid4()),
)
assert response.status_code == 400
assert b"Signature value does not match the expected format" in response.content
@patch("sentry.integrations.github_enterprise.webhook.get_installation_metadata")
def test_malformed_signature_too_short_sha256(self, mock_installation: MagicMock) -> None:
mock_installation.return_value = self.metadata
response = self.client.post(
path=self.url,
data=PUSH_EVENT_EXAMPLE_INSTALLATION,
content_type="application/json",
HTTP_X_GITHUB_EVENT="push",
HTTP_X_GITHUB_ENTERPRISE_HOST="35.232.149.196",
HTTP_X_HUB_SIGNATURE_256="sha256=33521a2abfcf36fec", # hash is too short
HTTP_X_GITHUB_DELIVERY=str(uuid4()),
)
assert response.status_code == 400
assert b"Signature value does not match the expected format" in response.content
@patch("sentry.integrations.github_enterprise.webhook.get_installation_metadata")
def test_malformed_signature_no_value_sha256(self, mock_installation: MagicMock) -> None:
mock_installation.return_value = self.metadata
response = self.client.post(
path=self.url,
data=PUSH_EVENT_EXAMPLE_INSTALLATION,
content_type="application/json",
HTTP_X_GITHUB_EVENT="push",
HTTP_X_GITHUB_ENTERPRISE_HOST="35.232.149.196",
HTTP_X_HUB_SIGNATURE_256="sha256=",
HTTP_X_GITHUB_DELIVERY=str(uuid4()),
)
assert response.status_code == 400
assert b"Signature value does not match the expected format" in response.content
@patch("sentry.integrations.github_enterprise.webhook.get_installation_metadata")
def test_sha256_signature_ok(self, mock_installation: MagicMock) -> None:
mock_installation.return_value = self.metadata
response = self.client.post(
path=self.url,
data=PUSH_EVENT_EXAMPLE_INSTALLATION,
content_type="application/json",
HTTP_X_GITHUB_EVENT="push",
HTTP_X_GITHUB_ENTERPRISE_HOST="35.232.149.196",
HTTP_X_HUB_SIGNATURE_256="sha256=7fb2fed663d2f386f29c1cff8980e11738a435b7e3c9332c1ab1fcc870f8964b",
HTTP_X_GITHUB_DELIVERY=str(uuid4()),
)
assert response.status_code == 204
@patch("sentry.integrations.github_enterprise.webhook.get_installation_metadata")
def test_sha256_signature_invalid(self, mock_installation: MagicMock) -> None:
mock_installation.return_value = self.metadata
response = self.client.post(
path=self.url,
data=PUSH_EVENT_EXAMPLE_INSTALLATION,
content_type="application/json",
HTTP_X_GITHUB_EVENT="push",
HTTP_X_GITHUB_ENTERPRISE_HOST="35.232.149.196",
HTTP_X_HUB_SIGNATURE_256="sha256=7fb2fed663d2f386f29c1cff8980e11738a435b7e3c9332c1ab1fcc870f8abcd",
HTTP_X_GITHUB_DELIVERY=str(uuid4()),
)
assert response.status_code == 401
assert b"Provided signature does not match the computed body signature" in response.content
@patch("sentry.integrations.github_enterprise.webhook.get_installation_metadata")
@override_options({"github-enterprise-app.allowed-hosts-legacy-webhooks": ["35.232.149.196"]})
def test_missing_signature_ok(self, mock_installation: MagicMock) -> None:
# Old Github:e doesn't send a signature, so we have to accept that, but only for specific hosts.
mock_installation.return_value = self.metadata
response = self.client.post(
path=self.url,
data=PUSH_EVENT_EXAMPLE_INSTALLATION,
content_type="application/json",
HTTP_X_GITHUB_EVENT="push",
HTTP_X_GITHUB_ENTERPRISE_HOST="35.232.149.196",
HTTP_X_GITHUB_DELIVERY=str(uuid4()),
)
assert response.status_code == 204
@patch("sentry.integrations.github_enterprise.webhook.get_installation_metadata")
def test_missing_signature_fail_without_option_set(self, mock_installation: MagicMock) -> None:
# Old Github:e doesn't send a signature, so we have to accept that, but only for specific hosts.
mock_installation.return_value = self.metadata
response = self.client.post(
path=self.url,
data=PUSH_EVENT_EXAMPLE_INSTALLATION,
content_type="application/json",
HTTP_X_GITHUB_EVENT="push",
HTTP_X_GITHUB_ENTERPRISE_HOST="35.232.149.196",
HTTP_X_GITHUB_DELIVERY=str(uuid4()),
)
assert response.status_code == 400
assert b"Missing headers X-Hub-Signature-256 or X-Hub-Signature" in response.content
@patch("sentry.integrations.github_enterprise.client.get_jwt")
@patch("sentry.integrations.github_enterprise.webhook.get_installation_metadata")
| WebhookTest |
python | pytorch__pytorch | torch/_inductor/fx_passes/overlap_scheduling.py | {
"start": 6035,
"end": 6456
} | class ____:
"""Track info about a collective operation"""
start_node: fx.Node
wait_node: fx.Node
size_bytes: int
estimated_time_ms: float
exposed_time_ms: float # How much of this collective is still exposed
hiding_nodes: OrderedSet[fx.Node] = field(default_factory=OrderedSet)
@property
def is_exposed(self) -> bool:
return self.exposed_time_ms != 0
@dataclass
| CollectiveInfo |
python | huggingface__transformers | src/transformers/models/patchtst/modeling_patchtst.py | {
"start": 12001,
"end": 14051
} | class ____(nn.Module):
"""
A class to patchify the time series sequence into different patches
Returns:
`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`
"""
def __init__(self, config: PatchTSTConfig):
super().__init__()
self.sequence_length = config.context_length
self.patch_length = config.patch_length
self.patch_stride = config.patch_stride
if self.sequence_length <= self.patch_length:
raise ValueError(
f"Sequence length ({self.sequence_length}) has to be greater than the patch length ({self.patch_length})"
)
# get the number of patches
self.num_patches = (max(self.sequence_length, self.patch_length) - self.patch_length) // self.patch_stride + 1
new_sequence_length = self.patch_length + self.patch_stride * (self.num_patches - 1)
self.sequence_start = self.sequence_length - new_sequence_length
def forward(self, past_values: torch.Tensor):
"""
Parameters:
past_values (`torch.Tensor` of shape `(batch_size, sequence_length, num_channels)`, *required*):
Input for patchification
Returns:
`torch.Tensor` of shape `(batch_size, num_channels, num_patches, patch_length)`
"""
sequence_length = past_values.shape[-2]
if sequence_length != self.sequence_length:
raise ValueError(
f"Input sequence length ({sequence_length}) doesn't match model configuration ({self.sequence_length})."
)
# output: [bs x new_sequence_length x num_channels]
output = past_values[:, self.sequence_start :, :]
# output: [bs x num_patches x num_input_channels x patch_length]
output = output.unfold(dimension=-2, size=self.patch_length, step=self.patch_stride)
# output: [bs x num_input_channels x num_patches x patch_length]
output = output.transpose(-2, -3).contiguous()
return output
| PatchTSTPatchify |
python | Textualize__textual | docs/examples/guide/css/nesting02.py | {
"start": 122,
"end": 479
} | class ____(App):
"""App with nested CSS."""
CSS_PATH = "nesting02.tcss"
def compose(self) -> ComposeResult:
with Horizontal(id="questions"):
yield Static("Yes", classes="button affirmative")
yield Static("No", classes="button negative")
if __name__ == "__main__":
app = NestingDemo()
app.run()
| NestingDemo |
python | PyCQA__pylint | tests/functional/u/unpacking/unpacking_non_sequence_py37.py | {
"start": 373,
"end": 486
} | class ____:
function: Callable[..., tuple[int, int]]
def update(self):
_, _ = self.function()
| Metric |
python | realpython__materials | thread-safety-locks/bank_deadlock.py | {
"start": 81,
"end": 1213
} | class ____:
def __init__(self):
self.balance = 0
self.lock = threading.Lock()
def deposit(self, amount):
print(
f"Thread {threading.current_thread().name} waiting "
"to acquire lock for deposit()"
)
with self.lock:
print(
f"Thread {threading.current_thread().name} acquired lock for deposit()"
)
time.sleep(0.1)
self._update_balance(amount)
def _update_balance(self, amount):
print(
f"Thread {threading.current_thread().name} waiting to acquire "
"lock for _update_balance()"
)
with self.lock: # This will cause a deadlock
print(
f"Thread {threading.current_thread().name} "
"acquired lock for _update_balance()"
)
self.balance += amount
account = BankAccount()
with ThreadPoolExecutor(
max_workers=3, thread_name_prefix="Worker"
) as executor:
for _ in range(3):
executor.submit(account.deposit, 100)
print(f"Final balance: {account.balance}")
| BankAccount |
python | pytorch__pytorch | torch/distributed/algorithms/ddp_comm_hooks/mixed_precision_hooks.py | {
"start": 218,
"end": 3254
} | class ____:
"""
State to manage DDP mixed precision in backward / gradient communication.
This contains a weakref to the DDP module for access to reducer and process
group, and a stream to run parameter and gradient upcasts.
"""
ddp_weakref: Any
upcast_stream: torch.Stream
wait_for_stream_enqueued: bool = False
@no_type_check
def _reducer_allreduce_and_upcast_hook(
hook_state: _AllreduceUpcastHookState, bucket: dist.GradBucket
) -> torch.futures.Future[torch.Tensor]:
"""
Perform allreduce in precision ``reduce_dtype``, upcast to prepare for optimizer.
Performs allreduce in the reduced precision given by DDP's mixed precision
reduce_dtype, and upcasts parameters and gradients to fp32 in preparation
to run the optimizer.
"""
ddp_weakref = hook_state.ddp_weakref
reducer, process_group = ddp_weakref().reducer, ddp_weakref().process_group
# Cast bucket if different than param_dtype.
if (
ddp_weakref().mixed_precision.param_dtype
!= ddp_weakref().mixed_precision.reduce_dtype
):
# Cast bucket tensor to reduce_dtype
bucket.set_buffer(
bucket.buffer().to(ddp_weakref().mixed_precision.reduce_dtype)
)
fut = reducer._run_allreduce_hook(bucket)
ret_fut = torch.futures.Future()
stream = hook_state.upcast_stream
with stream:
fut.wait()
bucket.buffer().div_(process_group.size())
ret_fut.set_result(bucket.buffer())
# Upcast parameters and gradients so optimizer step can run in fp32.
for p in bucket.parameters():
p.data = p._fp_param
# free storage for mp param as it will be allocated again in next
# forward pass.
_free_storage(p._mp_param)
p.grad.data = p.grad.to(p.data.dtype)
# enqueue a callback to wait for this stream at end of backward
def wait_for_stream_cb():
torch.accelerator.current_stream().wait_stream(stream)
# Remove post-backward hooks since they are re-installed in next
# iteration, similar to FSDP.
# Parameters that don't require grad still needed to be casted since
# they may participate in computation. However, they would not be recast
# by hook above as they don't have a grad hook installed, so cast them
# back here.
for _, p in ddp_weakref().module.named_parameters():
if hasattr(p, "_ddp_mp_hook_state"):
p._ddp_mp_hook_state[1].remove()
delattr(p, "_ddp_mp_hook_state")
if not p.requires_grad and not hasattr(p, "_ddp_ignored"):
p.data = p._fp_param
# reset for next backward pass
hook_state.wait_for_stream_enqueued = False
if not hook_state.wait_for_stream_enqueued:
Variable._execution_engine.queue_callback(wait_for_stream_cb)
# mark that the callback is enqueued
hook_state.wait_for_stream_enqueued = True
return ret_fut
| _AllreduceUpcastHookState |
python | getsentry__sentry | src/sentry/models/groupreaction.py | {
"start": 522,
"end": 3205
} | class ____(DefaultFieldsModel):
"""
This model has no affiliation with PullRequestComment.reactions.
This model represents feedback/evaluations related to a Group or an entity associated with a Group.
This model supports multiple patterns based on NULL combinations:
Suspect Commit Reactions:
- commit=commit_obj, group=group_obj: Reaction on specific commit for specific group
- commit=commit_obj, group=NULL: Commit excluded from suspicion on groups project-wide
- commit=NULL, group=group_obj: Group excluded from suspect commits entirely
"""
__relocation_scope__ = RelocationScope.Excluded
reaction = models.BooleanField()
project = FlexibleForeignKey("sentry.Project", on_delete=models.CASCADE)
group = FlexibleForeignKey("sentry.Group", null=True, on_delete=models.CASCADE)
commit = FlexibleForeignKey(
"sentry.Commit", null=True, on_delete=models.CASCADE, db_constraint=False
)
user_id = HybridCloudForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete="SET_NULL")
source = models.PositiveSmallIntegerField(
choices=(
(
GroupReactionType.USER_SUSPECT_COMMIT_REACTION.value,
"User Submitted Suspect Commit Reaction",
),
)
)
class Meta:
app_label = "sentry"
db_table = "sentry_groupreaction"
constraints = [
# Ensure at least one of commit or group is provided
models.CheckConstraint(
condition=~models.Q(commit__isnull=True, group__isnull=True),
name="commit_or_group_required",
),
# User reaction constraints: one reaction per user per context
models.UniqueConstraint(
fields=["project", "commit", "group", "user_id"],
condition=models.Q(
commit__isnull=False, group__isnull=False, user_id__isnull=False
),
name="unique_user_commit_group_reaction",
),
models.UniqueConstraint(
fields=["project", "commit", "user_id"],
condition=models.Q(commit__isnull=False, group__isnull=True, user_id__isnull=False),
name="unique_user_project_commit_reaction",
),
models.UniqueConstraint(
fields=["project", "group", "user_id"],
condition=models.Q(commit__isnull=True, group__isnull=False, user_id__isnull=False),
name="unique_user_group_exclusion_reaction",
),
]
__repr__ = sane_repr("project", "group", "commit", "user_id", "reaction", "source")
| GroupReaction |
python | sympy__sympy | sympy/plotting/pygletplot/plot.py | {
"start": 891,
"end": 11354
} | class ____:
"""
Plot Examples
=============
See examples/advanced/pyglet_plotting.py for many more examples.
>>> from sympy.plotting.pygletplot import PygletPlot as Plot
>>> from sympy.abc import x, y, z
>>> Plot(x*y**3-y*x**3)
[0]: -x**3*y + x*y**3, 'mode=cartesian'
>>> p = Plot()
>>> p[1] = x*y
>>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4)
>>> p = Plot()
>>> p[1] = x**2+y**2
>>> p[2] = -x**2-y**2
Variable Intervals
==================
The basic format is [var, min, max, steps], but the
syntax is flexible and arguments left out are taken
from the defaults for the current coordinate mode:
>>> Plot(x**2) # implies [x,-5,5,100]
[0]: x**2, 'mode=cartesian'
>>> Plot(x**2, [], []) # [x,-1,1,40], [y,-1,1,40]
[0]: x**2, 'mode=cartesian'
>>> Plot(x**2-y**2, [100], [100]) # [x,-1,1,100], [y,-1,1,100]
[0]: x**2 - y**2, 'mode=cartesian'
>>> Plot(x**2, [x,-13,13,100])
[0]: x**2, 'mode=cartesian'
>>> Plot(x**2, [-13,13]) # [x,-13,13,100]
[0]: x**2, 'mode=cartesian'
>>> Plot(x**2, [x,-13,13]) # [x,-13,13,10]
[0]: x**2, 'mode=cartesian'
>>> Plot(1*x, [], [x], mode='cylindrical')
... # [unbound_theta,0,2*Pi,40], [x,-1,1,20]
[0]: x, 'mode=cartesian'
Coordinate Modes
================
Plot supports several curvilinear coordinate modes, and
they independent for each plotted function. You can specify
a coordinate mode explicitly with the 'mode' named argument,
but it can be automatically determined for Cartesian or
parametric plots, and therefore must only be specified for
polar, cylindrical, and spherical modes.
Specifically, Plot(function arguments) and Plot[n] =
(function arguments) will interpret your arguments as a
Cartesian plot if you provide one function and a parametric
plot if you provide two or three functions. Similarly, the
arguments will be interpreted as a curve if one variable is
used, and a surface if two are used.
Supported mode names by number of variables:
1: parametric, cartesian, polar
2: parametric, cartesian, cylindrical = polar, spherical
>>> Plot(1, mode='spherical')
Calculator-like Interface
=========================
>>> p = Plot(visible=False)
>>> f = x**2
>>> p[1] = f
>>> p[2] = f.diff(x)
>>> p[3] = f.diff(x).diff(x)
>>> p
[1]: x**2, 'mode=cartesian'
[2]: 2*x, 'mode=cartesian'
[3]: 2, 'mode=cartesian'
>>> p.show()
>>> p.clear()
>>> p
<blank plot>
>>> p[1] = x**2+y**2
>>> p[1].style = 'solid'
>>> p[2] = -x**2-y**2
>>> p[2].style = 'wireframe'
>>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4)
>>> p[1].style = 'both'
>>> p[2].style = 'both'
>>> p.close()
Plot Window Keyboard Controls
=============================
Screen Rotation:
X,Y axis Arrow Keys, A,S,D,W, Numpad 4,6,8,2
Z axis Q,E, Numpad 7,9
Model Rotation:
Z axis Z,C, Numpad 1,3
Zoom: R,F, PgUp,PgDn, Numpad +,-
Reset Camera: X, Numpad 5
Camera Presets:
XY F1
XZ F2
YZ F3
Perspective F4
Sensitivity Modifier: SHIFT
Axes Toggle:
Visible F5
Colors F6
Close Window: ESCAPE
=============================
"""
@doctest_depends_on(modules=('pyglet',))
def __init__(self, *fargs, **win_args):
"""
Positional Arguments
====================
Any given positional arguments are used to
initialize a plot function at index 1. In
other words...
>>> from sympy.plotting.pygletplot import PygletPlot as Plot
>>> from sympy.abc import x
>>> p = Plot(x**2, visible=False)
...is equivalent to...
>>> p = Plot(visible=False)
>>> p[1] = x**2
Note that in earlier versions of the plotting
module, you were able to specify multiple
functions in the initializer. This functionality
has been dropped in favor of better automatic
plot plot_mode detection.
Named Arguments
===============
axes
An option string of the form
"key1=value1; key2 = value2" which
can use the following options:
style = ordinate
none OR frame OR box OR ordinate
stride = 0.25
val OR (val_x, val_y, val_z)
overlay = True (draw on top of plot)
True OR False
colored = False (False uses Black,
True uses colors
R,G,B = X,Y,Z)
True OR False
label_axes = False (display axis names
at endpoints)
True OR False
visible = True (show immediately
True OR False
The following named arguments are passed as
arguments to window initialization:
antialiasing = True
True OR False
ortho = False
True OR False
invert_mouse_zoom = False
True OR False
"""
# Register the plot modes
from . import plot_modes # noqa
self._win_args = win_args
self._window = None
self._render_lock = RLock()
self._functions = {}
self._pobjects = []
self._screenshot = ScreenShot(self)
axe_options = parse_option_string(win_args.pop('axes', ''))
self.axes = PlotAxes(**axe_options)
self._pobjects.append(self.axes)
self[0] = fargs
if win_args.get('visible', True):
self.show()
## Window Interfaces
def show(self):
"""
Creates and displays a plot window, or activates it
(gives it focus) if it has already been created.
"""
if self._window and not self._window.has_exit:
self._window.activate()
else:
self._win_args['visible'] = True
self.axes.reset_resources()
#if hasattr(self, '_doctest_depends_on'):
# self._win_args['runfromdoctester'] = True
self._window = PlotWindow(self, **self._win_args)
def close(self):
"""
Closes the plot window.
"""
if self._window:
self._window.close()
def saveimage(self, outfile=None, format='', size=(600, 500)):
"""
Saves a screen capture of the plot window to an
image file.
If outfile is given, it can either be a path
or a file object. Otherwise a png image will
be saved to the current working directory.
If the format is omitted, it is determined from
the filename extension.
"""
self._screenshot.save(outfile, format, size)
## Function List Interfaces
def clear(self):
"""
Clears the function list of this plot.
"""
self._render_lock.acquire()
self._functions = {}
self.adjust_all_bounds()
self._render_lock.release()
def __getitem__(self, i):
"""
Returns the function at position i in the
function list.
"""
return self._functions[i]
def __setitem__(self, i, args):
"""
Parses and adds a PlotMode to the function
list.
"""
if not (isinstance(i, (SYMPY_INTS, Integer)) and i >= 0):
raise ValueError("Function index must "
"be an integer >= 0.")
if isinstance(args, PlotObject):
f = args
else:
if (not is_sequence(args)) or isinstance(args, GeometryEntity):
args = [args]
if len(args) == 0:
return # no arguments given
kwargs = {"bounds_callback": self.adjust_all_bounds}
f = PlotMode(*args, **kwargs)
if f:
self._render_lock.acquire()
self._functions[i] = f
self._render_lock.release()
else:
raise ValueError("Failed to parse '%s'."
% ', '.join(str(a) for a in args))
def __delitem__(self, i):
"""
Removes the function in the function list at
position i.
"""
self._render_lock.acquire()
del self._functions[i]
self.adjust_all_bounds()
self._render_lock.release()
def firstavailableindex(self):
"""
Returns the first unused index in the function list.
"""
i = 0
self._render_lock.acquire()
while i in self._functions:
i += 1
self._render_lock.release()
return i
def append(self, *args):
"""
Parses and adds a PlotMode to the function
list at the first available index.
"""
self.__setitem__(self.firstavailableindex(), args)
def __len__(self):
"""
Returns the number of functions in the function list.
"""
return len(self._functions)
def __iter__(self):
"""
Allows iteration of the function list.
"""
return self._functions.itervalues()
def __repr__(self):
return str(self)
def __str__(self):
"""
Returns a string containing a new-line separated
list of the functions in the function list.
"""
s = ""
if len(self._functions) == 0:
s += "<blank plot>"
else:
self._render_lock.acquire()
s += "\n".join(["%s[%i]: %s" % ("", i, str(self._functions[i]))
for i in self._functions])
self._render_lock.release()
return s
def adjust_all_bounds(self):
self._render_lock.acquire()
self.axes.reset_bounding_box()
for f in self._functions:
self.axes.adjust_bounds(self._functions[f].bounds)
self._render_lock.release()
def wait_for_calculations(self):
sleep(0)
self._render_lock.acquire()
for f in self._functions:
a = self._functions[f]._get_calculating_verts
b = self._functions[f]._get_calculating_cverts
while a() or b():
sleep(0)
self._render_lock.release()
| PygletPlot |
python | mlflow__mlflow | mlflow/webhooks/types.py | {
"start": 9245,
"end": 9922
} | class ____(TypedDict):
"""Payload sent when an alias is created for a prompt version.
Example payload:
.. code-block:: python
{
"name": "example_prompt",
"alias": "example_alias",
"version": "1",
}
"""
name: str
"""The name of the prompt."""
alias: str
"""The alias being created."""
version: str
"""The version of the prompt the alias is being assigned to."""
@classmethod
def example(cls) -> "PromptAliasCreatedPayload":
return cls(
name="example_prompt",
alias="example_alias",
version="1",
)
| PromptAliasCreatedPayload |
python | nryoung__algorithms | algorithms/data_structures/queue.py | {
"start": 672,
"end": 1445
} | class ____:
def __init__(self):
self._queue = deque([])
def add(self, value):
"""
Add element as the last item in the Queue.
Worst Case Complexity: O(1)
"""
self._queue.append(value)
def remove(self):
"""
Remove element from the front of the Queue and return it's value.
Worst Case Complexity: O(1)
"""
return self._queue.popleft()
def is_empty(self):
"""
Returns a boolean indicating if the Queue is empty.
Worst Case Complexity: O(1)
"""
return not len(self._queue)
def size(self):
"""
Return size of the Queue.
Worst Case Complexity: O(1)
"""
return len(self._queue)
| Queue |
python | kamyu104__LeetCode-Solutions | Python/longest-fibonacci-subarray.py | {
"start": 37,
"end": 413
} | class ____(object):
def longestSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = cnt = 2
for i in xrange(2, len(nums)):
if nums[i] != nums[i-1]+nums[i-2]:
cnt = 2
continue
cnt += 1
result = max(result, cnt)
return result
| Solution |
python | pytorch__pytorch | test/distributed/_composable/test_replicate_with_compiler.py | {
"start": 13679,
"end": 16131
} | class ____(InductorTestCase):
def setUp(self):
# Hmm, why a specific set_device call for rank 0?
self.rank = 0
self.world_size = 4
torch.get_device_module(device_type).set_device(device_type)
store = FakeStore()
dist.init_process_group(
backend="fake",
world_size=self.world_size,
rank=self.rank,
store=store,
)
def tearDown(self):
dist.destroy_process_group()
@unittest.skip(
"Temporarily disabled due to SymInt error: `unhashable type: non-nested SymInt`"
)
@unittest.skipIf(not HAS_GPU, "Inductor+gpu needs triton and recent GPU arch")
def test_ddp_tp(self):
ref_model = Net()
compiled_replicate_model = deepcopy(ref_model)
mesh_2d = init_device_mesh(
device_type, (2, self.world_size // 2), mesh_dim_names=("dp", "tp")
)
tp_mesh = mesh_2d["tp"]
dp_mesh = mesh_2d["dp"]
parallelize_plan = {
"fc1": ColwiseParallel(),
"fc2": RowwiseParallel(),
"fc3": ColwiseParallel(),
"fc4": RowwiseParallel(),
}
ref_model = parallelize_module(ref_model, tp_mesh, parallelize_plan)
ref_model = replicate(ref_model, device_mesh=dp_mesh)
compiled_replicate_model = parallelize_module(
compiled_replicate_model, tp_mesh, parallelize_plan
)
compiled_replicate_model = replicate(
compiled_replicate_model, device_mesh=dp_mesh
)
compiled_replicate_model = torch.compile(compiled_replicate_model)
data = torch.randn([1, DIM])
with compiled_autograd._enable(compiler_fn()):
loss = compiled_replicate_model(data).sum()
# TODO: We need "pre-dispatch tracing of backward graph" to make this work:
# https://github.com/pytorch/pytorch/issues/127797#issuecomment-2291695474
with self.assertRaisesRegex(
AssertionError,
"Expected ProxyTensor, got <class 'torch.distributed.tensor.DTensor'>",
):
loss.backward()
# ref_loss = ref_model(data).sum()
# ref_loss.backward()
# for p1, p2 in zip(
# ref_model.parameters(), compiled_replicate_model.parameters()
# ):
# self.assertEqual(p1.grad, p2.grad)
if __name__ == "__main__":
run_tests()
| DDP_TP_Test |
python | huggingface__transformers | src/transformers/models/timm_wrapper/modeling_timm_wrapper.py | {
"start": 5645,
"end": 10641
} | class ____(TimmWrapperPreTrainedModel):
"""
Wrapper class for timm models to be used in transformers.
"""
def __init__(self, config: TimmWrapperConfig):
super().__init__(config)
# using num_classes=0 to avoid creating classification head
extra_init_kwargs = config.model_args or {}
self.features_only = extra_init_kwargs.get("features_only", False)
self.timm_model = _create_timm_model_with_error_handling(config, num_classes=0, **extra_init_kwargs)
self.post_init()
@auto_docstring
def forward(
self,
pixel_values: torch.FloatTensor,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[Union[bool, list[int]]] = None,
return_dict: Optional[bool] = None,
do_pooling: Optional[bool] = None,
**kwargs,
) -> Union[TimmWrapperModelOutput, tuple[Tensor, ...]]:
r"""
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. Not compatible with timm wrapped models.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. Not compatible with timm wrapped models.
do_pooling (`bool`, *optional*):
Whether to do pooling for the last_hidden_state in `TimmWrapperModel` or not. If `None` is passed, the
`do_pooling` value from the config is used.
Examples:
```python
>>> import torch
>>> from PIL import Image
>>> from urllib.request import urlopen
>>> from transformers import AutoModel, AutoImageProcessor
>>> # Load image
>>> image = Image.open(urlopen(
... 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png'
... ))
>>> # Load model and image processor
>>> checkpoint = "timm/resnet50.a1_in1k"
>>> image_processor = AutoImageProcessor.from_pretrained(checkpoint)
>>> model = AutoModel.from_pretrained(checkpoint).eval()
>>> # Preprocess image
>>> inputs = image_processor(image)
>>> # Forward pass
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # Get pooled output
>>> pooled_output = outputs.pooler_output
>>> # Get last hidden state
>>> last_hidden_state = outputs.last_hidden_state
```
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
do_pooling = do_pooling if do_pooling is not None else self.config.do_pooling
if output_attentions:
raise ValueError("Cannot set `output_attentions` for timm models.")
if output_hidden_states and not hasattr(self.timm_model, "forward_intermediates"):
raise ValueError(
"The 'output_hidden_states' option cannot be set for this timm model. "
"To enable this feature, the 'forward_intermediates' method must be implemented "
"in the timm model (available in timm versions > 1.*). Please consider using a "
"different architecture or updating the timm package to a compatible version."
)
pixel_values = pixel_values.to(self.device, self.dtype)
if self.features_only:
last_hidden_state = self.timm_model.forward(pixel_values, **kwargs)
hidden_states = last_hidden_state if output_hidden_states else None
pooler_output = None
else:
if output_hidden_states:
# to enable hidden states selection
if isinstance(output_hidden_states, (list, tuple)):
kwargs["indices"] = output_hidden_states
last_hidden_state, hidden_states = self.timm_model.forward_intermediates(pixel_values, **kwargs)
else:
last_hidden_state = self.timm_model.forward_features(pixel_values, **kwargs)
hidden_states = None
if do_pooling:
# classification head is not created, applying pooling only
pooler_output = self.timm_model.forward_head(last_hidden_state)
else:
pooler_output = None
if not return_dict:
outputs = (last_hidden_state, pooler_output, hidden_states)
outputs = tuple(output for output in outputs if output is not None)
return outputs
return TimmWrapperModelOutput(
last_hidden_state=last_hidden_state,
pooler_output=pooler_output,
hidden_states=hidden_states,
)
| TimmWrapperModel |
python | google__pytype | pytype/pytd/pytd.py | {
"start": 15072,
"end": 15193
} | class ____(Type):
"""A type we know nothing about yet (? in pytd)."""
def __bool__(self):
return True
| AnythingType |
python | openai__openai-python | src/openai/types/evals/create_eval_completions_run_data_source.py | {
"start": 1913,
"end": 3015
} | class ____(BaseModel):
type: Literal["stored_completions"]
"""The type of source. Always `stored_completions`."""
created_after: Optional[int] = None
"""An optional Unix timestamp to filter items created after this time."""
created_before: Optional[int] = None
"""An optional Unix timestamp to filter items created before this time."""
limit: Optional[int] = None
"""An optional maximum number of items to return."""
metadata: Optional[Metadata] = None
"""Set of 16 key-value pairs that can be attached to an object.
This can be useful for storing additional information about the object in a
structured format, and querying for objects via API or the dashboard.
Keys are strings with a maximum length of 64 characters. Values are strings with
a maximum length of 512 characters.
"""
model: Optional[str] = None
"""An optional model to filter by (e.g., 'gpt-4o')."""
Source: TypeAlias = Annotated[
Union[SourceFileContent, SourceFileID, SourceStoredCompletions], PropertyInfo(discriminator="type")
]
| SourceStoredCompletions |
python | pytorch__pytorch | torch/_inductor/codegen/cpp_gemm_template.py | {
"start": 25570,
"end": 73855
} | class ____(CppTemplate):
"""
GEMM Template for Inductor CPP Backend.
"""
def __init__(
self,
input_nodes,
layout: ir.Layout,
num_threads: int,
register_blocking: GemmBlocking,
beta=1,
alpha=1,
has_bias=False,
epilogue_creator: Optional[Callable[[ir.Buffer], ir.Pointwise]] = None,
should_block_weights: bool = True,
name="packed_gemm",
) -> None:
assert layout.dtype in [torch.float, torch.bfloat16, torch.half, torch.uint8]
super().__init__(
name,
input_nodes,
layout,
num_threads,
epilogue_creator=epilogue_creator,
)
self.beta = beta
self.alpha = alpha
self.has_bias = has_bias
self.register_blocking = register_blocking
m, n = layout.size[-2:]
k = input_nodes[0].get_size()[-1]
self.m, self.n, self.k = m, n, k
self.padded_n = get_padded_n(n, self.register_blocking.block_n)
self.is_dynamic_M = has_free_symbols((m,))
self.should_block_weights = should_block_weights
self.thread_blocking = self.make_thread_blocking_cache()
self.cache_blocking = self.make_cache_blocking_cache()
def make_thread_blocking_cache(self):
cache = lru_cache()(self._thread_blocking)
def thread_blocking(num_threads: int) -> GemmBlocking:
return cache(num_threads)
return thread_blocking
def _thread_blocking(self, num_threads: int) -> GemmBlocking:
"""
NOTE [Thread blocking in Cpp GEMM]
We use simple heuristics to decide the thread blocking:
1. Make sure all threads are occupied as much as possible.
2. For (m, n) blocks, favor more square-sized thread blocks for better data reuse.
3. If (m, n) blocks cannot occupy all the threads, we consider k-slicing.
TODO(jgong5): allow tuning various blocking options
"""
def get_factors(number):
factors = []
for i in range(int(number**0.5), 0, -1):
if number % i == 0:
factors.append(number // i)
factors.append(i)
return factors
def get_blocking(m_factor, n_factor, k_factor, m_blocks, n_blocks, k_blocks):
thread_block_k = math.ceil(k_blocks / k_factor)
thread_block_n = math.ceil(n_blocks / n_factor)
thread_block_m = math.ceil(m_blocks / m_factor)
return GemmBlocking(thread_block_m, thread_block_n, thread_block_k)
assert not self.is_dynamic_M, (
"Unable to determine thread blocking for dynamic M."
)
register_blocking = self.register_blocking
m_blocks = math.ceil(self.m / register_blocking.block_m)
n_blocks = math.ceil(self.n / register_blocking.block_n)
k_blocks = math.ceil(self.k / register_blocking.block_k)
factors = get_factors(num_threads)
assert len(factors) > 0
if config.cpp.gemm_thread_factors is not None:
factors = [int(i) for i in config.cpp.gemm_thread_factors.split(",")]
assert len(factors) == 3
assert math.prod(factors) == self.num_threads
return get_blocking(
factors[0], factors[1], factors[2], m_blocks, n_blocks, k_blocks
)
# we favor square-sized thread blocks for good data reuse
def get_better_blocking(blocking, best_blocking):
if best_blocking is None:
best_blocking = blocking
else:
block_m_size = blocking.block_m * register_blocking.block_m
block_n_size = blocking.block_n * register_blocking.block_n
best_block_m_size = best_blocking.block_m * register_blocking.block_m
best_block_n_size = best_blocking.block_n * register_blocking.block_n
if blocking.block_k > best_blocking.block_k:
best_blocking = blocking
elif (
blocking.block_k == best_blocking.block_k
and block_m_size + block_n_size
< best_block_m_size + best_block_n_size
):
best_blocking = blocking
return best_blocking
best_blocking = None
# check if we can have a thread-blocking to occupy all threads without k-slicing
for n_factor in factors:
m_factor = num_threads // n_factor
if n_blocks >= n_factor and m_blocks >= m_factor:
blocking = get_blocking(
m_factor, n_factor, 1, m_blocks, n_blocks, k_blocks
)
best_blocking = get_better_blocking(blocking, best_blocking)
if best_blocking is None:
for k_factor in factors:
if k_blocks >= k_factor and (
config.cpp.gemm_max_k_slices == 0
or k_factor <= config.cpp.gemm_max_k_slices
):
n_factors = get_factors(num_threads // k_factor)
for n_factor in n_factors:
m_factor = (num_threads // k_factor) // n_factor
if n_blocks >= n_factor and m_blocks >= m_factor:
blocking = get_blocking(
m_factor,
n_factor,
k_factor,
m_blocks,
n_blocks,
k_blocks,
)
best_blocking = get_better_blocking(blocking, best_blocking)
if best_blocking is None:
for n_factor in factors:
m_factor = num_threads // n_factor
if n_blocks >= n_factor or m_blocks >= m_factor:
blocking = get_blocking(
m_factor, n_factor, 1, m_blocks, n_blocks, k_blocks
)
best_blocking = get_better_blocking(blocking, best_blocking)
assert best_blocking is not None
return best_blocking
def make_cache_blocking_cache(self):
cache = lru_cache()(self._cache_blocking)
def cache_blocking(num_threads: int) -> GemmBlocking:
return cache(num_threads)
return cache_blocking
def _cache_blocking(self, num_threads: int) -> GemmBlocking:
def get_cache_blocking(register_blocking, thread_blocking):
Mr = register_blocking.block_m
Nr = register_blocking.block_n
Kr = register_blocking.block_k
Mt_blocks = thread_blocking.block_m
Nt_blocks = thread_blocking.block_n
Kt_blocks = thread_blocking.block_k
if config.cpp.gemm_cache_blocking is not None:
blockings = [int(i) for i in config.cpp.gemm_cache_blocking.split(",")]
assert len(blockings) == 3
Mc_blocks, Nc_blocks, Kc_blocks = blockings
return (
min(Mc_blocks, Mt_blocks),
min(Nc_blocks, Nt_blocks),
min(Kc_blocks, Kt_blocks),
)
# The ratios below are empirically determined to decide
# the effective sizes of L1 and L2.
# TODO: tune the factor here
L1_limit_factor = 0.8
L2_limit_factor = 0.5
L1_cache_size = (
torch._C._cpu._L1d_cache_size()
) # per core cache size in Bytes
assert L1_cache_size > 0, (
f"Expect L1_cache_size > 0 but got {L1_cache_size}"
)
L1 = L1_cache_size * L1_limit_factor
L2_cache_size = (
torch._C._cpu._L2_cache_size()
) # per core cache size in Bytes
assert L2_cache_size > 0, (
f"Expect L2_cache_size > 0 but got {L2_cache_size}"
)
L2 = L2_cache_size * L2_limit_factor
def get_num_byte(dtype):
return torch.tensor([], dtype=dtype).element_size()
dtype_A = self.input_nodes[0].get_dtype()
dtype_B = self.input_nodes[1].get_dtype()
num_byte_A = get_num_byte(dtype_A)
num_byte_B = get_num_byte(dtype_B)
if dtype_A is torch.bfloat16 and dtype_B is torch.int8 and Kr != 1:
# We will cache dequantized weights (BF16) in L1D for AMX micro-kernel.
# In this case, the choice of the micro-kernel being used can't be decoupled from
# the cache blocking.
# TODO: Decouple the choice of micro-kernel from cache blocking
num_byte_B *= num_byte_A
# NOTE [CPP GEMM Cache Blocking Algorithm]
# Our overall strategy is to
# 1) Make cache blocks of B L1-reside and reused by multiple rows of A, i.e. Mc.
# Here, B is Kc x Nr where Nr is a single register block. We use L1 size to
# decide Kc. We want to make Mc large enough to better reuse B.
# 2) Make cache blocks of A L2-reside, which would limit Mc. We want to reuse A
# along N, where we have two sub-strategies (see notes below) to decide Mc and Nc.
# Step 1: Decide Kc assuming B block is L1-reside.
size_cache_B = Kr * Kt_blocks * Nr * num_byte_B
Kc_blocks = Kt_blocks
if size_cache_B > L1:
Kc_blocks = math.floor(L1 / (Kr * Nr * num_byte_B))
if (
config.cpp.use_small_dequant_buffer
and dtype_A is torch.bfloat16
and Mt_blocks == 1
):
if dtype_B is torch.uint8:
# A16W4
# Make a small dequant_B buffer for woq int4 [q_group_size, Nr]
# Since when Mt_blocks == 1, L1-reside B block can't be reused by A.
if Kc_blocks * Kr >= self.q_group_size():
Kc_blocks = self.q_group_size() // Kr
elif dtype_B is torch.int8:
# A16W8
# Make A, B, C buffer in L1
A_buf_size_div_K = self.m * num_byte_A
B_buf_size_div_K = Nr * num_byte_B
# assume acc in float32/int32 and Mc_blocks = Nc_blocks = 1
C_buf_size = Mr * Nr * 4
K_block_size = (L1 - C_buf_size) // (
A_buf_size_div_K + B_buf_size_div_K
)
if Kc_blocks * Kr >= K_block_size:
Kc_blocks = (K_block_size + Kr - 1) // Kr
# Step 2: Decide Mc assuming A block is L2-reside.
min_Mc_ratio = 2 # TODO(jgong5): something to tune?
min_Mc_blocks = math.ceil(min_Mc_ratio * Mr / Nr)
assert min_Mc_blocks >= 1
Kt_bytes = Kt_blocks * Kr * num_byte_A
if min_Mc_blocks * Mr * Kt_bytes < L2:
# Strategy 1: A (Mc x Kt) resides in L2 and reused by all Nt
# when Nc_blocks is kept 1. Mc should be large enough (>= min_Mc_blocks)
# to reuse B (Kc x Nr) in L1. This makes C (Mc x Nr) small enough to reside
# in L1.
Mc_blocks = min(Mt_blocks, math.floor(L2 / (Mr * Kt_bytes)))
Nc_blocks = 1
else:
# Strategy 2: Kt is too large to hold A (Mc x Kt) in L2, we reuse
# A (Mc x Kc) in L2 by B (Kc x Nc). C (Mc x Nc) resides in L2.
Mc_blocks = Mt_blocks
Nc_blocks = min(math.ceil(Mc_blocks * Mr / Nr), Nt_blocks)
Nc_bytes = Nc_blocks * Nr * 4 # assume C or acc is float32/int32
Kc_bytes = Kc_blocks * Kr * num_byte_A
if Mc_blocks * Mr * (Kc_bytes + Nc_bytes) > L2:
# The following is the solution for 4*Mc*Nc + Mc*Kc_bytes = L2,
# assuming Mc == Nc for good data reuse.
M_max = (math.sqrt(Kc_bytes * Kc_bytes + 16 * L2) - Kc_bytes) / 8
if M_max < Mc_blocks * Mr:
Mc_blocks = math.floor(M_max / Mr)
Nc_blocks = min(math.ceil(Mc_blocks * Mr / Nr), Nt_blocks)
return Mc_blocks, Nc_blocks, Kc_blocks
assert not self.is_dynamic_M, (
"Unable to determine cache blocking for dynamic M."
)
register_blocking = self.register_blocking
thread_blocking = self.thread_blocking(num_threads)
return GemmBlocking(*get_cache_blocking(register_blocking, thread_blocking))
def log_blockings(self):
log.debug(f"Register blocking: {self.register_blocking}") # noqa: G004
if self.is_dynamic_M:
# thread and cache blockings are determined at runtime for dynamic shapes
return
log.debug(
f"Cache blocking: {self.cache_blocking(self.num_threads)}" # noqa: G004
)
thread_blocking = self.thread_blocking(self.num_threads)
log.debug(f"Thread blocking: {thread_blocking}") # noqa: G004
def get_occupancy():
m_blocks = math.ceil(self.m / self.register_blocking.block_m)
n_blocks = math.ceil(self.n / self.register_blocking.block_n)
k_blocks = math.ceil(self.k / self.register_blocking.block_k)
m = math.ceil(m_blocks / thread_blocking.block_m)
n = math.ceil(n_blocks / thread_blocking.block_n)
k = math.ceil(k_blocks / thread_blocking.block_k)
return (m, n, k)
log.debug(
f"Number of threads: {self.num_threads}, occupancy: {get_occupancy()}" # noqa: G004
)
def maybe_k_slicing(self):
if self.num_threads == 1:
return False
if self.is_dynamic_M:
# TODO(jgong5): perhaps use size hint to decide?
return True
register_blocking = self.register_blocking
k_blocks = math.ceil(self.k / register_blocking.block_k)
thread_blocking = self.thread_blocking(self.num_threads)
return k_blocks > thread_blocking.block_k
@classmethod
def add_choices(
cls,
choices,
layout,
input_nodes,
beta=1,
alpha=1,
has_bias=False,
trans_w=False,
input_indices=None,
epilogue_creator: Optional[Callable[[ir.Buffer], ir.Pointwise]] = None,
act_mapping: Optional[dict[int, ir.IRNode]] = None,
):
"""
Add choices for the GEMM template.
"""
# Fast path to save the epilogue calculation when x_scale/x_zp/w_scale are constant
use_int8_fast_compensation_path = _is_int8_gemm(input_nodes) and all(
(
isinstance(input_nodes[idx], ir.TensorBox)
and isinstance(input_nodes[idx].data.data, ir.ConstantBuffer)
)
for idx in [1, 2, 4]
)
if input_indices is None:
input_indices = list(range(len(input_nodes)))
def reorder_and_filter(inputs, layout_or_out):
if has_bias:
assert len(input_indices) >= 3
# Assume the input order is [inp, x, w] and we reorder it to [x, w, inp]
inp_idx = input_indices[0]
x_idx = input_indices[1]
w_idx = input_indices[2]
return [
inputs[x_idx],
inputs[w_idx],
inputs[inp_idx],
*[inputs[idx] for idx in input_indices[3:]],
], layout_or_out
elif len(inputs) >= len(input_indices):
assert len(input_indices) >= 2
return [inputs[idx] for idx in input_indices], layout_or_out
else:
# For when input is used for x and w, i.e. X@X.T or similar
# Assumes the first input is the only input
assert len(inputs) == 1
return [inputs[0]] * len(input_indices), layout_or_out
new_inputs, new_layout = reorder_and_filter(input_nodes, layout)
is_mkldnn_wgt = (
new_inputs[1].get_name() in V.graph.constants
and V.graph.constants[new_inputs[1].get_name()].is_mkldnn
)
if is_mkldnn_wgt:
# It shouldn't happen as viewing an mkldnn tensor, we can extend the
# implementation if it does.
assert not isinstance(new_inputs[1], ir.BaseView)
# Note that the layout of MKLDNN Tensor is with the wrong stride
view_size = new_inputs[1].layout.size
view_stride = new_inputs[1].layout.stride
view_offset = new_inputs[1].layout.offset
def maybe_to_dense(inputs, layout_or_out):
new_inputs = list(inputs)
if isinstance(inputs[1], torch.Tensor):
W = inputs[1]
new_inputs[1] = W.to_dense() if W.is_mkldnn else W
return new_inputs, layout_or_out
def normalize_shapes(inputs, layout_or_out):
new_inputs = list(inputs)
if not is_mkldnn_wgt and isinstance(new_inputs[1], torch.Tensor):
if has_free_symbols(view_size):
# If batch size B is dynamic, we need to set the batch size and possibly stride
assert not has_free_symbols(view_size[1:])
view_size[:] = V.graph.sizevars.size_hints(view_size)
view_stride[:] = V.graph.sizevars.size_hints(view_stride)
# With the assumptation that W is the storage of unwrap view
# thus view it back here
new_inputs[1] = new_inputs[1].as_strided(
view_size, view_stride, view_offset
)
if not trans_w:
return new_inputs, layout_or_out
X = new_inputs[0]
W = new_inputs[1]
B = new_inputs[2] if has_bias else None
W = transpose_w(W, trans_w)
B = expand_bias(B, X) # type:ignore[arg-type]
new_inputs[1] = W
if B is not None:
new_inputs[2] = B
return new_inputs, layout_or_out
# TODO(jgong5): decide proper number of threads per problem size
num_threads = parallel_num_threads()
new_inputs, _ = normalize_shapes(*maybe_to_dense(new_inputs, new_layout))
m, n, k, *_ = mm_args(
new_inputs[0],
new_inputs[1],
mat2_transposed=cls.is_woq_int4(),
use_4x2_dim=cls.is_woq_int4(),
)
output_dtype, compute_dtype = get_gemm_template_output_and_compute_dtype(
new_inputs[0].get_dtype()
)
micro_gemm = create_micro_gemm(
"micro_gemm",
m,
n,
k,
input_dtype=new_inputs[0].get_dtype(),
input2_dtype=new_inputs[1].get_dtype(),
output_dtype=output_dtype,
compute_dtype=compute_dtype,
alpha=alpha,
num_threads=num_threads,
use_ref=not cls.is_woq_int4(),
q_group_size=cls.q_group_size(),
)
assert micro_gemm is not None
pre_block_weights = cls.check_if_block_weight(new_inputs[1], micro_gemm)
micro_gemm.use_local_vnni_blocking(not pre_block_weights)
only_one_input = (
input_nodes[0] == input_nodes[1] if len(input_nodes) > 1 else False
) and not pre_block_weights # If weights are blocked, use the second input
def preprocessor(inputs, layout):
new_inputs, new_layout = normalize_shapes(
*maybe_to_dense(*reorder_and_filter(inputs, layout))
)
if only_one_input and isinstance(new_inputs[0], torch.Tensor):
return new_inputs[1:], new_layout
return cls.prep_weight(
new_inputs,
new_layout,
# pyrefly: ignore [bad-argument-type]
micro_gemm,
pre_block_weights,
use_int8_fast_compensation_path,
)
def postprocessor(output):
if isinstance(output, ir.TensorBox):
# prepack the weight as input to the template buffer
template_buffer = ir.InputsKernel.unwrap_storage_for_input(output)
assert isinstance(template_buffer, ir.CppTemplateBuffer)
new_input_nodes, _ = reorder_and_filter(input_nodes, layout)
W_node = new_input_nodes[1]
if W_node.get_name() not in V.graph.constants:
return output
W = V.graph.constants[W_node.get_name()]
new_input_nodes[1] = W
new_input_nodes, new_layout = normalize_shapes(
*maybe_to_dense(new_input_nodes, layout)
)
new_input_nodes, _ = cls.prep_weight(
new_input_nodes,
new_layout,
# pyrefly: ignore [bad-argument-type]
micro_gemm,
pre_block_weights,
use_int8_fast_compensation_path,
skip_int8_compensation=True,
)
W_packed = new_input_nodes[1]
W_packed_constant = V.graph.add_tensor_constant(W_packed)
new_input_nodes[1] = W_packed_constant
# Prune unused tensors
prune_tensors(input_nodes, new_input_nodes)
template_buffer.inputs[1] = ir.InputsKernel.unwrap_storage_for_input(
W_packed_constant
)
return output
template = DataProcessorTemplateWrapper(
cls,
preprocessor,
postprocessor,
input_nodes=input_nodes,
layout=layout,
num_threads=num_threads,
register_blocking=micro_gemm.register_blocking,
beta=beta,
alpha=alpha,
has_bias=has_bias,
epilogue_creator=epilogue_creator,
should_block_weights=pre_block_weights,
name=micro_gemm.__class__.__name__,
)
template.maybe_append_choice(choices)
return template
@staticmethod
def get_padded_size(n, block_n, k, should_block_weight):
padded_n = get_padded_n(n, block_n)
# We assume that all GEMM weight tensors should be blocked and padded
new_size = [padded_n // block_n, k, block_n]
return new_size, padded_n
@staticmethod
def _maybe_remove_storage_offset(node: ir.IRNode):
if node.get_layout().offset == 0:
return node
# node may be contiguous but still have a non-zero storage offset.
# GEMM_TEMPLATE emits code like:
# W.data_ptr[node.offset + ...]
# but runtime W.data_ptr (after normalize_shapes()) already includes this offset.
# To avoid double-offsetting, we remove the offset in the node also in the generated code.
# W.data_ptr[...]
return ir.ExternKernel.copy_input(node)
@classmethod
def prep_weight(
cls,
inputs,
layout: ir.Layout,
micro_gemm: CppMicroGemm,
should_block_weight: bool,
use_int8_fast_compensation_path: bool = False,
skip_int8_compensation: bool = False,
):
"""
NOTE Weight prep consists of 2 separate steps:
1. Blocking the weight tensor into a 3D shape: [n//block_n, k, block_n]
This is always done if the weight tensor is constant, i.e. for all GEMM and some BMM.
For BMM, we also block non-contiguous weight tensors, since they would be reshaped anyway.
This assumes that blocked, contiguous weights will be more efficient for the GEMM kernel,
and is worth the overhead of reshape and blocking.
This blocking includes additional padding, when n is not a multiple of block_n.
This padding allows a more efficient microkernel implementation. For BMM, this is only done
if reshape would happen anyway, i.e. if the weight tensor is constant, is not contiguous,
or is using AMX VNNI layout.
2. Packing the weight tensor into a VNNI-friendly shape. For constant input,
this is done at the same time as the weight blocking.
At compile time, the constant weight tensors are blocked and packed. For non-constant tensors (e.g. BMM)
which will be blocked (non-contiguous or VNNI-layout tensors), the weight tensor is blocked and packed at runtime.
CppBmmTemplate overrides the methods get_padded_size, and block_weight in order to accommodate
an additional dimension for the batch size and to determine if the weight tensor should be blocked.
"""
W = inputs[1]
new_inputs = list(inputs)
if cls.is_woq_int4():
assert (
len(W.get_size()) == 2
if isinstance(W, ir.IRNode)
else len(W.shape) == 2
)
n, k = W.get_size() if isinstance(W, ir.IRNode) else W.shape
else:
k, n = W.get_size()[-2:] if isinstance(W, ir.IRNode) else W.shape[-2:]
_, block_n, _ = micro_gemm.register_blocking
new_size, padded_n = cls.get_padded_size(n, block_n, k, should_block_weight)
padding = padded_n - n
if should_block_weight and not cls.is_woq_int4():
blocked_w = cls.block_weight(W, new_size, padding)
new_inputs[1] = cls.pack_vnni_weight(blocked_w, micro_gemm, new_size)
elif should_block_weight:
assert cls.is_woq_int4()
new_inputs[1] = cls.block_weight(W, new_size, padding)
elif isinstance(W, ir.IRNode):
# Require W layout to be fixed & contiguous, happens inplace.
ir.ExternKernel.require_contiguous(W)
new_inputs[1] = cls._maybe_remove_storage_offset(W)
if not skip_int8_compensation and _is_int8_gemm(new_inputs):
BCompensate = None
x_w_scale = None
def _get_compensation_node(W, use_int8_fast_compensation_path):
BCompensate = V.graph.add_tensor_constant(
V.graph.constants[W.get_name() + "_BMatrixCompens"],
W.get_name() + "_BMatrixCompens",
)
x_w_scale = None
if use_int8_fast_compensation_path:
x_w_scale = V.graph.add_tensor_constant(
V.graph.constants[W.get_name() + "_x_w_compens"],
W.get_name() + "_x_w_compens",
)
return BCompensate, x_w_scale
if use_int8_fast_compensation_path:
# new_inputs has been reordered: [x, w, optional[bias], x_scale, x_zp, w_scale, w_zp]
x_scale = new_inputs[-4]
x_zp = new_inputs[-3]
w_scale = new_inputs[-2]
if isinstance(W, ir.IRNode):
BCompensate, x_w_scale = _get_compensation_node(
W, use_int8_fast_compensation_path
)
else:
# Use the original W, not the blocked_w in new_inputs[1] to calculate BCompensate
BCompensate = torch.sum(W.to_dense().to(torch.float), dim=0) # type: ignore[assignment]
assert all(
isinstance(item, torch.Tensor)
for item in (x_scale, x_zp, w_scale)
)
BCompensate = BCompensate * x_scale * w_scale * x_zp
x_w_scale = x_scale * w_scale
new_inputs.append(BCompensate)
new_inputs.append(x_w_scale)
else:
if isinstance(W, ir.IRNode):
BCompensate, _ = _get_compensation_node(
W, use_int8_fast_compensation_path
)
else:
# Use the original W, not the blocked_w in new_inputs[1] to calculate BCompensate
BCompensate = torch.sum(W.to_dense().to(torch.float), dim=0) # type: ignore[assignment]
new_inputs.append(BCompensate)
return new_inputs, layout
@staticmethod
def check_if_block_weight(W, micro_gemm):
return True
@classmethod
def block_weight(cls, W, new_size, padding):
# These are separated into two methods to allow subclasses to override them separately
if isinstance(W, ir.IRNode):
if W.get_name() in V.graph.constants:
# Create a new buffer, representing the constant blocked tensor
blocked_w = ir.Buffer(
name=W.get_name(), # Borrow the registered buffer name
layout=ir.FixedLayout(
W.get_device_or_error(),
W.get_dtype(),
new_size,
ir.FlexibleLayout.contiguous_strides(new_size),
0,
),
)
else:
if not isinstance(W, ir.TensorBox):
W = ir.TensorBox(W)
permute_dims = list(range(len(new_size)))
permute_dims[-2], permute_dims[-3] = permute_dims[-3], permute_dims[-2]
permute_size = list(new_size)
permute_size[-2], permute_size[-3] = permute_size[-3], permute_size[-2]
blocked_w = L.constant_pad_nd(W, (0, padding))
blocked_w = L.permute(
L.view(blocked_w, permute_size), # type: ignore[arg-type]
permute_dims,
)
else:
assert isinstance(W, torch.Tensor)
# Pad the weight tensor and reshape it into a 3D blocked shape
blocked_size = list(new_size)
blocked_size[-2], blocked_size[-3] = blocked_size[-3], blocked_size[-2]
blocked_w = (
torch.nn.functional.pad(W, (0, padding)) # type: ignore[assignment]
.reshape(*blocked_size)
.transpose(-3, -2)
.contiguous()
)
return blocked_w
@classmethod
def pack_vnni_weight(cls, W, micro_gemm, new_size):
# WOQ INT4 weights are reordered in microkernel so do not pack them here
should_pack = (
micro_gemm.get_b_layout() != LayoutType.NORMAL
and not micro_gemm.is_woq_int4()
)
# These are separated into two methods to allow subclasses to override them separately
if isinstance(W, ir.IRNode):
if isinstance(W, ir.Buffer) and W.get_name() in V.graph.constants:
return W
k = new_size[-2]
if not isinstance(W, ir.TensorBox):
W = ir.TensorBox(W)
if should_pack:
permute_dims = list(range(len(new_size) + 1))
permute_dims[-1], permute_dims[-2] = permute_dims[-2], permute_dims[-1]
vnni_size = 4 if micro_gemm.get_b_layout() == LayoutType.VNNI4 else 2
vnni_view_size = list(new_size)
vnni_view_size[-2] = k // vnni_size
vnni_view_size.insert(-1, vnni_size)
W = L.view(
L.permute(L.view(W, vnni_view_size), permute_dims),
new_size,
)
W = ir.ExternKernel.realize_input(W)
W = ir.ExternKernel.require_contiguous(W)
return W
else:
k = new_size[-2]
# Apply VNNI packing to the weight tensor
if should_pack:
# TODO: Move VNNI weight packing for non-constant tensors into the template,
# to improve cache locality and avoid full-tensor copy.
layout_str = (
"VNNI4"
if micro_gemm.get_b_layout() == LayoutType.VNNI4
else "VNNI2"
)
assert micro_gemm.get_b_layout() in [
LayoutType.VNNI2,
LayoutType.VNNI4,
], f"We only support {layout_str} for now"
vnni_size = 4 if micro_gemm.get_b_layout() == LayoutType.VNNI4 else 2
assert k % vnni_size == 0, (
f"k should be divisible by vnni_size for {layout_str} layout"
)
vnni_view_size = list(new_size)
vnni_view_size[-2] = k // vnni_size
vnni_view_size.insert(-1, vnni_size)
W = W.view(vnni_view_size).transpose(-1, -2).contiguous().view(new_size)
# normalize stride to be "contiguous_strides" per size
# this avoids the problems in L.view during template codegen
new_stride = [1]
for sz in reversed(W.shape[1:]):
new_stride.insert(0, new_stride[0] * sz)
W = W.as_strided(W.shape, new_stride)
return W
def get_default_reindexers(self, epilogue_nodes):
return [None] * len(epilogue_nodes)
def get_options(
self,
kernel: CppTemplateKernel,
template_buffer_node: Optional[ir.CppTemplateBuffer] = None,
flag_template_buffer_has_other_users: Optional[bool] = None,
epilogue_nodes: Optional[list[ir.IRNode]] = None,
) -> dict[str, Any]:
assert len(self.input_nodes) >= 2
int8_gemm = self.input_nodes[0].get_dtype() in [torch.uint8, torch.int8]
x_scale = None
x_zp = None
w_scale = None
w_zp = None
inp = None
q_group_size_node = None
qscale_and_zeros = None
if int8_gemm:
X, W = self.input_nodes[0], self.input_nodes[1]
bias_idx = 2 if self.has_bias else 1
inp = self.input_nodes[bias_idx] if self.has_bias else None
x_scale = self.input_nodes[bias_idx + 1]
x_zp = self.input_nodes[bias_idx + 2]
w_scale = self.input_nodes[bias_idx + 3]
w_zp = self.input_nodes[bias_idx + 4]
Y = self.output_node
elif self.is_woq_int4():
X, W = self.input_nodes[0], self.input_nodes[1]
Y = self.output_node
q_group_size_node = self.input_nodes[2]
qscale_and_zeros = self.input_nodes[3]
else:
X, W = self.input_nodes[0], self.input_nodes[1]
Y = self.output_node
inp = self.input_nodes[2] if self.has_bias else None
template_buffer_has_other_users = None
if template_buffer_node is not None:
# Use the updated prepacked weight buffer
W = template_buffer_node.inputs[1]
Y = template_buffer_node
assert flag_template_buffer_has_other_users is not None
template_buffer_has_other_users = flag_template_buffer_has_other_users
template_buffer = Y
gemm_output_buffer = template_buffer
epilogues: list[ir.IRNode] = []
reindexers: list[Optional[Callable[[list[Any]], list[Any]]]] = []
epilogue_creators: list[Callable[[ir.Buffer], ir.Pointwise]] = []
fake_buffers: list[ir.Buffer] = []
Y_aliases: OrderedSet[str] = OrderedSet()
use_local_acc = (
self.layout.dtype != torch.float
or template_buffer_has_other_users
or int8_gemm
or self.padded_n != self.n
or self.maybe_k_slicing()
or (epilogue_nodes and epilogue_nodes[-1].get_dtype() != self.layout.dtype)
)
# TODO(jgong5): for int8 gemm, bias-add is handled outside of gemm template,
# but we'd better move it here to align with fp.
if inp is not None and self.beta != 0 and not int8_gemm:
# add an epilogue for bias add
def _bias_add_epilogue(buf):
return create_epilogue_with_attr(
buf, "bias_add", other=inp, beta=self.beta, dtype=self.layout.dtype
)
epilogue_creators.append(_bias_add_epilogue)
if self.epilogue_creator is not None:
epilogue_creators.append(self.epilogue_creator)
# When the GEMM output buffer is localized but it has users other than the epilogue nodes,
# we need to copy the value in the GEMM output local buffer to a global buffer.
def need_copy_from_local_to_global_buffer_epilogue(
use_local_acc, template_buffer_has_other_users, epilogue_creators
):
# The GEMM output buffer is a global buffer, thus copy is not needed.
if not use_local_acc:
return False
# The possible value of template_buffer_has_other_users is (None, False, True)
# It is None when generating the gemm template during autotune and it will have value during scheduler codegen.
# extra copy_from_local_to_global_buffer_epilogue is not needed in either of the below two cases:
# 1. template_buffer_has_other_users is None (i.e. when doing the codegen during autotune)
# 2. template_buffer_has_other_users is False, which means it's safe to keep the value in the
# GEMM output buffer in local buffer only (no users outside of the epilogues will use its value).
if not template_buffer_has_other_users:
return False
# When bias is not None or self.epilogue_creator is not None,
# there will be epilogue_creators after the GEMM.
# The GEMM output buffer is localized while
# the output buffer of the epilogue_creators is a global buffer.
if epilogue_creators:
return False
return True
if need_copy_from_local_to_global_buffer_epilogue(
use_local_acc, template_buffer_has_other_users, epilogue_creators
):
def copy_from_local_to_global_buffer_epilogue(input_buffer: ir.Buffer):
dtype = self.layout.dtype
input_loader = input_buffer.make_loader()
def copy_inner(index):
input = input_loader(index)
result = ops.to_dtype(input, dtype)
return result
return ir.Pointwise(
device=input_buffer.get_device_or_error(),
dtype=self.layout.dtype,
inner_fn=copy_inner,
ranges=input_buffer.get_size(),
)
epilogue_creators.append(copy_from_local_to_global_buffer_epilogue)
# NOTE [How CPP GEMM template epilogues are organized]
# gemm_output_buffer
# --> zero or more in-template epilogues (created by `epilogue_creators`) -->
# template_buffer
# --> zero or more out-of-template epilogues (`epilogue_nodes`) -->
# Y
if epilogue_creators:
assert isinstance(template_buffer, ir.IRNode)
gemm_output_name = f"{template_buffer.get_name()}_GemmOut"
gemm_output_buffer = ir.Buffer(
name=gemm_output_name,
# pyrefly: ignore [missing-attribute]
layout=template_buffer.layout,
)
current_input_buffer = gemm_output_buffer
for i, creator in enumerate(epilogue_creators):
if i == len(epilogue_creators) - 1:
buffer_name = template_buffer.get_name()
else:
buffer_name = f"{gemm_output_name}_epilogue_{i}"
epilogues.append(
ir.ComputedBuffer(
name=buffer_name,
# pyrefly: ignore [missing-attribute]
layout=template_buffer.layout,
data=creator(current_input_buffer),
)
)
fake_buffers.append(current_input_buffer)
Y_aliases.add(current_input_buffer.get_name())
reindexers.append(None)
if i < len(epilogue_creators) - 1:
current_input_buffer = ir.Buffer(
name=buffer_name,
# pyrefly: ignore [missing-attribute]
layout=template_buffer.layout,
)
assert isinstance(Y, (ir.Buffer, ir.ReinterpretView))
Y_2d: Union[ir.Buffer, ir.ReinterpretView] = Y
if epilogue_nodes:
if not template_buffer_has_other_users:
assert isinstance(template_buffer, ir.IRNode)
Y_aliases.add(template_buffer.get_name())
epilogues.extend(epilogue_nodes)
assert Y.get_numel() == epilogues[-1].get_numel()
Y = cast(ir.Buffer, epilogues[-1])
assert isinstance(template_buffer, ir.Buffer)
Y_2d, reindexers = gen_2d_view_of_epilogue_buf(
Y,
template_buffer,
epilogue_nodes,
reindexers,
default_reindexers=self.get_default_reindexers(epilogue_nodes),
)
output_dtype, compute_dtype = get_gemm_template_output_and_compute_dtype(
X.get_dtype()
)
micro_gemm = create_micro_gemm(
f"{kernel.kernel_name}_micro_gemm",
self.m,
self.n,
self.k,
input_dtype=X.get_dtype(),
# pyrefly: ignore [missing-attribute]
input2_dtype=W.get_dtype(),
output_dtype=output_dtype,
compute_dtype=compute_dtype,
alpha=self.alpha,
num_threads=self.num_threads,
use_ref=not self.is_woq_int4(),
q_group_size=self.q_group_size(),
)
assert micro_gemm is not None
micro_gemm.use_local_vnni_blocking(not self.should_block_weights)
assert self.register_blocking == micro_gemm.register_blocking
self.log_blockings()
if isinstance(micro_gemm, CppMicroGemmAMX):
counters["inductor"]["cpp_micro_gemm_amx_counter"] += 1
if isinstance(micro_gemm, CppMicroBrgemm):
counters["inductor"]["cpp_micro_brgemm_counter"] += 1
L1_cache_size = torch._C._cpu._L1d_cache_size() # per core cache size in Bytes
assert L1_cache_size > 0, f"Expect L1_cache_size > 0 but got {L1_cache_size}"
L2_cache_size = torch._C._cpu._L2_cache_size() # per core cache size in Bytes
assert L2_cache_size > 0, f"Expect L2_cache_size > 0 but got {L2_cache_size}"
options = dict(
X=X,
W=W,
inp=inp,
Y=Y,
N=self.n,
K=self.k,
PADDED_N=self.padded_n,
GemmOut=gemm_output_buffer,
aliases={alias: Y.get_name() for alias in Y_aliases},
beta=self.beta,
alpha=self.alpha,
num_threads=self.num_threads,
micro_gemm=micro_gemm,
is_dynamic_M=self.is_dynamic_M,
template=self,
kernel=kernel,
export_declaration=get_export_declaration(),
epilogue_nodes=epilogues,
reindexers=reindexers,
Y_2d=Y_2d,
use_local_acc=use_local_acc,
maybe_k_slicing=self.maybe_k_slicing(),
x_scale=x_scale,
x_zp=x_zp,
w_scale=w_scale,
w_zp=w_zp,
acc_buf_dtype=torch.int32 if int8_gemm else torch.float,
DTYPE_TO_CPP=DTYPE_TO_CPP,
L1_cache_size=L1_cache_size,
L2_cache_size=L2_cache_size,
config=config,
fake_buffers=fake_buffers,
is_woq_int4=self.is_woq_int4(),
q_group_size=q_group_size_node,
qscale_and_zeros=qscale_and_zeros,
)
return options
def is_int8_woq_gemm_small_m_dim(
self,
X: ir.ReinterpretView,
W: ir.ReinterpretView,
N,
K,
micro_gemm,
):
"""Use SMALL_M_GEMM_TEMPLATE"""
return (
isinstance(micro_gemm, CppMicroGemmFP32Vec)
and is_int8_woq_gemm_small_m_dim_corner_case(
micro_gemm, X.get_size()[0], N, K
)
and X.get_dtype() is torch.bfloat16
and W.get_dtype() is torch.int8
)
def render( # type: ignore[override, return]
self,
kernel: CppTemplateKernel,
template_buffer_node: Optional[ir.CppTemplateBuffer] = None,
flag_template_buffer_has_other_users: Optional[bool] = None,
epilogue_nodes: Optional[list[ir.IRNode]] = None,
**kwargs,
) -> str:
options = self.get_options(
kernel=kernel,
template_buffer_node=template_buffer_node,
flag_template_buffer_has_other_users=flag_template_buffer_has_other_users,
epilogue_nodes=epilogue_nodes,
)
self.render_options = options
with contextlib.ExitStack() as stack:
for buf in options["fake_buffers"]:
stack.enter_context(
patch.object(V.graph, "get_dtype", self._fake_get_dtype(buf))
)
if not options["is_dynamic_M"] and self.is_int8_woq_gemm_small_m_dim(
options["X"],
options["W"],
options["N"],
options["K"],
options["micro_gemm"],
):
template_str = SMALL_M_GEMM_TEMPLATE
else:
template_str = GEMM_TEMPLATE
return self._template_from_string(template_str).render(**options)
def codegen_blocks(
self,
num_threads,
N,
K,
micro_gemm,
is_dynamic_M,
kernel,
GemmOut,
config,
L1_cache_size,
L2_cache_size,
X,
W,
):
options = dict(
num_threads=num_threads,
N=N,
K=K,
micro_gemm=micro_gemm,
is_dynamic_M=is_dynamic_M,
kernel=kernel,
GemmOut=GemmOut,
config=config,
L1_cache_size=L1_cache_size,
L2_cache_size=L2_cache_size,
template=self,
X=X,
W=W,
is_woq_int4=self.is_woq_int4(),
)
template_str = GEMM_TEMPLATE_INIT_BLOCKING_BASIC_BLOCK
if not (
not is_dynamic_M
and self.is_int8_woq_gemm_small_m_dim(X, W, N, K, micro_gemm)
):
template_str += GEMM_TEMPLATE_INIT_BLOCKING_EXTENDED
return self._template_from_string(template_str).render(options)
def codegen_microkernel_def(self):
return self._template_from_string(GEMM_TEMPLATE_MICROKERNEL_DEF).render(
self.render_options
)
def codegen_gemm_stub_def(self):
microkernel = self.codegen_microkernel_def()
return microkernel + self._template_from_string(GEMM_TEMPLATE_STUB_DEF).render(
self.render_options
)
def codegen_multi_threads_params(self):
return self._template_from_string(GEMM_TEMPLATE_MULTI_THREADS_PARAMS).render()
def codegen_single_thread_params(self, is_dynamic_M):
options = dict(
is_dynamic_M=is_dynamic_M,
)
return self._template_from_string(GEMM_TEMPLATE_SINGLE_THREAD_PARAMS).render(
options
)
def codegen_m_loop_params(self):
return self._template_from_string(GEMM_TEMPLATE_M_LOOP_PARAMS).render()
def codegen_n_loop_params(self):
return self._template_from_string(GEMM_TEMPLATE_N_LOOP_PARAMS).render()
@classmethod
def is_woq_int4(cls):
return False
@classmethod
def q_group_size(cls):
return None
| CppGemmTemplate |
python | getsentry__sentry | src/sentry/conduit/auth.py | {
"start": 194,
"end": 2436
} | class ____(NamedTuple):
token: str
channel_id: str
url: str
def generate_channel_id() -> str:
"""Generate a unique channel ID for a Conduit stream."""
return str(uuid.uuid4())
def generate_conduit_token(
org_id: int,
channel_id: str,
issuer: str | None = None,
audience: str | None = None,
conduit_private_key: str | None = None,
) -> str:
"""
Generate a JWT token for Conduit authentication.
Optional parameters default to settings values if not provided.
Returns:
JWT token string
"""
if issuer is None:
issuer = settings.CONDUIT_GATEWAY_JWT_ISSUER
if audience is None:
audience = settings.CONDUIT_GATEWAY_JWT_AUDIENCE
if conduit_private_key is None:
conduit_private_key = settings.CONDUIT_GATEWAY_PRIVATE_KEY
if conduit_private_key is None:
raise ValueError("CONDUIT_GATEWAY_PRIVATE_KEY not configured")
try:
conduit_private_key_decoded = base64.b64decode(conduit_private_key).decode("utf-8")
except (binascii.Error, UnicodeDecodeError) as e:
raise ValueError("CONDUIT_GATEWAY_PRIVATE_KEY is not valid base64") from e
now = int(time.time())
exp = now + TOKEN_TTL_SEC
payload = {
"org_id": org_id,
"channel_id": channel_id,
"iat": now,
# Conduit only validates tokens on initial connection, not for stream lifetime
"exp": exp,
"iss": issuer,
"aud": audience,
}
return jwt.encode(payload, conduit_private_key_decoded, algorithm="RS256")
def get_conduit_credentials(
org_id: int,
gateway_url: str | None = None,
) -> ConduitCredentials:
"""
Generate all credentials needed to connect to Conduit.
Returns:
ConduitCredentials containing authentication details
"""
if gateway_url is None:
gateway_url = settings.CONDUIT_GATEWAY_URL
channel_id = generate_channel_id()
token = generate_conduit_token(org_id, channel_id)
metrics.incr(
"conduit.credentials.generated",
sample_rate=1.0,
)
return ConduitCredentials(
token=token,
channel_id=channel_id,
url=f"{gateway_url}/events/{org_id}",
)
| ConduitCredentials |
python | walkccc__LeetCode | solutions/3393. Count Paths With the Given XOR Value/3393.py | {
"start": 0,
"end": 613
} | class ____:
def countPathsWithXorValue(self, grid: list[list[int]], k: int) -> int:
MOD = 1_000_000_007
m = len(grid)
n = len(grid[0])
@functools.lru_cache(None)
def count(i: int, j: int, xors: int) -> int:
"""
Return the number of paths from (i, j) to (m - 1, n - 1) with XOR value
`xors`.
"""
if i == m or j == n:
return 0
xors ^= grid[i][j]
if i == m - 1 and j == n - 1:
return int(xors == k)
right = count(i, j + 1, xors)
down = count(i + 1, j, xors)
return (right + down) % MOD
return count(0, 0, 0)
| Solution |
python | getsentry__sentry | tests/sentry/monitors/endpoints/test_organization_monitor_details.py | {
"start": 301,
"end": 430
} | class ____(BaseUpdateMonitorTest):
endpoint = "sentry-api-0-organization-monitor-details"
__test__ = True
| UpdateMonitorTest |
python | mozilla__bleach | bleach/_vendor/html5lib/serializer.py | {
"start": 15682,
"end": 15759
} | class ____(Exception):
"""Error in serialized tree"""
pass
| SerializeError |
python | django-extensions__django-extensions | tests/test_autoslug_fields.py | {
"start": 740,
"end": 8185
} | class ____(TestCase):
def tearDown(self):
super().tearDown()
SluggedTestModel.objects.all().delete()
CustomFuncSluggedTestModel.objects.all().delete()
CustomFuncPrecedenceSluggedTestModel.objects.all().delete()
def test_auto_create_slug(self):
m = SluggedTestModel(title="foo")
m.save()
self.assertEqual(m.slug, "foo")
def test_auto_create_next_slug(self):
m = SluggedTestModel(title="foo")
m.save()
m = SluggedTestModel(title="foo")
m.save()
self.assertEqual(m.slug, "foo-2")
def test_auto_create_slug_with_number(self):
m = SluggedTestModel(title="foo 2012")
m.save()
self.assertEqual(m.slug, "foo-2012")
def test_auto_update_slug_with_number(self):
m = SluggedTestModel(title="foo 2012")
m.save()
m.save()
self.assertEqual(m.slug, "foo-2012")
def test_update_slug(self):
m = SluggedTestModel(title="foo")
m.save()
self.assertEqual(m.slug, "foo")
# update m instance without using `save'
SluggedTestModel.objects.filter(pk=m.pk).update(slug="foo-2012")
# update m instance with new data from the db
m = SluggedTestModel.objects.get(pk=m.pk)
self.assertEqual(m.slug, "foo-2012")
m.save()
self.assertEqual(m.title, "foo")
self.assertEqual(m.slug, "foo-2012")
# Check slug is not overwrite
m.title = "bar"
m.save()
self.assertEqual(m.title, "bar")
self.assertEqual(m.slug, "foo-2012")
def test_simple_slug_source(self):
m = SluggedTestModel(title="-foo")
m.save()
self.assertEqual(m.slug, "foo")
n = SluggedTestModel(title="-foo")
n.save()
self.assertEqual(n.slug, "foo-2")
n.save()
self.assertEqual(n.slug, "foo-2")
def test_empty_slug_source(self):
# regression test
m = SluggedTestModel(title="")
m.save()
self.assertEqual(m.slug, "-2")
n = SluggedTestModel(title="")
n.save()
self.assertEqual(n.slug, "-3")
n.save()
self.assertEqual(n.slug, "-3")
def test_callable_method_slug_source(self):
m = ModelMethodSluggedTestModel(title="-foo")
m.save()
self.assertEqual(m.slug, "the-title-is-foo")
n = ModelMethodSluggedTestModel(title="-foo")
n.save()
self.assertEqual(n.slug, "the-title-is-foo-2")
n.save()
self.assertEqual(n.slug, "the-title-is-foo-2")
def test_callable_function_slug_source(self):
m = FunctionSluggedTestModel(title="-foo")
m.save()
self.assertEqual(m.slug, "the-title-is-foo")
n = FunctionSluggedTestModel(title="-foo")
n.save()
self.assertEqual(n.slug, "the-title-is-foo-2")
n.save()
self.assertEqual(n.slug, "the-title-is-foo-2")
def test_inheritance_creates_next_slug(self):
m = SluggedTestModel(title="foo")
m.save()
n = ChildSluggedTestModel(title="foo")
n.save()
self.assertEqual(n.slug, "foo-2")
o = SluggedTestModel(title="foo")
o.save()
self.assertEqual(o.slug, "foo-3")
def test_foreign_key_populate_from_field(self):
m_fk = SluggedTestModel(title="foo")
m_fk.save()
m = FKSluggedTestModel(related_field=m_fk)
m.save()
self.assertEqual(m.slug, "foo")
def test_foreign_key_populate_from_callable(self):
m_fk = ModelMethodSluggedTestModel(title="foo")
m_fk.save()
m = FKSluggedTestModelCallable(related_field=m_fk)
m.save()
self.assertEqual(m.slug, "the-title-is-foo")
def test_copy_model_generates_new_slug(self):
m = SluggedTestModel(title="foo")
m.save()
self.assertEqual(m.slug, "foo")
m.pk = None
m.save()
self.assertEqual(m.slug, "foo-2")
def test_copy_model_generates_new_slug_no_overwrite_on_add(self):
m = SluggedTestNoOverwriteOnAddModel(title="foo")
m.save()
self.assertEqual(m.slug, "foo")
m.pk = None
m.slug = None
m.save()
self.assertEqual(m.slug, "foo-2")
def test_populate_from_does_not_allow_bytes(self):
with pytest.raises(TypeError):
AutoSlugField(populate_from=b"bytes")
with pytest.raises(TypeError):
AutoSlugField(populate_from=[b"bytes"])
def test_populate_from_must_allow_string_or_list_str_or_tuple_str(self):
AutoSlugField(populate_from="str")
AutoSlugField(populate_from=["str"])
AutoSlugField(populate_from=("str",))
def test_slug_argument_priority(self):
m = SluggedTestModel(slug="slug", title="title")
m.save()
self.assertEqual(m.slug, "title")
def test_slug_argument_priority_no_overwrite_on_add(self):
m = SluggedTestNoOverwriteOnAddModel(slug="slug", title="title")
m.save()
self.assertEqual(m.slug, "slug")
def test_overrided_find_unique_autoslug_field(self):
m = OverridedFindUniqueModel(title="foo")
slug_field = m._meta.fields[2]
self.assertFalse(hasattr(slug_field, "overrided"))
m.save()
slug_field = m._meta.fields[2]
self.assertTrue(slug_field.overrided)
def test_slugify_func(self):
to_upper = lambda c: c.upper()
to_lower = lambda c: c.lower()
content_n_func_n_expected = (
("test", to_upper, "TEST"),
("", to_upper, ""),
("TEST", to_lower, "test"),
)
for content, slugify_function, expected in content_n_func_n_expected:
self.assertEqual(
AutoSlugField.slugify_func(content, slugify_function), expected
)
def test_use_custom_slug_function(self):
m = CustomFuncSluggedTestModel(title="test")
m.save()
self.assertEqual(m.slug, "TEST")
def test_precedence_custom_slug_function(self):
m = CustomFuncPrecedenceSluggedTestModel(title="test")
m.save()
self.assertEqual(m.slug, "TEST")
self.assertTrue(hasattr(m._meta.get_field("slug"), "slugify_function"))
self.assertEqual(m._meta.get_field("slug").slugify_function("TEST"), "test")
def test_auto_create_slug_with_unique_together(self):
m = SluggedWithUniqueTogetherTestModel(
title="foo", category="self-introduction"
)
m.save()
self.assertEqual(m.slug, "foo")
m = SluggedWithUniqueTogetherTestModel(title="foo", category="review")
m.save()
self.assertEqual(m.slug, "foo")
# check if satisfy database integrity
m = SluggedWithUniqueTogetherTestModel(title="foo", category="review")
m.save()
self.assertEqual(m.slug, "foo-2")
def test_auto_create_slug_with_constraints(self):
m = SluggedWithConstraintsTestModel(title="foo", category="self-introduction")
m.save()
self.assertEqual(m.slug, "foo")
m = SluggedWithConstraintsTestModel(title="foo", category="review")
m.save()
self.assertEqual(m.slug, "foo")
# check if satisfy database integrity
m = SluggedWithConstraintsTestModel(title="foo", category="review")
m.save()
self.assertEqual(m.slug, "foo-2")
| AutoSlugFieldTest |
python | pennersr__django-allauth | allauth/socialaccount/providers/openid/migrations/0001_initial.py | {
"start": 43,
"end": 1643
} | class ____(migrations.Migration):
dependencies = []
operations = [
migrations.CreateModel(
name="OpenIDNonce",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("server_url", models.CharField(max_length=255)),
("timestamp", models.IntegerField()),
("salt", models.CharField(max_length=255)),
("date_created", models.DateTimeField(auto_now_add=True)),
],
options={},
bases=(models.Model,),
),
migrations.CreateModel(
name="OpenIDStore",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("server_url", models.CharField(max_length=255)),
("handle", models.CharField(max_length=255)),
("secret", models.TextField()),
("issued", models.IntegerField()),
("lifetime", models.IntegerField()),
("assoc_type", models.TextField()),
],
options={},
bases=(models.Model,),
),
]
| Migration |
python | scipy__scipy | scipy/sparse/linalg/_eigen/arpack/arpack.py | {
"start": 12741,
"end": 13029
} | class ____(RuntimeError):
"""
ARPACK error
"""
def __init__(self, info, infodict=None):
if infodict is None:
infodict = _NAUPD_ERRORS
msg = infodict.get(info, "Unknown error")
super().__init__(f"ARPACK error {info}: {msg}")
| ArpackError |
python | getsentry__sentry | src/sentry/notifications/notifications/organization_request/invite_request.py | {
"start": 373,
"end": 1447
} | class ____(AbstractInviteRequestNotification):
metrics_key = "invite_request"
template_path = "sentry/emails/organization-invite-request"
def get_specific_analytics_event(self, provider: ExternalProviders) -> analytics.Event | None:
"""
Returns the specific analytics event for the provider.
"""
return InviteRequestSentEvent(
organization_id=self.organization.id,
user_id=self.requester.id,
target_user_id=self.pending_member.id,
providers=provider.name.lower() if provider.name else "",
subtype=self.metrics_key,
invited_member_id=self.pending_member.id,
)
def build_attachment_title(self, recipient: Actor) -> str:
return "Request to Invite"
def get_message_description(self, recipient: Actor, provider: ExternalProviders) -> str:
requester_name = self.requester.get_display_name()
return f"{requester_name} is requesting to invite {self.pending_member.email} into {self.organization.name}"
| InviteRequestNotification |
python | cherrypy__cherrypy | cherrypy/lib/sessions.py | {
"start": 16221,
"end": 22261
} | class ____(Session):
"""Implementation of the file backend for sessions.
storage_path
The folder where session data will be saved. Each session
will be saved as pickle.dump(data, expiration_time) in its own file;
the filename will be self.SESSION_PREFIX + self.id.
lock_timeout
A timedelta or numeric seconds indicating how long
to block acquiring a lock. If None (default), acquiring a lock
will block indefinitely.
"""
SESSION_PREFIX = 'session-'
LOCK_SUFFIX = '.lock'
pickle_protocol = pickle.HIGHEST_PROTOCOL
def __init__(self, id=None, **kwargs):
"""Prepare the file session store."""
# The 'storage_path' arg is required for file-based sessions.
kwargs['storage_path'] = os.path.abspath(kwargs['storage_path'])
kwargs.setdefault('lock_timeout', None)
Session.__init__(self, id=id, **kwargs)
# validate self.lock_timeout
if isinstance(self.lock_timeout, (int, float)):
self.lock_timeout = datetime.timedelta(seconds=self.lock_timeout)
if not isinstance(self.lock_timeout, (datetime.timedelta, type(None))):
raise ValueError(
'Lock timeout must be numeric seconds '
'or a timedelta instance.',
)
@classmethod
def setup(cls, **kwargs):
"""Set up the storage system for file-based sessions.
This should only be called once per process; this will be done
automatically when using sessions.init (as the built-in Tool
does).
"""
# The 'storage_path' arg is required for file-based sessions.
kwargs['storage_path'] = os.path.abspath(kwargs['storage_path'])
for k, v in kwargs.items():
setattr(cls, k, v)
def _get_file_path(self):
f = os.path.join(self.storage_path, self.SESSION_PREFIX + self.id)
if not os.path.abspath(f).startswith(self.storage_path):
raise cherrypy.HTTPError(400, 'Invalid session id in cookie.')
return f
def _exists(self):
path = self._get_file_path()
return os.path.exists(path)
def _load(self, path=None):
assert self.locked, (
'The session load without being locked. '
"Check your tools' priority levels."
)
if path is None:
path = self._get_file_path()
try:
with open(path, 'rb') as f:
return pickle.load(f)
except (IOError, EOFError):
e = sys.exc_info()[1]
if self.debug:
cherrypy.log(
'Error loading the session pickle: %s' % e,
'TOOLS.SESSIONS',
)
return None
def _save(self, expiration_time):
assert self.locked, (
'The session was saved without being locked. '
"Check your tools' priority levels."
)
with open(self._get_file_path(), 'wb') as f:
pickle.dump((self._data, expiration_time), f, self.pickle_protocol)
def _delete(self):
assert self.locked, (
'The session deletion without being locked. '
"Check your tools' priority levels."
)
try:
os.unlink(self._get_file_path())
except OSError:
pass
def acquire_lock(self, path=None):
"""Acquire an exclusive lock on the currently-loaded session data."""
if path is None:
path = self._get_file_path()
path += self.LOCK_SUFFIX
checker = locking.LockChecker(self.id, self.lock_timeout)
while not checker.expired():
lock = FileLock(path)
timeout = 0.1
try:
lock.acquire(timeout=timeout)
self.lock = lock
break
except Timeout:
time.sleep(timeout)
self.locked = True
if self.debug:
cherrypy.log('Lock acquired.', 'TOOLS.SESSIONS')
def release_lock(self, path=None):
"""Release the lock on the currently-loaded session data."""
self.lock.release()
self.locked = False
def clean_up(self):
"""Clean up expired sessions."""
now = self.now()
# Iterate over all session files in self.storage_path
for fname in os.listdir(self.storage_path):
have_session = fname.startswith(
self.SESSION_PREFIX,
) and not fname.endswith(self.LOCK_SUFFIX)
if have_session:
# We have a session file: lock and load it and check
# if it's expired. If it fails, nevermind.
path = os.path.join(self.storage_path, fname)
self.acquire_lock(path)
if self.debug:
# This is a bit of a hack, since we're calling clean_up
# on the first instance rather than the entire class,
# so depending on whether you have "debug" set on the
# path of the first session called, this may not run.
cherrypy.log('Cleanup lock acquired.', 'TOOLS.SESSIONS')
try:
contents = self._load(path)
# _load returns None on IOError
if contents is not None:
data, expiration_time = contents
if expiration_time < now:
# Session expired: deleting it
os.unlink(path)
finally:
self.release_lock(path)
def __len__(self):
"""Return the number of active sessions."""
return len(
[
fname
for fname in os.listdir(self.storage_path)
if (
fname.startswith(self.SESSION_PREFIX)
and not fname.endswith(self.LOCK_SUFFIX)
)
],
)
| FileSession |
python | wandb__wandb | tests/unit_tests/test_step_prepare.py | {
"start": 7170,
"end": 10537
} | class ____:
@staticmethod
def _bg_prepare(
step_prepare: StepPrepare, *args, **kwargs
) -> "concurrent.futures.Future[ResponsePrepare]":
"""Starts prepare running in the background."""
enqueued = threading.Event()
future = concurrent.futures.Future()
def prepare_and_resolve():
q = step_prepare.prepare(*args, **kwargs)
enqueued.set()
future.set_result(q.get())
threading.Thread(
name="prepare_and_resolve",
target=prepare_and_resolve,
daemon=True,
).start()
enqueued.wait()
return future
def test_smoke(self):
caf_result = mock_create_artifact_files_result(["foo"])
api = Mock(create_artifact_files=Mock(return_value=caf_result))
step_prepare = StepPrepare(
api=api, batch_time=1e-12, inter_event_time=1e-12, max_batch_size=1
)
step_prepare.start()
res = self._bg_prepare(step_prepare, simple_file_spec(name="foo")).result()
step_prepare.finish()
upload_id = (
caf_result["foo"]["uploadMultipartUrls"]["uploadID"]
if caf_result["foo"]["uploadMultipartUrls"]
else None
)
assert res == ResponsePrepare(
birth_artifact_id=caf_result["foo"]["artifact"]["id"],
upload_url=caf_result["foo"]["uploadUrl"],
upload_headers=caf_result["foo"]["uploadHeaders"],
upload_id=upload_id,
storage_path=caf_result["foo"]["storagePath"],
multipart_upload_urls=caf_result["foo"]["uploadMultipartUrls"],
)
def test_batches_requests(self):
caf_result = mock_create_artifact_files_result(["a", "b"])
api = Mock(create_artifact_files=Mock(return_value=caf_result))
step_prepare = StepPrepare(
api=api, batch_time=1, inter_event_time=1, max_batch_size=10
)
step_prepare.start()
future_a = self._bg_prepare(step_prepare, simple_file_spec(name="a"))
future_b = self._bg_prepare(step_prepare, simple_file_spec(name="b"))
step_prepare.finish()
res_a = future_a.result()
res_b = future_b.result()
assert res_a.upload_url == caf_result["a"]["uploadUrl"]
assert res_b.upload_url == caf_result["b"]["uploadUrl"]
# make sure the URLs are different, just in case the fixture returns a constant
assert res_a.upload_url != res_b.upload_url
api.create_artifact_files.assert_called_once()
def test_finish_waits_for_pending_requests(self):
caf_result = mock_create_artifact_files_result(["a", "b"])
api = Mock(create_artifact_files=Mock(return_value=caf_result))
step_prepare = StepPrepare(
api=api, batch_time=1, inter_event_time=1, max_batch_size=10
)
step_prepare.start()
res_future = self._bg_prepare(step_prepare, simple_file_spec(name="a"))
with pytest.raises(concurrent.futures.TimeoutError):
res_future.result(timeout=0.2)
assert step_prepare.is_alive()
step_prepare.finish()
res = res_future.result(timeout=5)
assert res.upload_url == caf_result["a"]["uploadUrl"]
step_prepare._thread.join()
assert not step_prepare.is_alive()
| TestStepPrepare |
python | huggingface__transformers | src/transformers/models/x_clip/modeling_x_clip.py | {
"start": 2100,
"end": 4250
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
Contrastive loss for video-text similarity.
logits_per_video (`torch.FloatTensor` of shape `(video_batch_size, text_batch_size)`):
The scaled dot product scores between `video_embeds` and `text_embeds`. This represents the video-text
similarity scores.
logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, video_batch_size)`):
The scaled dot product scores between `text_embeds` and `video_embeds`. This represents the text-video
similarity scores.
text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
The text embeddings obtained by applying the projection layer to the pooled output of [`XCLIPTextModel`].
video_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
The video embeddings obtained by applying the projection layer to the pooled output of
[`XCLIPVisionModel`].
text_model_output (`BaseModelOutputWithPooling`):
The output of the [`XCLIPTextModel`].
vision_model_output (`BaseModelOutputWithPooling`):
The output of the [`XCLIPVisionModel`].
mit_output (`BaseModelOutputWithPooling`):
The output of `XCLIPMultiframeIntegrationTransformer` (MIT for short).
"""
loss: Optional[torch.FloatTensor] = None
logits_per_video: Optional[torch.FloatTensor] = None
logits_per_text: Optional[torch.FloatTensor] = None
text_embeds: Optional[torch.FloatTensor] = None
video_embeds: Optional[torch.FloatTensor] = None
text_model_output: BaseModelOutputWithPooling = None
vision_model_output: BaseModelOutputWithPooling = None
mit_output: BaseModelOutputWithPooling = None
def to_tuple(self) -> tuple[Any]:
return tuple(
self[k]
if k not in ["text_model_output", "vision_model_output", "mit_output"]
else getattr(self, k).to_tuple()
for k in self.keys()
)
# Copied from transformers.models.clip.modeling_clip.CLIPVisionEmbeddings with CLIP->XCLIP
| XCLIPOutput |
python | astropy__astropy | astropy/nddata/__init__.py | {
"start": 838,
"end": 1551
} | class ____(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.nddata`.
"""
warn_unsupported_correlated = _config.ConfigItem(
True,
"Whether to issue a warning if `~astropy.nddata.NDData` arithmetic "
"is performed with uncertainties and the uncertainties do not "
"support the propagation of correlated uncertainties.",
)
warn_setting_unit_directly = _config.ConfigItem(
True,
"Whether to issue a warning when the `~astropy.nddata.NDData` unit "
"attribute is changed from a non-``None`` value to another value "
"that data values/uncertainties are not scaled with the unit change.",
)
conf = Conf()
| Conf |
python | sanic-org__sanic | sanic/http/tls/creators.py | {
"start": 7907,
"end": 9542
} | class ____(CertCreator):
def check_supported(self) -> None:
if not TRUSTME_INSTALLED:
raise SanicException(
"Sanic is attempting to use trustme to generate local TLS "
"certificates since you did not supply a certificate, but "
"one is required. Sanic cannot proceed since trustme does not "
"appear to be installed. Alternatively, you can use mkcert. "
"Please install mkcert, trustme, or supply TLS certificates "
"to proceed. Installation instructions can be found here: "
"https://github.com/python-trio/trustme.\n"
"Find out more information about your options here: "
"https://sanic.dev/en/guide/deployment/development.html#"
"automatic-tls-certificate"
)
def generate_cert(self, localhost: str) -> ssl.SSLContext:
context = SanicSSLContext.create_from_ssl_context(
ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
)
context.sanic = {
"cert": self.cert_path.absolute(),
"key": self.key_path.absolute(),
}
ca = trustme.CA()
server_cert = ca.issue_cert(localhost)
server_cert.configure_cert(context)
ca.configure_trust(context)
ca.cert_pem.write_to_path(str(self.cert_path.absolute()))
server_cert.private_key_and_cert_chain_pem.write_to_path(
str(self.key_path.absolute())
)
context.sanic["creator"] = "trustme"
context.sanic["localhost"] = localhost
return context
| TrustmeCreator |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/auto_ml.py | {
"start": 26661,
"end": 28896
} | class ____(GoogleCloudBaseOperator):
"""
List an AutoML training job.
Can be used with AutoMLForecastingTrainingJob, AutoMLImageTrainingJob, AutoMLTabularTrainingJob,
AutoMLTextTrainingJob, or AutoMLVideoTrainingJob in a Location.
"""
template_fields = (
"region",
"project_id",
"impersonation_chain",
)
operator_extra_links = [
VertexAITrainingPipelinesLink(),
]
def __init__(
self,
*,
region: str,
project_id: str,
page_size: int | None = None,
page_token: str | None = None,
filter: str | None = None,
read_mask: str | None = None,
retry: Retry | _MethodDefault = DEFAULT,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.region = region
self.project_id = project_id
self.page_size = page_size
self.page_token = page_token
self.filter = filter
self.read_mask = read_mask
self.retry = retry
self.timeout = timeout
self.metadata = metadata
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
@property
def extra_links_params(self) -> dict[str, Any]:
return {
"project_id": self.project_id,
}
def execute(self, context: Context):
hook = AutoMLHook(
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.impersonation_chain,
)
results = hook.list_training_pipelines(
region=self.region,
project_id=self.project_id,
page_size=self.page_size,
page_token=self.page_token,
filter=self.filter,
read_mask=self.read_mask,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
VertexAITrainingPipelinesLink.persist(context=context)
return [TrainingPipeline.to_dict(result) for result in results]
| ListAutoMLTrainingJobOperator |
python | doocs__leetcode | solution/0000-0099/0078.Subsets/Solution.py | {
"start": 0,
"end": 350
} | class ____:
def subsets(self, nums: List[int]) -> List[List[int]]:
def dfs(i: int):
if i == len(nums):
ans.append(t[:])
return
dfs(i + 1)
t.append(nums[i])
dfs(i + 1)
t.pop()
ans = []
t = []
dfs(0)
return ans
| Solution |
python | getsentry__sentry | src/sentry/plugins/bases/issue2.py | {
"start": 3030,
"end": 17351
} | class ____(Plugin):
auth_provider: str | None = None
allowed_actions = ("create", "link", "unlink")
# we default this to None to support legacy integrations, but newer style
# should explicitly call out what is stored
issue_fields: frozenset[str] | None = None
# issue_fields = frozenset(['id', 'title', 'url'])
def get_plugin_type(self) -> str:
return "issue-tracking"
def has_project_conf(self) -> bool:
return True
def get_group_body(self, group, event, **kwargs):
result = []
for interface in event.interfaces.values():
output = safe_execute(interface.to_string, event)
if output:
result.append(output)
return "\n\n".join(result)
def get_group_description(self, group, event):
referrer = self.get_conf_key() + "_plugin"
output = [absolute_uri(group.get_absolute_url(params={"referrer": referrer}))]
body = self.get_group_body(group, event)
if body:
output.extend(["", "```", body, "```"])
return "\n".join(output)
def get_group_title(self, group, event):
return event.title
def is_configured(self, project) -> bool:
raise NotImplementedError
def get_group_urls(self):
_urls = []
for action in self.allowed_actions:
view_method_name = "view_%s" % action
_urls.append(
re_path(
rf"^{action}/",
PluginGroupEndpoint.as_view(view=getattr(self, view_method_name)),
name=f"sentry-api-0-plugins-{self.slug}-{action}",
)
)
return _urls
def get_auth_for_user(self, user, **kwargs) -> RpcUserSocialAuth | None:
"""
Return a ``RpcUserSocialAuth`` object for the given user based on this plugins ``auth_provider``.
"""
assert self.auth_provider, "There is no auth provider configured for this plugin."
if not user.is_authenticated:
return None
return usersocialauth_service.get_one_or_none(
filter={"user_id": user.id, "provider": self.auth_provider}
)
def needs_auth(self, request: Request, project, **kwargs):
"""
Return ``True`` if the authenticated user needs to associate an auth service before
performing actions with this plugin.
"""
if self.auth_provider is None:
return False
if not request.user.is_authenticated:
return True
auth = usersocialauth_service.get_one_or_none(
filter={"user_id": request.user.id, "provider": self.auth_provider}
)
return not bool(auth)
def get_new_issue_fields(self, request: Request, group, event, **kwargs):
"""
If overriding, supported properties include 'readonly': true
"""
return self._get_new_issue_fields_impl(group, event)
def _get_new_issue_fields_impl(self, group, event):
return [
{
"name": "title",
"label": "Title",
"default": self.get_group_title(group, event),
"type": "text",
},
{
"name": "description",
"label": "Description",
"default": self.get_group_description(group, event),
"type": "textarea",
},
]
def get_link_existing_issue_fields(self, request: Request, group, event, **kwargs):
return []
def get_issue_url(self, group, issue_id: str) -> str:
"""
Given an issue context (issue_id string) return an absolute URL to the issue's details
page.
"""
raise NotImplementedError
def get_issue_label(self, group, issue_id: str) -> str:
"""
Given an issue context (issue_id string) return a string representing the issue.
e.g. GitHub represents issues as GH-XXX
"""
return f"#{issue_id}"
def create_issue(self, request: Request, group, form_data):
"""
Creates the issue on the remote service and returns an issue ID.
Returns ``{'id': '1', 'title': issue_title}``
"""
raise NotImplementedError
def link_issue(self, request: Request, group, form_data, **kwargs):
"""
Can be overridden for any actions needed when linking issues
(like adding a comment to an existing issue).
Returns ``{'id': '1', 'title': issue_title}``
"""
def has_auth_configured(self, **kwargs):
if not self.auth_provider:
return True
return self.auth_provider in get_auth_providers()
def validate_form(self, fields, form_data):
errors = {}
for field in fields:
if field.get("required", True) and not field.get("readonly"):
value = form_data.get(field["name"])
if value is None or value == "":
errors[field["name"]] = "%s is a required field." % field["label"]
return errors
def get_issue_field_map(self):
# XXX(dcramer): legacy support
conf_key = self.get_conf_key()
if self.issue_fields is None:
return {"id": f"{conf_key}:tid"}
return {key: f"{conf_key}:issue_{key}" for key in self.issue_fields}
def build_issue(self, group):
issue_field_map = self.get_issue_field_map()
issue = {}
for key, meta_name in issue_field_map.items():
issue[key] = GroupMeta.objects.get_value(group, meta_name, None)
if not any(issue.values()):
return None
return issue
def has_linked_issue(self, group):
return bool(self.build_issue(group))
def unlink_issue(self, request: Request, group, issue, **kwargs):
issue_field_map = self.get_issue_field_map()
for meta_name in issue_field_map.values():
GroupMeta.objects.unset_value(group, meta_name)
return self.redirect(group.get_absolute_url())
def view_create(self, request: Request, group, **kwargs):
auth_errors = self.check_config_and_auth(request, group)
if auth_errors:
return Response(auth_errors, status=400)
event = group.get_latest_event()
if event is None:
return Response(
{
"message": "Unable to create issues: there are "
"no events associated with this group"
},
status=400,
)
try:
fields = self.get_new_issue_fields(request, group, event, **kwargs)
except Exception as e:
return self.handle_api_error(e)
if request.method == "GET":
return Response(fields)
errors = self.validate_form(fields, request.data)
if errors:
return Response({"error_type": "validation", "errors": errors}, status=400)
try:
issue = self.create_issue(group=group, form_data=request.data, request=request)
except Exception as e:
return self.handle_api_error(e)
if not isinstance(issue, dict):
issue = {"id": issue}
issue_field_map = self.get_issue_field_map()
for key, meta_name in issue_field_map.items():
if key in issue:
GroupMeta.objects.set_value(group, meta_name, issue[key])
else:
GroupMeta.objects.unset_value(group, meta_name)
issue_information = {
"title": issue.get("title")
or request.data.get("title")
or self._get_issue_label_compat(group, issue),
"provider": self.get_title(),
"location": self.get_issue_url(group, issue["id"]),
"label": self.get_issue_label(group, issue["id"]),
}
Activity.objects.create(
project=group.project,
group=group,
type=ActivityType.CREATE_ISSUE.value,
user_id=request.user.id,
data=issue_information,
)
try:
analytics.record(
IssueTrackerUsedEvent(
user_id=request.user.id,
default_user_id=group.project.organization.get_default_owner().id,
organization_id=group.project.organization_id,
project_id=group.project.id,
issue_tracker=self.slug,
)
)
except Exception as e:
sentry_sdk.capture_exception(e)
return Response(
{
"issue_url": self.get_issue_url(group, issue["id"]),
"link": self.get_issue_url(group, issue["id"]),
"label": self.get_issue_label(group, issue["id"]),
"id": issue["id"],
}
)
def view_link(self, request: Request, group, **kwargs):
auth_errors = self.check_config_and_auth(request, group)
if auth_errors:
return Response(auth_errors, status=400)
event = group.get_latest_event()
if event is None:
return Response(
{
"message": "Unable to create issues: there are "
"no events associated with this group"
},
status=400,
)
try:
fields = self.get_link_existing_issue_fields(request, group, event, **kwargs)
except Exception as e:
return self.handle_api_error(e)
if request.method == "GET":
return Response(fields)
errors = self.validate_form(fields, request.data)
if errors:
return Response({"error_type": "validation", "errors": errors}, status=400)
try:
issue = self.link_issue(group=group, form_data=request.data, request=request) or {}
except Exception as e:
return self.handle_api_error(e)
# HACK(dcramer): maintain data for legacy issues
if "id" not in issue and "issue_id" in request.data:
issue["id"] = request.data["issue_id"]
issue_field_map = self.get_issue_field_map()
for key, meta_name in issue_field_map.items():
if key in issue:
GroupMeta.objects.set_value(group, meta_name, issue[key])
else:
GroupMeta.objects.unset_value(group, meta_name)
issue_information = {
"title": issue.get("title") or self._get_issue_label_compat(group, issue),
"provider": self.get_title(),
"location": self.get_issue_url(group, issue["id"]),
"label": self.get_issue_label(group, issue["id"]),
}
Activity.objects.create(
project=group.project,
group=group,
type=ActivityType.CREATE_ISSUE.value,
user_id=request.user.id,
data=issue_information,
)
return Response(
{
"message": "Successfully linked issue.",
"link": self.get_issue_url(group, issue["id"]),
"label": self.get_issue_label(group, issue["id"]),
"id": issue["id"],
}
)
def view_unlink(self, request: Request, group, **kwargs):
auth_errors = self.check_config_and_auth(request, group)
if auth_errors:
return Response(auth_errors, status=400)
issue = self.build_issue(group)
if issue and "unlink" in self.allowed_actions:
self.unlink_issue(request, group, issue)
return Response({"message": "Successfully unlinked issue."})
return Response({"message": "No issues to unlink."}, status=400)
def plugin_issues(self, group, plugin_issues, **kwargs) -> None:
if not self.is_configured(project=group.project):
return
item: _PluginIssue = {
"slug": self.slug,
"allowed_actions": self.allowed_actions,
"title": self.get_title(),
}
issue = self.build_issue(group)
if issue:
item["issue"] = {
"issue_id": issue.get("id"),
"url": self.get_issue_url(group, issue["id"]),
"label": self.get_issue_label(group, issue["id"]),
}
item.update(serialize(self, serializer=PluginSerializer(group.project)))
plugin_issues.append(item)
def get_config(self, project, user=None, initial=None, add_additional_fields: bool = False):
# TODO(dcramer): update existing plugins to just use get_config
return self.get_configure_plugin_fields(
project=project, user=user, initial=initial, add_additional_fields=add_additional_fields
)
def check_config_and_auth(self, request: Request, group):
has_auth_configured = self.has_auth_configured()
if not (has_auth_configured and self.is_configured(project=group.project)):
if self.auth_provider:
required_auth_settings = settings.AUTH_PROVIDERS[self.auth_provider]
else:
required_auth_settings = None
return {
"error_type": "config",
"has_auth_configured": has_auth_configured,
"auth_provider": self.auth_provider,
"required_auth_settings": required_auth_settings,
}
if self.needs_auth(project=group.project, request=request):
return {
"error_type": "auth",
"auth_url": absolute_uri(
reverse("socialauth_associate", args=[self.auth_provider])
),
}
# TODO: should we get rid of this (move it to react?)
def tags(self, request: Request, group, tag_list, **kwargs):
if not self.is_configured(project=group.project):
return tag_list
issue = self.build_issue(group)
if not issue:
return tag_list
tag_list.append(
{
"url": self.get_issue_url(group, issue["id"]),
"displayName": self.get_issue_label(group, issue["id"]),
}
)
return tag_list
IssuePlugin2 = IssueTrackingPlugin2
| IssueTrackingPlugin2 |
python | jazzband__pip-tools | piptools/resolver.py | {
"start": 19485,
"end": 32056
} | class ____(BaseResolver):
"""A wrapper for the backtracking (or 2020) resolver."""
def __init__(
self,
constraints: Iterable[InstallRequirement],
existing_constraints: dict[str, InstallRequirement],
repository: BaseRepository,
allow_unsafe: bool = False,
unsafe_packages: set[str] | None = None,
**kwargs: _t.Any,
) -> None:
self.constraints = list(constraints)
self.repository = repository
self.allow_unsafe = allow_unsafe
self.unsafe_packages = unsafe_packages or UNSAFE_PACKAGES
options = self.options = self.repository.options
self.session = self.repository.session
self.finder = self.repository.finder
self.command = self.repository.command
self.unsafe_constraints: set[InstallRequirement] = set()
self.existing_constraints = existing_constraints
# Categorize InstallRequirements into sets by key
constraints_sets: collections.defaultdict[str, set[InstallRequirement]] = (
collections.defaultdict(set)
)
for ireq in constraints:
constraints_sets[key_from_ireq(ireq)].add(ireq)
# Collapse each set of InstallRequirements using combine_install_requirements
self._constraints_map = {
ireq_key: combine_install_requirements(ireqs)
for ireq_key, ireqs in constraints_sets.items()
}
# Make sure there is no enabled legacy resolver
options.deprecated_features_enabled = omit_list_value(
options.deprecated_features_enabled, "legacy-resolver"
)
def resolve(self, max_rounds: int = 10) -> set[InstallRequirement]:
r"""
Resolve given ireqs.
Find concrete package versions for all the given InstallRequirements
and their recursive dependencies.
:returns: A set of pinned ``InstallRequirement``\ s.
"""
with (
update_env_context_manager(PIP_EXISTS_ACTION="i"),
get_build_tracker() as build_tracker,
global_tempdir_manager(),
indent_log(),
):
# Mark direct/primary/user_supplied packages
for ireq in self.constraints:
if ireq.constraint:
ireq.extras = set() # pip does not support extras in constraints
ireq.user_supplied = True
# Pass compiled requirements from `requirements.txt`
# as constraints to resolver
compatible_existing_constraints: dict[str, InstallRequirement] = {}
for ireq in self.existing_constraints.values():
# Skip if the compiled install requirement conflicts with
# the primary install requirement.
primary_ireq = self._constraints_map.get(key_from_ireq(ireq))
if primary_ireq is not None:
_, version, _ = as_tuple(ireq)
prereleases = ireq.specifier.prereleases
if not primary_ireq.specifier.contains(version, prereleases):
continue
ireq.extras = set()
ireq.constraint = True
ireq.user_supplied = False
compatible_existing_constraints[key_from_ireq(ireq)] = ireq
wheel_cache = create_wheel_cache(
cache_dir=self.options.cache_dir,
format_control=self.options.format_control,
)
temp_dir = TempDirectory(
delete=not self.options.no_clean,
kind="resolve",
globally_managed=True,
)
preparer_kwargs = {
"temp_build_dir": temp_dir,
"options": self.options,
"session": self.session,
"finder": self.finder,
"use_user_site": False,
"build_tracker": build_tracker,
}
preparer = self.command.make_requirement_preparer(**preparer_kwargs)
extra_resolver_kwargs = {}
if PIP_VERSION[:2] < (25, 3): # pragma: <3.9 cover
# Ref: https://github.com/jazzband/pip-tools/issues/2252
extra_resolver_kwargs["use_pep517"] = self.options.use_pep517
resolver = self.command.make_resolver(
preparer=preparer,
finder=self.finder,
options=self.options,
wheel_cache=wheel_cache,
use_user_site=False,
ignore_installed=True,
ignore_requires_python=False,
force_reinstall=False,
upgrade_strategy="to-satisfy-only",
**extra_resolver_kwargs,
)
self.command.trace_basic_info(self.finder)
for current_round in count(start=1): # pragma: no branch
if current_round > max_rounds:
raise RuntimeError(
"No stable configuration of concrete packages "
"could be found for the given constraints after "
f"{max_rounds} rounds of resolving.\n"
"This is likely a bug."
)
log.debug("")
log.debug(magenta(f"{f'ROUND {current_round}':^60}"))
is_resolved = self._do_resolve(
resolver=resolver,
compatible_existing_constraints=compatible_existing_constraints,
)
if is_resolved:
break
resolver_result = resolver._result
assert isinstance(resolver_result, Result)
# Prepare set of install requirements from resolver result.
result_ireqs = self._get_install_requirements(resolver_result=resolver_result)
# Filter out unsafe requirements.
if not self.allow_unsafe:
self._filter_out_unsafe_constraints(
ireqs=result_ireqs,
unsafe_packages=self.unsafe_packages,
)
return result_ireqs
def _do_resolve(
self,
resolver: Resolver,
compatible_existing_constraints: dict[str, InstallRequirement],
) -> bool:
"""
Resolve dependencies based on resolvelib ``Resolver``.
:returns: :py:data:`True` on successful resolution, otherwise removes
problematic requirements from existing constraints and
returns :py:data:`False`.
"""
try:
resolver.resolve(
root_reqs=self.constraints
+ list(compatible_existing_constraints.values()),
check_supported_wheels=not self.options.target_dir,
)
except DistributionNotFound as e:
cause_exc = e.__cause__
if cause_exc is None:
raise
if not isinstance(cause_exc, ResolutionImpossible):
raise
# Collect all incompatible install requirement names
cause_ireq_names = {
strip_extras(key_from_req(cause.requirement))
for cause in cause_exc.causes
}
# Looks like resolution is impossible, try to fix
for cause_ireq_name in cause_ireq_names:
# Find the cause requirement in existing requirements,
# otherwise raise error
cause_existing_ireq = compatible_existing_constraints.get(
cause_ireq_name
)
if cause_existing_ireq is None:
raise
# Remove existing incompatible constraint that causes error
log.warning(
f"Discarding {cause_existing_ireq} to proceed the resolution"
)
del compatible_existing_constraints[cause_ireq_name]
return False
return True
def _get_install_requirements(
self, resolver_result: Result
) -> set[InstallRequirement]:
"""Return a set of install requirements from resolver results."""
result_ireqs: dict[str, InstallRequirement] = {}
# Get reverse requirements from the resolver result graph.
reverse_dependencies = self._get_reverse_dependencies(resolver_result)
# Transform candidates to install requirements
resolved_candidates = tuple(resolver_result.mapping.values())
for candidate in resolved_candidates:
ireq = self._get_install_requirement_from_candidate(
candidate=candidate,
reverse_dependencies=reverse_dependencies,
)
if ireq is None:
continue
project_name = canonicalize_name(candidate.project_name)
result_ireqs[project_name] = ireq
# Merge extras to install requirements
extras_candidates = (
candidate
for candidate in resolved_candidates
if isinstance(candidate, ExtrasCandidate)
)
for extras_candidate in extras_candidates:
project_name = canonicalize_name(extras_candidate.project_name)
ireq = result_ireqs[project_name]
ireq.extras |= extras_candidate.extras
ireq.req.extras |= extras_candidate.extras
return set(result_ireqs.values())
@staticmethod
def _get_reverse_dependencies(
resolver_result: Result,
) -> dict[str, set[str]]:
reverse_dependencies: collections.defaultdict[str, set[str]] = (
collections.defaultdict(set)
)
for candidate in resolver_result.mapping.values():
stripped_name = strip_extras(canonicalize_name(candidate.name))
for parent_name in resolver_result.graph.iter_parents(candidate.name):
# Skip root dependency which is always None
if parent_name is None:
continue
# Skip a dependency that equals to the candidate. This could be
# the dependency with extras.
stripped_parent_name = strip_extras(canonicalize_name(parent_name))
if stripped_name == stripped_parent_name:
continue
reverse_dependencies[stripped_name].add(stripped_parent_name)
return dict(reverse_dependencies)
def _get_install_requirement_from_candidate(
self, candidate: Candidate, reverse_dependencies: dict[str, set[str]]
) -> InstallRequirement | None:
ireq = candidate.get_install_requirement()
if ireq is None:
return None
# Determine a pin operator
version_pin_operator = "=="
version_as_str = str(candidate.version)
for specifier in ireq.specifier:
if specifier.operator == "===" and specifier.version == version_as_str:
version_pin_operator = "==="
break
# Prepare pinned install requirement. Copy it from candidate's install
# requirement so that it could be mutated later.
pinned_ireq = copy_install_requirement(
template=ireq,
# The link this candidate "originates" from. This is different
# from ``ireq.link`` when the link is found in the wheel cache.
# ``ireq.link`` would point to the wheel cache, while this points
# to the found remote link (e.g. from pypi.org).
link=candidate.source_link,
)
# Canonicalize name
assert ireq.name is not None
pinned_ireq.req.name = canonicalize_name(ireq.name)
# Pin requirement to a resolved version
pinned_ireq.req.specifier = SpecifierSet(
f"{version_pin_operator}{candidate.version}"
)
# Save reverse dependencies for annotation
ireq_key = key_from_ireq(ireq)
pinned_ireq._required_by = reverse_dependencies.get(ireq_key, set())
# Save sources for annotation
constraint_ireq = self._constraints_map.get(ireq_key)
if constraint_ireq is not None:
if hasattr(constraint_ireq, "_source_ireqs"):
# If the constraint is combined (has _source_ireqs), use those
pinned_ireq._source_ireqs = constraint_ireq._source_ireqs
else:
# Otherwise (the constraint is not combined) it is the source
pinned_ireq._source_ireqs = [constraint_ireq]
return pinned_ireq
| BacktrackingResolver |
python | urllib3__urllib3 | src/urllib3/contrib/emscripten/response.py | {
"start": 694,
"end": 9507
} | class ____(BaseHTTPResponse):
def __init__(
self,
internal_response: EmscriptenResponse,
url: str | None = None,
connection: BaseHTTPConnection | BaseHTTPSConnection | None = None,
):
self._pool = None # set by pool class
self._body = None
self._response = internal_response
self._url = url
self._connection = connection
self._closed = False
super().__init__(
headers=internal_response.headers,
status=internal_response.status_code,
request_url=url,
version=0,
version_string="HTTP/?",
reason="",
decode_content=True,
)
self.length_remaining = self._init_length(self._response.request.method)
self.length_is_certain = False
@property
def url(self) -> str | None:
return self._url
@url.setter
def url(self, url: str | None) -> None:
self._url = url
@property
def connection(self) -> BaseHTTPConnection | BaseHTTPSConnection | None:
return self._connection
@property
def retries(self) -> Retry | None:
return self._retries
@retries.setter
def retries(self, retries: Retry | None) -> None:
# Override the request_url if retries has a redirect location.
self._retries = retries
def stream(
self, amt: int | None = 2**16, decode_content: bool | None = None
) -> typing.Generator[bytes]:
"""
A generator wrapper for the read() method. A call will block until
``amt`` bytes have been read from the connection or until the
connection is closed.
:param amt:
How much of the content to read. The generator will return up to
much data per iteration, but may return less. This is particularly
likely when using compressed data. However, the empty string will
never be returned.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
"""
while True:
data = self.read(amt=amt, decode_content=decode_content)
if data:
yield data
else:
break
def _init_length(self, request_method: str | None) -> int | None:
length: int | None
content_length: str | None = self.headers.get("content-length")
if content_length is not None:
try:
# RFC 7230 section 3.3.2 specifies multiple content lengths can
# be sent in a single Content-Length header
# (e.g. Content-Length: 42, 42). This line ensures the values
# are all valid ints and that as long as the `set` length is 1,
# all values are the same. Otherwise, the header is invalid.
lengths = {int(val) for val in content_length.split(",")}
if len(lengths) > 1:
raise InvalidHeader(
"Content-Length contained multiple "
"unmatching values (%s)" % content_length
)
length = lengths.pop()
except ValueError:
length = None
else:
if length < 0:
length = None
else: # if content_length is None
length = None
# Check for responses that shouldn't include a body
if (
self.status in (204, 304)
or 100 <= self.status < 200
or request_method == "HEAD"
):
length = 0
return length
def read(
self,
amt: int | None = None,
decode_content: bool | None = None, # ignored because browser decodes always
cache_content: bool = False,
) -> bytes:
if (
self._closed
or self._response is None
or (isinstance(self._response.body, IOBase) and self._response.body.closed)
):
return b""
with self._error_catcher():
# body has been preloaded as a string by XmlHttpRequest
if not isinstance(self._response.body, IOBase):
self.length_remaining = len(self._response.body)
self.length_is_certain = True
# wrap body in IOStream
self._response.body = BytesIO(self._response.body)
if amt is not None and amt >= 0:
# don't cache partial content
cache_content = False
data = self._response.body.read(amt)
else: # read all we can (and cache it)
data = self._response.body.read()
if cache_content:
self._body = data
if self.length_remaining is not None:
self.length_remaining = max(self.length_remaining - len(data), 0)
if len(data) == 0 or (
self.length_is_certain and self.length_remaining == 0
):
# definitely finished reading, close response stream
self._response.body.close()
return typing.cast(bytes, data)
def read_chunked(
self,
amt: int | None = None,
decode_content: bool | None = None,
) -> typing.Generator[bytes]:
# chunked is handled by browser
while True:
bytes = self.read(amt, decode_content)
if not bytes:
break
yield bytes
def release_conn(self) -> None:
if not self._pool or not self._connection:
return None
self._pool._put_conn(self._connection)
self._connection = None
def drain_conn(self) -> None:
self.close()
@property
def data(self) -> bytes:
if self._body:
return self._body
else:
return self.read(cache_content=True)
def json(self) -> typing.Any:
"""
Deserializes the body of the HTTP response as a Python object.
The body of the HTTP response must be encoded using UTF-8, as per
`RFC 8529 Section 8.1 <https://www.rfc-editor.org/rfc/rfc8259#section-8.1>`_.
To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to
your custom decoder instead.
If the body of the HTTP response is not decodable to UTF-8, a
`UnicodeDecodeError` will be raised. If the body of the HTTP response is not a
valid JSON document, a `json.JSONDecodeError` will be raised.
Read more :ref:`here <json_content>`.
:returns: The body of the HTTP response as a Python object.
"""
data = self.data.decode("utf-8")
return _json.loads(data)
def close(self) -> None:
if not self._closed:
if isinstance(self._response.body, IOBase):
self._response.body.close()
if self._connection:
self._connection.close()
self._connection = None
self._closed = True
@contextmanager
def _error_catcher(self) -> typing.Generator[None]:
"""
Catch Emscripten specific exceptions thrown by fetch.py,
instead re-raising urllib3 variants, so that low-level exceptions
are not leaked in the high-level api.
On exit, release the connection back to the pool.
"""
from .fetch import _RequestError, _TimeoutError # avoid circular import
clean_exit = False
try:
yield
# If no exception is thrown, we should avoid cleaning up
# unnecessarily.
clean_exit = True
except _TimeoutError as e:
raise TimeoutError(str(e))
except _RequestError as e:
raise HTTPException(str(e))
finally:
# If we didn't terminate cleanly, we need to throw away our
# connection.
if not clean_exit:
# The response may not be closed but we're not going to use it
# anymore so close it now
if (
isinstance(self._response.body, IOBase)
and not self._response.body.closed
):
self._response.body.close()
# release the connection back to the pool
self.release_conn()
else:
# If we have read everything from the response stream,
# return the connection back to the pool.
if (
isinstance(self._response.body, IOBase)
and self._response.body.closed
):
self.release_conn()
| EmscriptenHttpResponseWrapper |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 245009,
"end": 247841
} | class ____:
def _create_arrays(self):
a = np.arange(20.0).reshape(4, 5)
a.flags.writeable = False
b = a[::2, ::2]
return a, b
def test_contiguous(self):
testpassed = False
a, _ = self._create_arrays()
try:
a.flat[12] = 100.0
except ValueError:
testpassed = True
assert_(testpassed)
assert_(a.flat[12] == 12.0)
def test_discontiguous(self):
testpassed = False
_, b = self._create_arrays()
try:
b.flat[4] = 100.0
except ValueError:
testpassed = True
assert_(testpassed)
assert_(b.flat[4] == 12.0)
def test___array__(self):
a0 = np.arange(20.0)
a = a0.reshape(4, 5)
a0 = a0.reshape((4, 5))
a.flags.writeable = False
b = a[::2, ::2]
b0 = a0[::2, ::2]
c = a.flat.__array__()
d = b.flat.__array__()
e = a0.flat.__array__()
f = b0.flat.__array__()
assert_(c.flags.writeable is False)
assert_(d.flags.writeable is False)
assert_(e.flags.writeable is True)
assert_(f.flags.writeable is False)
assert_(c.flags.writebackifcopy is False)
assert_(d.flags.writebackifcopy is False)
assert_(e.flags.writebackifcopy is False)
assert_(f.flags.writebackifcopy is False)
@pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
def test_refcount(self):
# includes regression test for reference count error gh-13165
a, _ = self._create_arrays()
inds = [np.intp(0), np.array([True] * a.size), np.array([0]), None]
indtype = np.dtype(np.intp)
rc_indtype = sys.getrefcount(indtype)
for ind in inds:
rc_ind = sys.getrefcount(ind)
for _ in range(100):
try:
a.flat[ind]
except IndexError:
pass
assert_(abs(sys.getrefcount(ind) - rc_ind) < 50)
assert_(abs(sys.getrefcount(indtype) - rc_indtype) < 50)
def test_index_getset(self):
it = np.arange(10).reshape(2, 1, 5).flat
with pytest.raises(AttributeError):
it.index = 10
for _ in it:
pass
# Check the value of `.index` is updated correctly (see also gh-19153)
# If the type was incorrect, this would show up on big-endian machines
assert it.index == it.base.size
def test_maxdims(self):
# The flat iterator and thus attribute is currently unfortunately
# limited to only 32 dimensions (after bumping it to 64 for 2.0)
a = np.ones((1,) * 64)
with pytest.raises(RuntimeError,
match=".*32 dimensions but the array has 64"):
a.flat
| TestFlat |
python | kamyu104__LeetCode-Solutions | Python/maximum-and-sum-of-array.py | {
"start": 72,
"end": 2199
} | class ____(object):
def maximumANDSum(self, nums, numSlots):
"""
:type nums: List[int]
:type numSlots: int
:rtype: int
"""
# Template translated from:
# https://github.com/kth-competitive-programming/kactl/blob/main/content/graph/WeightedMatching.h
def hungarian(a): # Time: O(n^2 * m), Space: O(n + m)
if not a:
return 0, []
n, m = len(a)+1, len(a[0])+1
u, v, p, ans = [0]*n, [0]*m, [0]*m, [0]*(n-1)
for i in xrange(1, n):
p[0] = i
j0 = 0 # add "dummy" worker 0
dist, pre = [float("inf")]*m, [-1]*m
done = [False]*(m+1)
while True: # dijkstra
done[j0] = True
i0, j1, delta = p[j0], None, float("inf")
for j in xrange(1, m):
if done[j]:
continue
cur = a[i0-1][j-1]-u[i0]-v[j]
if cur < dist[j]:
dist[j], pre[j] = cur, j0
if dist[j] < delta:
delta, j1 = dist[j], j
for j in xrange(m):
if done[j]:
u[p[j]] += delta
v[j] -= delta
else:
dist[j] -= delta
j0 = j1
if not p[j0]:
break
while j0: # update alternating path
j1 = pre[j0]
p[j0], j0 = p[j1], j1
for j in xrange(1, m):
if p[j]:
ans[p[j]-1] = j-1
return -v[0], ans # min cost
return -hungarian([[-((nums[i] if i < len(nums) else 0) & (1+x//2)) for x in xrange(2*numSlots)] for i in xrange(2*numSlots)])[0]
# Time: O(n^3)
# Space: O(n^2)
from scipy.optimize import linear_sum_assignment as hungarian
import itertools
# 3rd-party weighted bipartite matching solution
| Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.