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
getsentry__sentry
tests/sentry/integrations/slack/test_integration.py
{ "start": 19197, "end": 21468 }
class ____(TestCase): def setUp(self) -> None: self.integration = self.create_provider_integration( provider="slack", name="Slack", external_id="TXXXXXXX1", metadata={ "access_token": "xoxb-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx", "installation_type": "born_as_bot", }, ) self.installation = SlackIntegration(self.integration, self.organization.id) self.target = IntegrationNotificationTarget( provider_key=NotificationProviderKey.SLACK, resource_type=NotificationTargetResourceType.CHANNEL, resource_id="C1234567890", integration_id=self.integration.id, organization_id=self.organization.id, ) @patch("sentry.integrations.slack.sdk_client.SlackSdkClient.chat_postMessage") def test_send_notification_success(self, mock_chat_post: MagicMock) -> None: data = MockNotification(message="test") template = MockNotificationTemplate() rendered_template = template.render(data) renderer = SlackNotificationProvider.get_renderer( data=data, category=NotificationCategory.DEBUG ) payload = renderer.render(data=data, rendered_template=rendered_template) self.installation.send_notification(target=self.target, payload=payload) mock_chat_post.assert_called_once_with( channel="C1234567890", blocks=payload.get("blocks", []), text="Mock Notification", ) @patch("sentry.integrations.slack.sdk_client.SlackSdkClient.chat_postMessage") def test_send_notification_api_error(self, mock_chat_post: MagicMock) -> None: mock_response = MagicMock() mock_response.status_code = 400 mock_response.data = {"error": "channel_not_found"} mock_response.api_url = "https://slack.com/api/chat.postMessage" mock_chat_post.side_effect = SlackApiError("channel_not_found", mock_response) payload: SlackRenderable = {"blocks": [], "text": "Test"} with pytest.raises(IntegrationConfigurationError): self.installation.send_notification(target=self.target, payload=payload)
SlackIntegrationSendNotificationTest
python
getsentry__sentry
src/sentry/sentry_metrics/querying/units.py
{ "start": 2645, "end": 2853 }
class ____: """ Represents the specification of multiple units which has a common reference unit. """ reference_unit: MeasurementUnit units: Sequence[Unit] @dataclass(frozen=True)
UnitsSpec
python
apache__airflow
providers/apache/hdfs/tests/unit/apache/hdfs/log/test_hdfs_task_handler.py
{ "start": 1391, "end": 8922 }
class ____: @pytest.fixture(autouse=True) def ti(self, create_task_instance, create_log_template): create_log_template("{try_number}.log") ti = create_task_instance( dag_id="dag_for_testing_hdfs_task_handler", task_id="task_for_testing_hdfs_log_handler", logical_date=DEFAULT_DATE, start_date=DEFAULT_DATE, dagrun_state=TaskInstanceState.RUNNING, state=TaskInstanceState.RUNNING, ) ti.try_number = 1 ti.hostname = "localhost" ti.raw = False yield ti clear_db_runs() clear_db_dags() def setup_method(self): self.hdfs_log_folder = "hdfs://namenode/remote/log/location" self.remote_log_location = "remote/log/location/1.log" self.local_log_location = str(Path(tempfile.gettempdir()) / "local/log/location") self.hdfs_task_handler = HdfsTaskHandler( base_log_folder=self.local_log_location, hdfs_log_folder=self.hdfs_log_folder, delete_local_copy=True, ) def test_hook(self): assert isinstance(self.hdfs_task_handler.io.hook, WebHDFSHook) def test_set_context_raw(self, ti): ti.raw = True mock_open = mock.mock_open() with mock.patch("airflow.providers.apache.hdfs.log.hdfs_task_handler.open", mock_open): self.hdfs_task_handler.set_context(ti) assert self.hdfs_task_handler.upload_on_close is False mock_open.assert_not_called() def test_set_context_not_raw(self, ti): mock_open = mock.mock_open() with mock.patch("airflow.providers.apache.hdfs.log.hdfs_task_handler.open", mock_open): self.hdfs_task_handler.io.upload = mock.MagicMock() self.hdfs_task_handler.set_context(ti) assert self.hdfs_task_handler.upload_on_close is True mock_open.assert_called_once_with(self.hdfs_task_handler.handler.baseFilename, "w") mock_open().write.assert_not_called() @mock.patch( "airflow.providers.apache.hdfs.log.hdfs_task_handler.HdfsRemoteLogIO.hook", new_callable=PropertyMock ) def test_hdfs_read(self, mock_hook): expected_file_path = os.path.join(self.hdfs_task_handler.io.remote_base, "1.log") mock_hook.return_value.check_for_path.return_value = True mock_hook.return_value.read_file.return_value = b"mock_content" dummy_ti = "dummy_ti" messages, logs = self.hdfs_task_handler.io.read("1.log", dummy_ti) mock_hook.return_value.check_for_path.assert_called_once_with(expected_file_path) mock_hook.return_value.read_file.assert_called_once_with(expected_file_path) assert messages == [] assert logs == ["mock_content"] @mock.patch( "airflow.providers.apache.hdfs.log.hdfs_task_handler.HdfsRemoteLogIO.hook", new_callable=PropertyMock ) def test_hdfs_read_not_exists(self, mock_hook): expected_file_path = os.path.join(self.hdfs_task_handler.io.remote_base, "1.log") mock_hook.return_value.check_for_path.return_value = False dummy_ti = "dummy_ti" messages, logs = self.hdfs_task_handler.io.read("1.log", dummy_ti) mock_hook.return_value.check_for_path.assert_called_once_with(expected_file_path) assert messages == [f"No logs found on hdfs for ti={dummy_ti}"] assert logs == [] @mock.patch("shutil.rmtree") def test_upload_absolute_path(self, mock_rmtree, ti): base_path = Path(self.local_log_location) base_path.mkdir(parents=True, exist_ok=True) test_file = base_path / "test.log" test_file.write_text("log content") absolute_path = str(test_file.resolve()) relative_path = test_file.relative_to(base_path) expected_remote_loc = os.path.join(self.hdfs_task_handler.io.remote_base, str(relative_path)) self.hdfs_task_handler.io.hook = mock.MagicMock(spec=WebHDFSHook) self.hdfs_task_handler.io.hook.load_file = mock.MagicMock() self.hdfs_task_handler.io.upload(absolute_path, ti) self.hdfs_task_handler.io.hook.load_file.assert_called_once_with(test_file, expected_remote_loc) mock_rmtree.assert_called_once_with(os.path.dirname(str(test_file))) @mock.patch("shutil.rmtree") def test_upload_relative_path(self, mock_rmtree, ti): base_path = Path(self.local_log_location) base_path.mkdir(parents=True, exist_ok=True) test_file = base_path / "relative.log" test_file.write_text("relative log content") relative_path = "relative.log" expected_remote_loc = os.path.join(self.hdfs_task_handler.io.remote_base, relative_path) self.hdfs_task_handler.io.hook = mock.MagicMock(spec=WebHDFSHook) self.hdfs_task_handler.io.hook.load_file = mock.MagicMock() self.hdfs_task_handler.io.upload(relative_path, ti) self.hdfs_task_handler.io.hook.load_file.assert_called_once_with(test_file, expected_remote_loc) mock_rmtree.assert_called_once_with(os.path.dirname(str(test_file))) def test_close_uploads_once(self, ti): self.hdfs_task_handler.set_context(ti) self.hdfs_task_handler.io.upload = mock.MagicMock() self.hdfs_task_handler.close() self.hdfs_task_handler.io.upload.assert_called_once_with(self.hdfs_task_handler.log_relative_path, ti) self.hdfs_task_handler.io.upload.reset_mock() self.hdfs_task_handler.close() self.hdfs_task_handler.io.upload.assert_not_called() def test_read_remote_logs_found(self, ti): self.hdfs_task_handler._render_filename = lambda ti, try_number: "dummy.log" self.hdfs_task_handler.io.read = mock.MagicMock(return_value=([], ["dummy log"])) messages, logs = self.hdfs_task_handler._read_remote_logs(ti, try_number=1) assert messages == [] assert logs == ["dummy log"] def test_read_remote_logs_not_found(self, ti): self.hdfs_task_handler._render_filename = lambda ti, try_number: "dummy.log" self.hdfs_task_handler.io.read = mock.MagicMock( return_value=([f"No logs found on hdfs for ti={ti}"], []) ) messages, logs = self.hdfs_task_handler._read_remote_logs(ti, try_number=1) assert [f"No logs found on hdfs for ti={ti}"] assert logs == [] @pytest.mark.parametrize( ("delete_local_copy", "expected_existence_of_local_copy"), [(True, False), (False, True)], ) def test_close_with_delete_local_logs_conf( self, ti, tmp_path_factory, delete_local_copy, expected_existence_of_local_copy ): local_log_dir = tmp_path_factory.mktemp("local-hdfs-log-location") local_log_file = local_log_dir / "1.log" local_log_file.write_text("test") with conf_vars({("logging", "delete_local_logs"): str(delete_local_copy)}): handler = HdfsTaskHandler( base_log_folder=str(local_log_dir), hdfs_log_folder=self.hdfs_log_folder, delete_local_copy=delete_local_copy, ) handler.log.info("test") handler.local_base = local_log_dir with mock.patch.object(handler.io, "hook") as mock_hook: mock_hook.load_file.return_value = None handler.set_context(ti) assert handler.upload_on_close handler.close() assert os.path.exists(handler.handler.baseFilename) == expected_existence_of_local_copy
TestHdfsTaskHandler
python
tensorflow__tensorflow
tensorflow/compiler/tests/unary_ops_test.py
{ "start": 1622, "end": 34873 }
class ____(xla_test.XLATestCase): """Test cases for unary operators.""" def _assertOpOutputMatchesExpected( self, op, inp, expected, equality_test=None, rtol=1e-3, atol=1e-5 ): """Verifies that 'op' produces 'expected' when fed input 'inp' . Args: op: operator to test inp: numpy input array to use as input to 'op'. expected: numpy array representing the expected output of 'op'. equality_test: either None, or a function that tests two numpy arrays for equality. If None, self.assertAllClose is used. rtol: relative tolerance for equality test. atol: absolute tolerance for equality test. """ with self.session() as session: with self.test_scope(): pinp = array_ops.placeholder( dtypes.as_dtype(inp.dtype), inp.shape, name="a" ) output = op(pinp) result = session.run(output, {pinp: inp}) if equality_test is None: self.assertEqual(output.dtype, expected.dtype) self.assertAllCloseAccordingToType( expected, result, rtol=rtol, atol=atol, bfloat16_rtol=0.03 ) else: equality_test(result, expected, rtol=rtol, atol=atol) def ListsAreClose(self, result, expected, rtol, atol): """Tests closeness of two lists of floats.""" self.assertEqual(len(result), len(expected)) for i in range(len(result)): self.assertAllClose(result[i], expected[i], rtol, atol) def AssertCloseAndSorted(self, result, expected, rtol, atol): """Tests that result and expected are both close and sorted.""" self.assertAllClose(result, expected, rtol, atol) self.assertAllEqual(np.sort(result), result) def AssertAllEqual(self, result, expected, rtol, atol): """Tests that result and expected are exactly equal.""" self.assertAllEqual(result, expected) def testAllTypeOps(self): for dtype in self.numeric_types - {np.int8, np.uint8}: self._assertOpOutputMatchesExpected( array_ops.diag, np.array([1, 2, 3, 4], dtype=dtype), np.array( [[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]], dtype=dtype, ), ) self._assertOpOutputMatchesExpected( array_ops.diag_part, np.arange(36).reshape([2, 3, 2, 3]).astype(dtype), np.array([[0, 7, 14], [21, 28, 35]], dtype=dtype), ) self._assertOpOutputMatchesExpected( array_ops.diag, np.array([[1, 2], [3, 4]], dtype=dtype), np.array( [ [[[1, 0], [0, 0]], [[0, 2], [0, 0]]], [[[0, 0], [3, 0]], [[0, 0], [0, 4]]], ], dtype=dtype, ), ) self._assertOpOutputMatchesExpected( array_ops.identity, np.array([[-1, 1]], dtype=dtype), expected=np.array([[-1, 1]], dtype=dtype), ) self._assertOpOutputMatchesExpected( array_ops.prevent_gradient, np.array([[-1, 1]], dtype=dtype), expected=np.array([[-1, 1]], dtype=dtype), ) self._assertOpOutputMatchesExpected( array_ops.squeeze, np.array([[[[[]]]]], dtype=dtype), expected=np.array([], dtype=dtype), ) self._assertOpOutputMatchesExpected( array_ops.squeeze, np.array([[[1], [2]]], dtype=dtype), expected=np.array([1, 2], dtype=dtype), ) self._assertOpOutputMatchesExpected( array_ops.squeeze, np.array([[[1]], [[2]]], dtype=dtype), expected=np.array([1, 2], dtype=dtype), ) self._assertOpOutputMatchesExpected( array_ops.squeeze, np.array([[[1, 2], [3, 4]]], dtype=dtype), expected=np.array([[1, 2], [3, 4]], dtype=dtype), ) self._assertOpOutputMatchesExpected( array_ops.stop_gradient, np.array([[-1, 1]], dtype=dtype), expected=np.array([[-1, 1]], dtype=dtype), ) def testLog(self): for dtype in self.float_types - {dtypes.bfloat16.as_numpy_dtype}: tol = 1e-4 if dtype == np.float32 else 1e-9 # pylint: disable=invalid-unary-operand-type x = np.linspace(-np.e, np.e, num=1000, dtype=dtype) self._assertOpOutputMatchesExpected( math_ops.log, x, expected=np.log(x), atol=tol, rtol=tol ) x = np.linspace(0.0, np.e * 1e-30, num=1000, dtype=dtype) self._assertOpOutputMatchesExpected( math_ops.log, x, expected=np.log(x), atol=tol, rtol=tol ) x = np.linspace(0.0, np.pi * 1e30, num=1000, dtype=dtype) self._assertOpOutputMatchesExpected( math_ops.log, x, expected=np.log(x), atol=tol, rtol=tol ) def testSin(self): for dtype in self.float_types - {dtypes.bfloat16.as_numpy_dtype}: tol = 1e-6 if dtype == np.float32 else 1e-12 x = np.linspace(-4 * np.e, 4 * np.e, num=1000, dtype=dtype) self._assertOpOutputMatchesExpected( math_ops.sin, x, expected=np.sin(x), rtol=tol, atol=tol ) x = np.linspace(0.0, np.e * 1e-30, num=1000, dtype=dtype) self._assertOpOutputMatchesExpected( math_ops.sin, x, expected=np.sin(x), rtol=tol, atol=tol ) if dtype == np.float64: x = np.linspace(0.0, np.e * 1e8, num=1000, dtype=dtype) self._assertOpOutputMatchesExpected( math_ops.sin, x, expected=np.sin(x), rtol=tol, atol=1e-5 ) def testCos(self): for dtype in self.float_types - {dtypes.bfloat16.as_numpy_dtype}: tol = 1e-6 if dtype == np.float32 else 1e-12 x = np.linspace(-4 * np.e, 4 * np.e, num=1000, dtype=dtype) self._assertOpOutputMatchesExpected( math_ops.cos, x, expected=np.cos(x), rtol=tol, atol=tol ) x = np.linspace(0.0, np.e * 1e-30, num=1000, dtype=dtype) self._assertOpOutputMatchesExpected( math_ops.cos, x, expected=np.cos(x), rtol=tol, atol=tol ) if dtype == np.float64: x = np.linspace(0.0, np.e * 1e8, num=1000, dtype=dtype) self._assertOpOutputMatchesExpected( math_ops.cos, x, expected=np.cos(x), rtol=tol, atol=1e-5 ) def testSigmoidNumericalStability(self): for dtype in self.float_types: if dtype != np.float16: self._assertOpOutputMatchesExpected( lambda x: math_ops.sigmoid(x) / math_ops.log1p(math_ops.exp(x)), np.array([-40, 40], dtype=dtype), expected=np.array([1.0, 0.025], dtype=dtype), ) def testQuantizeAndDequantize(self): for dtype in self.float_types: def quantize_and_dequantize_v2(x): return array_ops.quantize_and_dequantize( x, -127, 127, signed_input=True, num_bits=8 ) def quantize_and_dequantize_v3(x): return array_ops.quantize_and_dequantize_v3( x, -127, 127, num_bits=8, signed_input=True, range_given=False ) def quantize_and_dequantize_v4(x): return array_ops.quantize_and_dequantize_v2( x, -127, 127, signed_input=True, num_bits=8 ) test_fns = ( quantize_and_dequantize_v2, quantize_and_dequantize_v3, quantize_and_dequantize_v4, ) for test_fn in test_fns: self._assertOpOutputMatchesExpected( test_fn, np.array([-1, -0.5, 0, 0.3], dtype=dtype), expected=np.array([-1.0, -0.5, 0.0, 0.296875], dtype=dtype), ) def quantize_and_dequantize_v2_round_half_up(x): return array_ops.quantize_and_dequantize( x, -1.0, 1.0, signed_input=True, num_bits=8, range_given=True, round_mode="HALF_UP", ) self._assertOpOutputMatchesExpected( quantize_and_dequantize_v2_round_half_up, np.array([-0.8, -0.4, 0, 0.3, 0.8, -2, 33], dtype=dtype), expected=np.array( [ -102.0 / 127, -51.0 / 127, 0, 38.0 / 127, 102.0 / 127, -128.0 / 127, 1, ], dtype=dtype, ), ) def quantize_and_dequantize_v2_round_half_to_even(x): return array_ops.quantize_and_dequantize( x, -1.0, 1.0, signed_input=True, num_bits=8, range_given=True, round_mode="HALF_TO_EVEN", ) self._assertOpOutputMatchesExpected( quantize_and_dequantize_v2_round_half_to_even, np.array([-0.8, -0.4, 0, 0.3, 0.8, -2, 33], dtype=dtype), expected=np.array( [ -102.0 / 127, -51.0 / 127, 0, 38.0 / 127, 102.0 / 127, -128.0 / 127, 1, ], dtype=dtype, ), ) def testComplexOps(self): for dtype in self.complex_types: self._assertOpOutputMatchesExpected( math_ops.acosh, np.array([0.1, 0.2j, 0.3 - 0.1j, 0.4 + 0.5j], dtype=dtype), expected=np.arccosh( np.array([0.1, 0.2j, 0.3 - 0.1j, 0.4 + 0.5j], dtype=dtype) ), ) self._assertOpOutputMatchesExpected( math_ops.asinh, np.array([0.1, 0.2j, 0.3 - 0.1j, 0.4 + 0.5j], dtype=dtype), expected=np.arcsinh( np.array([0.1, 0.2j, 0.3 - 0.1j, 0.4 + 0.5j], dtype=dtype) ), ) self._assertOpOutputMatchesExpected( math_ops.atanh, np.array([0.1, 0.2j, 0.3 - 0.1j, 0.4 + 0.5j], dtype=dtype), expected=np.arctanh( np.array([0.1, 0.2j, 0.3 - 0.1j, 0.4 + 0.5j], dtype=dtype) ), ) self._assertOpOutputMatchesExpected( math_ops.cosh, np.array([1j, 2 - 3j, 3, 4 + 2j], dtype=dtype), expected=np.cosh(np.array([1j, 2 - 3j, 3, 4 + 2j], dtype=dtype)), ) self._assertOpOutputMatchesExpected( math_ops.sinh, np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype), expected=np.sinh(np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype)), ) self._assertOpOutputMatchesExpected( math_ops.exp, np.array([[-1 + 2j, 3j, 2 - 3j]], dtype=dtype), expected=np.exp(np.array([[-1 + 2j, 3j, 2 - 3j]], dtype=dtype)), ) self._assertOpOutputMatchesExpected( math_ops.expm1, np.array([[-1 + 2j, 3j, 2 - 3j]], dtype=dtype), expected=np.expm1(np.array([[-1 + 2j, 3j, 2 - 3j]], dtype=dtype)), rtol=1e-6, atol=1e-6, ) # For real part close to zero, or imaginary part close to a multiple of # pi. self._assertOpOutputMatchesExpected( math_ops.expm1, np.array( [[ 1e-11 + 1j, -1e-11 - 1j, 1.0 + 1e-11j, -1.0 - 1e-11j, 1e-13j + 1e-13j, ]], dtype=dtype, ), expected=np.expm1( np.array( [[ 1e-11 + 1j, -1e-11 - 1j, 1.0 + 1e-11j, -1.0 - 1e-11j, 1e-13j + 1e-13j, ]], dtype=dtype, ), dtype=dtype, ), rtol=1e-09, atol=1e-20, ) self._assertOpOutputMatchesExpected( math_ops.reciprocal, np.array([[1, 2j, 2 + 3j]], dtype=dtype), expected=1.0 / np.array([[1, 2j, 2 + 3j]], dtype=dtype), ) self._assertOpOutputMatchesExpected( math_ops.log, np.array([[5j, 3 - 2j]], dtype=dtype), expected=np.log(np.array([[5j, 3 - 2j]], dtype=dtype)), ) self._assertOpOutputMatchesExpected( math_ops.sin, np.array([[5j, 3 - 2j]], dtype=dtype), expected=np.sin(np.array([[5j, 3 - 2j]], dtype=dtype)), ) self._assertOpOutputMatchesExpected( math_ops.cos, np.array([[5j, 3 - 2j]], dtype=dtype), expected=np.cos(np.array([[5j, 3 - 2j]], dtype=dtype)), ) self._assertOpOutputMatchesExpected( math_ops.log1p, np.array([[1e-14, 1e-15j, 0.6 - 0.3j]], dtype=dtype), expected=np.log1p( np.array([[1e-14, 1e-15j, 0.6 - 0.3j]], dtype=dtype) ), rtol=1e-4, atol=1e-6, ) val = np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype) self._assertOpOutputMatchesExpected( math_ops.rsqrt, val, expected=1 / np.sqrt(val) ) self._assertOpOutputMatchesExpected( math_ops.sigmoid, val, expected=1 / (1 + np.exp(-val)) ) self._assertOpOutputMatchesExpected( math_ops.sqrt, val, expected=np.sqrt(val) ) self._assertOpOutputMatchesExpected( math_ops.tanh, np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype), expected=np.tanh(np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype)), ) self._assertOpOutputMatchesExpected( math_ops.tan, np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype), expected=np.tan(np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype)), ) ctypes = {np.complex64: np.float32, np.complex128: np.float64} self._assertOpOutputMatchesExpected( math_ops.abs, np.array([[3 - 4j, -1j, np.inf]], dtype=dtype), expected=np.array([[5, 1, np.inf]], dtype=ctypes[dtype]), ) self._assertOpOutputMatchesExpected( math_ops.negative, np.array([[-1 + 2j, -3j]], dtype=dtype), expected=np.array([[1 - 2j, 3j]], dtype=dtype), ) self._assertOpOutputMatchesExpected( math_ops.square, np.array([[-2 - 3j, 3 + 4j, 5j]], dtype=dtype), expected=np.array([[-2 - 3j, 3 + 4j, 5j]], dtype=dtype) ** 2, ) self._assertOpOutputMatchesExpected( array_ops.zeros_like, np.array([[4j, 3 - 2j], [2, -1j]], dtype=dtype), expected=np.array([[0, 0], [0, 0]], dtype=dtype), ) self._assertOpOutputMatchesExpected( array_ops.ones_like, np.array([[-4j, 3 + 2j], [2, -1j]], dtype=dtype), expected=np.array([[1, 1], [1, 1]], dtype=dtype), ) self._assertOpOutputMatchesExpected( math_ops.angle, np.array([1 + 3j, -4 + 7j, 2.7, -3j], dtype=dtype), expected=np.angle(np.array([1 + 3j, -4 + 7j, 2.7, -3j], dtype=dtype)), ) self._assertOpOutputMatchesExpected( math_ops.conj, np.array([1 + 3j, -4 + 7j, 2.7, -3j], dtype=dtype), expected=np.array([1 - 3j, -4 - 7j, 2.7, 3j], dtype=dtype), ) self._assertOpOutputMatchesExpected( math_ops.imag, np.array([1 + 3j, -4 + 7j, 2.7, -3j], dtype=dtype), expected=np.array([3, 7, 0, -3], dtype=ctypes[dtype]), ) self._assertOpOutputMatchesExpected( math_ops.real, np.array([1 + 3j, -4 + 7j, 2.7, -3j], dtype=dtype), expected=np.array([1, -4, 2.7, 0], dtype=ctypes[dtype]), ) def testIntOps(self): for dtype in self.int_types - self.unsigned_int_types: self._assertOpOutputMatchesExpected( bitwise_ops.invert, np.array([0, -1, 1, 16, 42], dtype=dtype), expected=np.array([-1, 0, -2, -17, -43], dtype=dtype), ) # Test population_count for array inputs. raw_inputs = [ 0, 1, -1, 3, -3, 5, -5, 14, -14, 127, 128, 255, 256, 65535, 65536, 2**31 - 1, 2**31, 2**32 - 1, 2**32, -(2**32) + 1, -(2**32), -(2**63) + 1, 2**63 - 1, ] # Only choose inputs which fit in the int dtype. raw_inputs = list( filter( lambda x: np.iinfo(dtype).min <= x <= np.iinfo(dtype).max, raw_inputs, ) ) inputs = np.array(raw_inputs, dtype=dtype) def count_bits(x): return sum(bin(z).count("1") for z in six.iterbytes(x.tobytes())) truth = [count_bits(x) for x in inputs] self._assertOpOutputMatchesExpected( bitwise_ops.population_count, inputs, expected=np.array(truth, dtype=np.uint8), equality_test=self.AssertAllEqual, ) # Test population_count for scalar inputs. for raw_inp in raw_inputs: inp = dtype(raw_inp) truth = count_bits(inp) self._assertOpOutputMatchesExpected( bitwise_ops.population_count, inp, expected=np.uint8(truth), equality_test=self.AssertAllEqual, ) def testNumericOps(self): for dtype in self.numeric_types - {np.int8, np.uint8}: self._assertOpOutputMatchesExpected( math_ops.abs, np.array([[2, -1]], dtype=dtype), expected=np.array([[2, 1]], dtype=np.real(dtype(0)).dtype), ) self._assertOpOutputMatchesExpected( math_ops.negative, np.array([[-1, 1]], dtype=dtype), expected=np.array([[1, -1]], dtype=dtype), ) self._assertOpOutputMatchesExpected( math_ops.square, np.array([[-2, 3]], dtype=dtype), expected=np.array([[4, 9]], dtype=dtype), ) self._assertOpOutputMatchesExpected( array_ops.zeros_like, np.array([[4, 3], [2, 1]], dtype=dtype), expected=np.array([[0, 0], [0, 0]], dtype=dtype), ) self._assertOpOutputMatchesExpected( array_ops.ones_like, np.array([[4, 3], [2, 1]], dtype=dtype), expected=np.array([[1, 1], [1, 1]], dtype=dtype), ) # TODO(phawkins): these tests fail unless fastmath optimizations # are disabled. Use more robust IsInf/IsNaN detection and enable these # tests. @unittest.skip("test case fails in fast-math mode") def testIsInfAndIsNan(self): for dtype in self.float_types: self._assertOpOutputMatchesExpected( math_ops.is_inf, np.array( [[-np.inf, -2, -1, 0, 0.5, 1, 2, np.inf, np.nan]], dtype=dtype ), expected=np.array([[1, 0, 0, 0, 0, 0, 0, 1, 0]], dtype=np.bool_), ) self._assertOpOutputMatchesExpected( math_ops.is_nan, np.array( [[-np.inf, -2, -1, 0, 0.5, 1, 2, np.inf, np.nan]], dtype=dtype ), expected=np.array([[0, 0, 0, 0, 0, 0, 0, 0, 1]], dtype=np.bool_), ) self._assertOpOutputMatchesExpected( math_ops.sign, np.array([[np.nan]], dtype=dtype), expected=np.array([[0.0]], dtype=dtype), ) def testLogicalOps(self): self._assertOpOutputMatchesExpected( math_ops.logical_not, np.array([[True, False], [False, True]], dtype=np.bool_), expected=np.array([[False, True], [True, False]], dtype=np.bool_), ) def testBiasAddGrad(self): self._assertOpOutputMatchesExpected( gen_nn_ops.bias_add_grad, np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32), expected=np.array([4.0, 6.0], dtype=np.float32), ) self._assertOpOutputMatchesExpected( lambda x: gen_nn_ops.bias_add_grad(x, data_format="NCHW"), np.array( [[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]], dtype=np.float32, ), expected=np.array([14.0, 22.0], dtype=np.float32), ) def testBitcast(self): self._assertOpOutputMatchesExpected( lambda x: array_ops.bitcast(x, dtypes.int32), np.array([1, 0x3F800000], np.int32), expected=np.array([1, 0x3F800000], np.int32), ) self._assertOpOutputMatchesExpected( lambda x: array_ops.bitcast(x, dtypes.float32), np.array([1, 0x3F800000], np.int32), expected=np.array([1e-45, 1.0], np.float32), ) self._assertOpOutputMatchesExpected( lambda x: array_ops.bitcast(x, dtypes.int32), np.array([1e-45, 1.0], np.float32), expected=np.array([1, 0x3F800000], np.int32), ) if np.int64 in self.numeric_types: self._assertOpOutputMatchesExpected( lambda x: array_ops.bitcast(x, dtypes.int64), np.array([1, 0x100000003F800000], np.uint64), expected=np.array([1, 0x100000003F800000], np.int64), ) self._assertOpOutputMatchesExpected( lambda x: array_ops.bitcast(x, dtypes.uint64), np.array([1, 0x100000003F800000], np.int64), expected=np.array([1, 0x100000003F800000], np.uint64), ) self._assertOpOutputMatchesExpected( lambda x: array_ops.bitcast(x, dtypes.float64), np.array( [0, 0x3FF0000000000000, 0xC3AF161421C8E000, 0x4032000000000007], np.uint64, ), expected=np.array( [0, 1.0, -1.12e18, 18.000000000000024869], np.float64 ), atol=0, ) def testBitcastInt8ToFloat(self): self._assertOpOutputMatchesExpected( lambda x: array_ops.bitcast(x, dtypes.float32), np.array([[1, 0, 0, 0], [0xD0, 0x0F, 0x49, 0x40]]).astype(np.int8), expected=np.array([1e-45, 3.14159], np.float32), ) self._assertOpOutputMatchesExpected( lambda x: array_ops.bitcast(x, dtypes.np.int8), np.array([1e-45, 3.14159], np.float32), expected=np.array([[1, 0, 0, 0], [0xD0, 0x0F, 0x49, 0x40]]).astype( np.int8 ), ) def testInvertPermutation(self): for np_dtype in [np.int32, np.int64]: self._assertOpOutputMatchesExpected( array_ops.invert_permutation, np.array([1, 2, 0], np_dtype), expected=np.array([2, 0, 1], dtype=np_dtype), ) def testInvertPermutationTwiceIsNoop(self): def invert_twice(x): return array_ops.invert_permutation(array_ops.invert_permutation(x)) for np_dtype in [np.int32, np.int64]: self._assertOpOutputMatchesExpected( invert_twice, np.array([1, 2, 0], np_dtype), expected=np.array([1, 2, 0], dtype=np_dtype), ) def testRank(self): rank_op = lambda x: array_ops.rank_internal(x, optimize=False) for dtype in self.numeric_types: self._assertOpOutputMatchesExpected( rank_op, dtype(7), expected=np.int32(0) ) self._assertOpOutputMatchesExpected( rank_op, np.array([[], []], dtype=dtype), expected=np.int32(2) ) self._assertOpOutputMatchesExpected( rank_op, np.array([0, 1], dtype=dtype), expected=np.int32(1) ) self._assertOpOutputMatchesExpected( rank_op, np.array([[0, 1]], dtype=dtype), expected=np.int32(2) ) self._assertOpOutputMatchesExpected( rank_op, np.array([[0], [1], [4]], dtype=dtype), expected=np.int32(2) ) def testShape(self): shape_op = lambda x: array_ops.shape_internal(x, optimize=False) for dtype in self.numeric_types: self._assertOpOutputMatchesExpected( shape_op, dtype(7), expected=np.array([], dtype=np.int32) ) self._assertOpOutputMatchesExpected( shape_op, np.array([[], []], dtype=dtype), expected=np.array([2, 0], dtype=np.int32), ) self._assertOpOutputMatchesExpected( shape_op, np.array([0, 1], dtype=dtype), expected=np.array([2], dtype=np.int32), ) self._assertOpOutputMatchesExpected( shape_op, np.array([[0, 1]], dtype=dtype), expected=np.array([1, 2], dtype=np.int32), ) self._assertOpOutputMatchesExpected( shape_op, np.array([[0], [1], [4]], dtype=dtype), expected=np.array([3, 1], dtype=np.int32), ) def testSize(self): size_op = lambda x: array_ops.size_internal(x, optimize=False) for dtype in self.numeric_types: self._assertOpOutputMatchesExpected( size_op, dtype(7), expected=np.int32(1) ) self._assertOpOutputMatchesExpected( size_op, np.array([[], []], dtype=dtype), expected=np.int32(0) ) self._assertOpOutputMatchesExpected( size_op, np.array([0, 1], dtype=dtype), expected=np.int32(2) ) self._assertOpOutputMatchesExpected( size_op, np.array([[0, 1]], dtype=dtype), expected=np.int32(2) ) self._assertOpOutputMatchesExpected( size_op, np.array([[0], [1], [4]], dtype=dtype), expected=np.int32(3) ) def testSizeWithInt64OutType(self): def size_op(x): return array_ops.size_internal(x, optimize=False, out_type=np.int64) for dtype in self.numeric_types: self._assertOpOutputMatchesExpected( size_op, np.array([[0], [1], [4]], dtype=dtype), expected=np.int64(3) ) def testUnpack(self): self._assertOpOutputMatchesExpected( array_ops_stack.unstack, np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=np.float32), expected=[ np.array([1.0, 2.0], dtype=np.float32), np.array([3.0, 4.0], dtype=np.float32), np.array([5.0, 6.0], dtype=np.float32), ], equality_test=self.ListsAreClose, ) self._assertOpOutputMatchesExpected( lambda x: array_ops_stack.unstack(x, axis=1), np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=np.float32), expected=[ np.array([1.0, 3.0, 5.0], dtype=np.float32), np.array([2.0, 4.0, 6.0], dtype=np.float32), ], equality_test=self.ListsAreClose, ) def testDepthToSpace(self): def make_op(data_format): def op(x): return array_ops.depth_to_space( x, block_size=2, data_format=data_format ) return op for dtype in self.numeric_types: for data_format in ["NCHW", "NHWC"]: self._assertOpOutputMatchesExpected( make_op(data_format), nhwc_to_format( np.array([[[[1, 2, 3, 4]]]], dtype=dtype), data_format ), expected=nhwc_to_format( np.array([[[[1], [2]], [[3], [4]]]], dtype=dtype), data_format ), ) self._assertOpOutputMatchesExpected( make_op(data_format), nhwc_to_format( np.array( [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]], dtype=dtype ), data_format, ), expected=nhwc_to_format( np.array( [[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]], dtype=dtype, ), data_format, ), ) self._assertOpOutputMatchesExpected( make_op(data_format), nhwc_to_format( np.array( [[ [[1, 2, 3, 4], [5, 6, 7, 8]], [[9, 10, 11, 12], [13, 14, 15, 16]], ]], dtype=dtype, ), data_format, ), expected=nhwc_to_format( np.array( [[ [[1], [2], [5], [6]], [[3], [4], [7], [8]], [[9], [10], [13], [14]], [[11], [12], [15], [16]], ]], dtype=dtype, ), data_format, ), ) self._assertOpOutputMatchesExpected( make_op("NCHW_VECT_C"), np.arange(32, dtype=dtype).reshape((1, 8, 1, 1, 4)), expected=np.array( [[ [ [[0, 1, 2, 3], [8, 9, 10, 11]], [[16, 17, 18, 19], [24, 25, 26, 27]], ], [ [[4, 5, 6, 7], [12, 13, 14, 15]], [[20, 21, 22, 23], [28, 29, 30, 31]], ], ]], dtype=dtype, ), ) def testSpaceToDepth(self): def make_op(data_format): def op(x): return array_ops.space_to_depth( x, block_size=2, data_format=data_format ) return op for dtype in self.numeric_types: for data_format in ["NCHW", "NHWC"]: self._assertOpOutputMatchesExpected( make_op(data_format), nhwc_to_format( np.array([[[[1], [2]], [[3], [4]]]], dtype=dtype), data_format ), expected=nhwc_to_format( np.array([[[[1, 2, 3, 4]]]], dtype=dtype), data_format ), ) self._assertOpOutputMatchesExpected( make_op(data_format), nhwc_to_format( np.array( [[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]], dtype=dtype, ), data_format, ), expected=nhwc_to_format( np.array( [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]], dtype=dtype ), data_format, ), ) self._assertOpOutputMatchesExpected( make_op(data_format), nhwc_to_format( np.array( [[ [[1], [2], [5], [6]], [[3], [4], [7], [8]], [[9], [10], [13], [14]], [[11], [12], [15], [16]], ]], dtype=dtype, ), data_format, ), expected=nhwc_to_format( np.array( [[ [[1, 2, 3, 4], [5, 6, 7, 8]], [[9, 10, 11, 12], [13, 14, 15, 16]], ]], dtype=dtype, ), data_format, ), ) self._assertOpOutputMatchesExpected( make_op("NCHW_VECT_C"), np.arange(32, dtype=dtype).reshape((1, 2, 2, 2, 4)), expected=np.array( [[ [[[0, 1, 2, 3]]], [[[16, 17, 18, 19]]], [[[4, 5, 6, 7]]], [[[20, 21, 22, 23]]], [[[8, 9, 10, 11]]], [[[24, 25, 26, 27]]], [[[12, 13, 14, 15]]], [[[28, 29, 30, 31]]], ]], dtype=dtype, ), ) def _assertSoftplusMatchesExpected( self, features, dtype, equality_test=None, rtol=1e-6, atol=9.1e-6 ): features = np.array(features, dtype=dtype) zero = np.asarray(0).astype(dtype) expected = np.logaddexp(zero, features).astype(dtype) self._assertOpOutputMatchesExpected( nn_ops.softplus, features, expected=expected, equality_test=equality_test, rtol=rtol, atol=atol, ) def testSoftplus(self): for dtype in self.float_types & {dtypes.float32, dtypes.float64}: self._assertSoftplusMatchesExpected([[-2, 0, 8]], dtype) self._assertSoftplusMatchesExpected( [[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]], dtype ) if dtype == dtypes.bfloat16.as_numpy_dtype: log_eps = np.log(np.finfo(np.float32).eps) else: log_eps = np.log(np.finfo(dtype).eps) one = dtype(1) ten = dtype(10) self._assertSoftplusMatchesExpected( [ log_eps, log_eps - one, log_eps + one, log_eps - ten, log_eps + ten, -log_eps, -log_eps - one, -log_eps + one, -log_eps - ten, -log_eps + ten, ], dtype, ) self._assertSoftplusMatchesExpected( [0.69302183, 0.69324386], dtype, equality_test=self.AssertCloseAndSorted, rtol=9e-5, atol=9e-5, ) def testToBool(self): for dtype in self.numeric_types - self.complex_types: self._assertOpOutputMatchesExpected( gen_functional_ops.to_bool, np.array(5, dtype=dtype), expected=np.array(True), ) self._assertOpOutputMatchesExpected( gen_functional_ops.to_bool, np.array(0, dtype=dtype), expected=np.array(False), ) self._assertOpOutputMatchesExpected( gen_functional_ops.to_bool, np.array([], dtype=dtype), expected=np.array(False), ) self._assertOpOutputMatchesExpected( gen_functional_ops.to_bool, np.array([1, 2, 3], dtype=dtype), expected=np.array(True), ) if __name__ == "__main__": googletest.main()
UnaryOpsTest
python
gevent__gevent
src/gevent/tests/test__monkey_queue.py
{ "start": 8519, "end": 8588 }
class ____(BaseQueueTest): type2test = Queue.LifoQueue
LifoQueueTest
python
sphinx-doc__sphinx
sphinx/domains/cpp/_ast.py
{ "start": 112027, "end": 113148 }
class ____(ASTBase): def __init__( self, value: ASTExpression | ASTBracedInitList, hasAssign: bool = True ) -> None: self.value = value self.hasAssign = hasAssign def __eq__(self, other: object) -> bool: if not isinstance(other, ASTInitializer): return NotImplemented return self.value == other.value and self.hasAssign == other.hasAssign def __hash__(self) -> int: return hash((self.value, self.hasAssign)) def _stringify(self, transform: StringifyTransform) -> str: val = transform(self.value) if self.hasAssign: return ' = ' + val else: return val def describe_signature( self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol ) -> None: verify_description_mode(mode) if self.hasAssign: signode += addnodes.desc_sig_space() signode += addnodes.desc_sig_punctuation('=', '=') signode += addnodes.desc_sig_space() self.value.describe_signature(signode, 'markType', env, symbol)
ASTInitializer
python
tensorflow__tensorflow
tensorflow/python/distribute/vars_test.py
{ "start": 3463, "end": 19315 }
class ____(test.TestCase, parameterized.TestCase): @combinations.generate(strategy_and_run_tf_function_combinations()) def testAssign(self, distribution, experimental_run_tf_function): def assign(fn, v, update_value, cross_replica): update_fn = lambda: getattr(v, fn)(update_value) if cross_replica: return update_fn() else: if experimental_run_tf_function: update_fn = def_function.function(update_fn) return test_util.gather(distribution, distribution.run(update_fn)) updates = [("assign", 1.), ("assign_add", 1.), ("assign_sub", -1.)] aggregations = [ variables_lib.VariableAggregation.NONE, variables_lib.VariableAggregation.SUM, variables_lib.VariableAggregation.MEAN, variables_lib.VariableAggregation.ONLY_FIRST_REPLICA, ] options = list( x for x in itertools.product(updates, aggregations, [True, False])) for update, aggregation, cross_replica in options: # assign in replica context with SUM does not make sense cause you can # just do value * num replicas error is 1. is not a distributed value and # is unsupported for aggregation SUM if (not cross_replica and aggregation == variables_lib.VariableAggregation.SUM): continue with distribution.scope(): v = variable_v1.VariableV1( 0., aggregation=aggregation) self.evaluate(variables_lib.global_variables_initializer()) fn, update_value = update self.evaluate(assign(fn, v, update_value, cross_replica)) for component in v._values: self.assertAllEqual(self.evaluate(component.read_value()), self.evaluate(array_ops.ones_like(component))) @combinations.generate(strategy_and_run_tf_function_combinations()) def testAssignOnWriteVar(self, distribution, experimental_run_tf_function): with distribution.scope(): v_to_assign = variable_v1.VariableV1( 2., aggregation=variables_lib.VariableAggregation.MEAN) v_to_assign_sub = variable_v1.VariableV1( -2., aggregation=variables_lib.VariableAggregation.MEAN) def assign(fn, v, update_value, cross_replica): update_fn = lambda: getattr(v, fn)(update_value) if cross_replica: return update_fn() else: if experimental_run_tf_function: update_fn = def_function.function(update_fn) return test_util.gather(distribution, distribution.run(update_fn)) updates = [("assign", v_to_assign), ("assign_add", v_to_assign), ("assign_sub", v_to_assign_sub)] aggregations = [ variables_lib.VariableAggregation.NONE, variables_lib.VariableAggregation.SUM, variables_lib.VariableAggregation.MEAN, variables_lib.VariableAggregation.ONLY_FIRST_REPLICA, ] options = list( x for x in itertools.product(updates, aggregations, [True, False])) for update, aggregation, cross_replica in options: # assign in replica context with SUM does not make sense cause you can # just do value * num replicas error is 1. is not a distributed value and # is unsupported for aggregation SUM if aggregation == variables_lib.VariableAggregation.SUM: continue with distribution.scope(): v = variable_v1.VariableV1( 0., aggregation=aggregation) self.evaluate(variables_lib.global_variables_initializer()) fn, update_value = update self.evaluate(assign(fn, v, update_value, cross_replica)) for component in v._values: self.assertAllEqual(2.0, self.evaluate(component.read_value())) @combinations.generate(strategy_and_run_tf_function_combinations()) def testAssignPerReplicaVal(self, distribution, experimental_run_tf_function): if strategy_test_lib.is_tpu_strategy(distribution): self.skipTest("Assigning PerReplica values is not supported. See" " sponge/80ba41f8-4220-4516-98ce-bbad48f9f11a.") with distribution.scope(): per_replica_value = values.PerReplica( [constant_op.constant(2.0), constant_op.constant(2.0)]) per_replica_sub_value = values.PerReplica( [constant_op.constant(-2.0), constant_op.constant(-2.0)]) def assign(fn, v, update_value, cross_replica): update_fn = lambda: getattr(v, fn)(update_value) if cross_replica: return update_fn() else: if experimental_run_tf_function: update_fn = def_function.function(update_fn) return test_util.gather(distribution, distribution.run(update_fn)) updates = [("assign", per_replica_value), ("assign_add", per_replica_value), ("assign_sub", per_replica_sub_value)] # We don't support assigning PerReplica valus to vars in replica context # with aggregation=NONE. aggregations = [ variables_lib.VariableAggregation.SUM, variables_lib.VariableAggregation.MEAN, variables_lib.VariableAggregation.ONLY_FIRST_REPLICA, ] options = list( x for x in itertools.product(updates, aggregations, [True, False])) for update, aggregation, cross_replica in options: # assign in replica context with SUM does not make sense cause you can # just do value * num replicas error is 1. is not a distributed value and # is unsupported for aggregation SUM if cross_replica: # We don't support assigning PerReplica values to MirroredVariables in # cross replica context continue with distribution.scope(): v = variable_v1.VariableV1( 0., aggregation=aggregation) self.evaluate(variables_lib.global_variables_initializer()) fn, update_value = update self.evaluate(assign(fn, v, update_value, cross_replica)) if aggregation == variables_lib.VariableAggregation.SUM: expected = 4.0 else: expected = 2.0 for component in v._values: self.assertAllEqual(expected, self.evaluate(component.read_value())) @combinations.generate(strategy_with_var_policy()) def testValueInReplicaContext(self, distribution): with distribution.scope(): v = variables_lib.Variable( 1., aggregation=variables_lib.VariableAggregation.MEAN) self.evaluate(variables_lib.global_variables_initializer()) @def_function.function def f(): with ops.control_dependencies([v.assign_add(1.)]): return v.value() results = self.evaluate( test_util.gather(distribution, distribution.run(f))) for value in results: self.assertEqual(2., value) @combinations.generate(strategy_with_var_policy()) def testValueInReplicaContextAssignDirectValue(self, distribution, use_var_policy): with distribution.scope(): v = variables_lib.Variable( 1., aggregation=variables_lib.VariableAggregation.MEAN) self.evaluate(variables_lib.global_variables_initializer()) @def_function.function def f(): with ops.control_dependencies([v.assign_add(1.)]): return v.value() results = self.evaluate( test_util.gather(distribution, distribution.run(f))) for value in results: self.assertEqual(2., value) @combinations.generate(strategy_and_run_tf_function_combinations()) def testReadValueInReplicaContext(self, distribution, experimental_run_tf_function): aggregations = [ variables_lib.VariableAggregation.NONE, variables_lib.VariableAggregation.SUM, variables_lib.VariableAggregation.MEAN, variables_lib.VariableAggregation.ONLY_FIRST_REPLICA, ] for aggregation in aggregations: with distribution.scope(): v = variable_v1.VariableV1( 0., aggregation=aggregation) self.evaluate(variables_lib.global_variables_initializer()) if experimental_run_tf_function: read_var_fn = def_function.function(v.read_value) else: read_var_fn = v.read_value results = self.evaluate( test_util.gather(distribution, distribution.run(read_var_fn))) for component, value in zip(v._values, results): self.assertAllEqual(self.evaluate(component.read_value()), value) @combinations.generate(strategy_and_run_tf_function_combinations()) def testReadValueInCrossReplicaContext(self, distribution, experimental_run_tf_function): aggregations = [ variables_lib.VariableAggregation.NONE, variables_lib.VariableAggregation.SUM, variables_lib.VariableAggregation.MEAN, variables_lib.VariableAggregation.ONLY_FIRST_REPLICA, ] for aggregation in aggregations: with distribution.scope(): v = variable_v1.VariableV1( 2., aggregation=aggregation) self.evaluate(variables_lib.global_variables_initializer()) if experimental_run_tf_function: read_var_fn = def_function.function(v.read_value) else: read_var_fn = v.read_value results = read_var_fn() for component in v._values: self.assertEqual(self.evaluate(component.read_value()), self.evaluate(results)) @combinations.generate(strategy_with_var_policy()) def testAssignOutOfScope(self, distribution): with distribution.scope(): mirrored = variables_lib.Variable(1.) self.evaluate(mirrored.assign(3.)) self.assertEqual(self.evaluate(mirrored.read_value()), 3.) for component in mirrored.values: self.assertEqual(self.evaluate(component.read_value()), 3.) @combinations.generate(strategy_with_var_policy()) def testInitializedToSameValueInsideEagerRun(self, distribution): if not context.executing_eagerly(): self.skipTest("eager only test") if isinstance(distribution.extended, collective_all_reduce_strategy.CollectiveAllReduceExtended): self.skipTest("Test for more than 1 device per worker only.") v = [None] @def_function.function def step(): def f(): if v[0] is None: v[0] = variables_lib.Variable(random_ops.random_normal([])) distribution.run(f) context.set_global_seed(None) step() vals = self.evaluate(v[0].values) self.assertAllEqual(vals[0], vals[1]) @combinations.generate(strategy_with_var_policy()) def testAggregationOnlyFirstReplica(self, distribution): if isinstance(distribution.extended, collective_all_reduce_strategy.CollectiveAllReduceExtended): self.skipTest("b/212945803") with distribution.scope(): v = variable_v1.VariableV1( 15., synchronization=variables_lib.VariableSynchronization.ON_WRITE, aggregation=variables_lib.VariableAggregation.ONLY_FIRST_REPLICA) self.evaluate(variables_lib.global_variables_initializer()) @def_function.function def assign(): ctx = distribute_lib.get_replica_context() replica_id = ctx.replica_id_in_sync_group return v.assign(math_ops.cast(replica_id, dtypes.float32)) per_replica_results = self.evaluate( test_util.gather(distribution, distribution.run(assign))) # The per-replica values should always match the first replicas value. self.assertAllEqual( array_ops.zeros(distribution.num_replicas_in_sync, dtypes.float32), per_replica_results) @combinations.generate(strategy_with_var_policy()) def testInitScope(self, distribution): if not context.executing_eagerly(): self.skipTest("eager only") class C(object): pass obj = C() obj.w = None obj.v = None @def_function.function def assign(): with ops.init_scope(): if obj.w is None: obj.w = variables_lib.Variable( 0., aggregation=variables_lib.VariableAggregation.MEAN) obj.v = variables_lib.Variable( obj.w.read_value(), aggregation=variables_lib.VariableAggregation.MEAN) self.evaluate(variables_lib.global_variables_initializer()) return obj.v.assign_add(2.) per_replica_results = self.evaluate( test_util.gather(distribution, distribution.run(assign))) self.assertAllEqual([2., 2.], per_replica_results) @combinations.generate(strategy_with_var_policy()) def testOperatorOverride(self, distribution): if not context.executing_eagerly() and isinstance( distribution.extended, collective_all_reduce_strategy.CollectiveAllReduceExtended): self.skipTest("b/212954197") with distribution.scope(): v = variable_v1.VariableV1( 1, aggregation=variables_lib.VariableAggregation.SUM) self.evaluate(variables_lib.global_variables_initializer()) self.assertEqual(2, self.evaluate(v + 1)) @def_function.function def add(): return v + 1 per_replica_results = self.evaluate( test_util.gather(distribution, distribution.run(add))) self.assertAllEqual([2, 2], per_replica_results) @combinations.generate( combinations.combine( strategy=[ strategy_combinations.mirrored_strategy_with_gpu_and_cpu, strategy_combinations.tpu_strategy, strategy_combinations.tpu_strategy_packed_var, strategy_combinations.multi_worker_mirrored_2x1_cpu, strategy_combinations.multi_worker_mirrored_2x1_gpu, ], mode=["eager"], use_var_policy=[True, False])) def testSaveAndRestoreOnWrite(self, strategy): aggregation = [ variable_scope.VariableAggregation.NONE, variable_scope.VariableAggregation.ONLY_FIRST_REPLICA, variable_scope.VariableAggregation.SUM, variable_scope.VariableAggregation.MEAN ] for agg in aggregation: v_normal_restore = variables_lib.Variable(1.0) v_normal_save = variables_lib.Variable(3.0) with strategy.scope(): v_on_write = variables_lib.Variable(2.0, aggregation=agg) # Save ONWRITE Restore ONWRITE # Save ckpt = trackable_utils.Checkpoint(var=v_on_write) manager = ckpt_manager.CheckpointManager( ckpt, "/tmp/ckpt_" + str(uuid.uuid4()), max_to_keep=None) manager.save() # Restore ckpt.restore(manager.latest_checkpoint) self.assertEqual(2.0, self.evaluate(v_on_write._values[0])) self.assertEqual(2.0, self.evaluate(v_on_write.read_value())) # Save Mirrored Restore Normal # We've already saved Mirrored, so we only need to restore normal ckpt_normal = trackable_utils.Checkpoint(var=v_normal_restore) ckpt_normal.restore(manager.latest_checkpoint) self.assertEqual(2.0, self.evaluate(v_on_write._values[0])) self.assertEqual(2.0, self.evaluate(v_normal_restore.read_value())) # Save Normal Restore Mirrored # Save ckpt = trackable_utils.Checkpoint(var=v_normal_save) manager_2 = ckpt_manager.CheckpointManager( ckpt, "/tmp/ckptckpt_" + str(uuid.uuid4()), max_to_keep=None) manager_2.save() # Restore ckpt_on_write = trackable_utils.Checkpoint(var=v_on_write) ckpt_on_write.restore(manager_2.latest_checkpoint) self.assertEqual(3.0, self.evaluate(v_on_write._values[0])) self.assertEqual(3.0, self.evaluate(v_on_write.read_value())) ms_combination = combinations.combine( distribution=[strategy_combinations.mirrored_strategy_with_gpu_and_cpu], mode=["graph", "eager"]) tpu_combination = combinations.combine( distribution=[strategy_combinations.tpu_strategy_packed_var], mode=["graph", "eager"])
OnWriteVariableSync
python
tensorflow__tensorflow
tensorflow/python/framework/error_interpolation_test.py
{ "start": 2767, "end": 3806 }
class ____(test.TestCase): def testCorrectFormatWithActiveDeviceAssignments(self): assignments = [] assignments.append( traceable_stack.TraceableObject("/cpu:0", filename="hope.py", lineno=24) ) assignments.append( traceable_stack.TraceableObject( "/gpu:2", filename="please.py", lineno=42 ) ) summary = error_interpolation._compute_device_summary_from_list( "nodename", assignments, prefix=" " ) self.assertIn("nodename", summary) self.assertIn("tf.device(/cpu:0)", summary) self.assertIn("<hope.py:24>", summary) self.assertIn("tf.device(/gpu:2)", summary) self.assertIn("<please.py:42>", summary) def testCorrectFormatWhenNoColocationsWereActive(self): device_assignment_list = [] summary = error_interpolation._compute_device_summary_from_list( "nodename", device_assignment_list, prefix=" " ) self.assertIn("nodename", summary) self.assertIn("No device assignments", summary)
ComputeDeviceSummaryFromOpTest
python
django-guardian__django-guardian
guardian/managers.py
{ "start": 369, "end": 6297 }
class ____(models.Manager): @property def user_or_group_field(self) -> str: try: self.model._meta.get_field("user") return "user" except FieldDoesNotExist: return "group" def is_generic(self) -> bool: try: self.model._meta.get_field("object_pk") return True except FieldDoesNotExist: return False def assign_perm(self, perm: str, user_or_group: Any, obj: Model) -> Any: """Assigns permission with given `perm` for an instance `obj` and `user`.""" if getattr(obj, "pk", None) is None: raise ObjectNotPersisted("Object %s needs to be persisted first" % obj) ctype = get_content_type(obj) if not isinstance(perm, Permission): permission = Permission.objects.get(content_type=ctype, codename=perm) else: permission = perm kwargs = {"permission": permission, self.user_or_group_field: user_or_group} if self.is_generic(): kwargs["content_type"] = ctype kwargs["object_pk"] = obj.pk else: kwargs["content_object"] = obj obj_perm, _ = self.get_or_create(**kwargs) return obj_perm def bulk_assign_perm( self, perm: str, user_or_group: Any, queryset: QuerySet, ignore_conflicts: bool = False ) -> Any: """ Bulk assigns permissions with given `perm` for an objects in `queryset` and `user_or_group`. """ if isinstance(queryset, list): ctype = get_content_type(queryset[0]) else: ctype = get_content_type(queryset.model) if not isinstance(perm, Permission): permission = Permission.objects.get(content_type=ctype, codename=perm) else: permission = perm checker = ObjectPermissionChecker(user_or_group) checker.prefetch_perms(queryset) assigned_perms = [] for instance in queryset: if not checker.has_perm(permission.codename, instance): kwargs = {"permission": permission, self.user_or_group_field: user_or_group} if self.is_generic(): kwargs["content_type"] = ctype kwargs["object_pk"] = instance.pk else: kwargs["content_object"] = instance assigned_perms.append(self.model(**kwargs)) self.model.objects.bulk_create(assigned_perms, ignore_conflicts=ignore_conflicts) return assigned_perms def assign_perm_to_many(self, perm: str, users_or_groups: Any, obj: Model, ignore_conflicts: bool = False) -> Any: """ Bulk assigns given `perm` for the object `obj` to a set of users or a set of groups. """ ctype = get_content_type(obj) if not isinstance(perm, Permission): permission = Permission.objects.get(content_type=ctype, codename=perm) else: permission = perm kwargs = {"permission": permission} if self.is_generic(): kwargs["content_type"] = ctype kwargs["object_pk"] = obj.pk else: kwargs["content_object"] = obj to_add = [] field = self.user_or_group_field for user in users_or_groups: kwargs[field] = user to_add.append(self.model(**kwargs)) return self.model.objects.bulk_create(to_add, ignore_conflicts=ignore_conflicts) def assign(self, perm: str, user_or_group: Any, obj: Model) -> Any: """Depreciated function name left in for compatibility""" warnings.warn( "UserObjectPermissionManager method 'assign' is being renamed to 'assign_perm'. Update your code accordingly as old name will be depreciated in 2.0 version.", DeprecationWarning, ) return self.assign_perm(perm, user_or_group, obj) def remove_perm(self, perm: str, user_or_group: Any, obj: Model) -> tuple[int, dict]: """ Removes permission `perm` for an instance `obj` and given `user_or_group`. Please note that we do NOT fetch object permission from database - we use `Queryset.delete` method for removing it. The main implication of this is that `post_delete` signals would NOT be fired. """ if getattr(obj, "pk", None) is None: raise ObjectNotPersisted("Object %s needs to be persisted first" % obj) filters = Q(**{self.user_or_group_field: user_or_group}) if isinstance(perm, Permission): filters &= Q(permission=perm) else: filters &= Q(permission__codename=perm, permission__content_type=get_content_type(obj)) if self.is_generic(): filters &= Q(object_pk=obj.pk) else: filters &= Q(content_object__pk=obj.pk) return self.filter(filters).delete() def bulk_remove_perm(self, perm: str, user_or_group: Any, queryset: QuerySet) -> tuple[int, dict]: """ Removes permission `perm` for a `queryset` and given `user_or_group`. Please note that we do NOT fetch object permission from database - we use `Queryset.delete` method for removing it. The main implication of this is that `post_delete` signals would NOT be fired. """ filters = Q(**{self.user_or_group_field: user_or_group}) if isinstance(perm, Permission): filters &= Q(permission=perm) else: ctype = get_content_type(queryset.model) filters &= Q(permission__codename=perm, permission__content_type=ctype) if self.is_generic(): filters &= Q(object_pk__in=[str(pk) for pk in queryset.values_list("pk", flat=True)]) else: filters &= Q(content_object__in=queryset) return self.filter(filters).delete()
BaseObjectPermissionManager
python
encode__django-rest-framework
tests/test_generics.py
{ "start": 13474, "end": 14198 }
class ____(TestCase): def setUp(self): self.objects = Comment.objects self.view = CommentView.as_view() def test_create_model_with_auto_now_add_field(self): """ Regression test for #285 https://github.com/encode/django-rest-framework/issues/285 """ data = {'email': 'foobar@example.com', 'content': 'foobar'} request = factory.post('/', data, format='json') response = self.view(request).render() assert response.status_code == status.HTTP_201_CREATED created = self.objects.get(id=1) assert created.content == 'foobar' # Test for particularly ugly regression with m2m in browsable API
TestCreateModelWithAutoNowAddField
python
lepture__authlib
authlib/jose/errors.py
{ "start": 2235, "end": 2355 }
class ____(JoseError): error = "invalid_use" description = "Key 'use' is not valid for your usage"
InvalidUseError
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/base.py
{ "start": 42301, "end": 42373 }
class ____(_UnicodeLiteral, sqltypes.UnicodeText): pass
_MSUnicodeText
python
pytest-dev__pluggy
docs/examples/eggsample/eggsample/host.py
{ "start": 532, "end": 1579 }
class ____: FAVORITE_INGREDIENTS = ("egg", "egg", "egg") def __init__(self, hook): self.hook = hook self.ingredients = None def add_ingredients(self): results = self.hook.eggsample_add_ingredients( ingredients=self.FAVORITE_INGREDIENTS ) my_ingredients = list(self.FAVORITE_INGREDIENTS) # Each hook returns a list - so we chain this list of lists other_ingredients = list(itertools.chain(*results)) self.ingredients = my_ingredients + other_ingredients def prepare_the_food(self): random.shuffle(self.ingredients) def serve_the_food(self): condiment_comments = self.hook.eggsample_prep_condiments( condiments=condiments_tray ) print(f"Your food. Enjoy some {', '.join(self.ingredients)}") print(f"Some condiments? We have {', '.join(condiments_tray.keys())}") if any(condiment_comments): print("\n".join(condiment_comments)) if __name__ == "__main__": main()
EggsellentCook
python
pypa__pip
tests/unit/test_network_session.py
{ "start": 2167, "end": 10535 }
class ____: def test_cache_defaults_off(self) -> None: session = PipSession() assert not hasattr(session.adapters["http://"], "cache") assert not hasattr(session.adapters["https://"], "cache") def test_cache_is_enabled(self, tmpdir: Path) -> None: cache_directory = os.fspath(tmpdir.joinpath("test-cache")) session = PipSession(cache=cache_directory) assert hasattr(session.adapters["https://"], "cache") assert session.adapters["https://"].cache.directory == cache_directory def test_http_cache_is_not_enabled(self, tmpdir: Path) -> None: session = PipSession(cache=os.fspath(tmpdir.joinpath("test-cache"))) assert not hasattr(session.adapters["http://"], "cache") def test_trusted_hosts_adapter(self, tmpdir: Path) -> None: session = PipSession( cache=os.fspath(tmpdir.joinpath("test-cache")), trusted_hosts=["example.com"], ) assert "https://example.com/" in session.adapters # Check that the "port wildcard" is present. assert "https://example.com:" in session.adapters # Check that the cache is enabled. assert hasattr(session.adapters["http://example.com/"], "cache") assert hasattr(session.adapters["https://example.com/"], "cache") def test_add_trusted_host(self) -> None: # Leave a gap to test how the ordering is affected. trusted_hosts = ["host1", "host3"] session = PipSession(trusted_hosts=trusted_hosts) trusted_host_adapter = session._trusted_host_adapter prefix2 = "https://host2/" prefix3 = "https://host3/" prefix3_wildcard = "https://host3:" prefix2_http = "http://host2/" prefix3_http = "http://host3/" prefix3_wildcard_http = "http://host3:" # Confirm some initial conditions as a baseline. assert session.pip_trusted_origins == [("host1", None), ("host3", None)] assert session.adapters[prefix3] is trusted_host_adapter assert session.adapters[prefix3_wildcard] is trusted_host_adapter assert session.adapters[prefix3_http] is trusted_host_adapter assert session.adapters[prefix3_wildcard_http] is trusted_host_adapter assert prefix2 not in session.adapters assert prefix2_http not in session.adapters # Test adding a new host. session.add_trusted_host("host2") assert session.pip_trusted_origins == [ ("host1", None), ("host3", None), ("host2", None), ] # Check that prefix3 is still present. assert session.adapters[prefix3] is trusted_host_adapter assert session.adapters[prefix2] is trusted_host_adapter assert session.adapters[prefix2_http] is trusted_host_adapter # Test that adding the same host doesn't create a duplicate. session.add_trusted_host("host3") assert session.pip_trusted_origins == [ ("host1", None), ("host3", None), ("host2", None), ], f"actual: {session.pip_trusted_origins}" session.add_trusted_host("host4:8080") prefix4 = "https://host4:8080/" prefix4_http = "http://host4:8080/" assert session.pip_trusted_origins == [ ("host1", None), ("host3", None), ("host2", None), ("host4", 8080), ] assert session.adapters[prefix4] is trusted_host_adapter assert session.adapters[prefix4_http] is trusted_host_adapter def test_add_trusted_host__logging(self, caplog: pytest.LogCaptureFixture) -> None: """ Test logging when add_trusted_host() is called. """ trusted_hosts = ["host0", "host1"] session = PipSession(trusted_hosts=trusted_hosts) with caplog.at_level(logging.INFO): # Test adding an existing host. session.add_trusted_host("host1", source="somewhere") session.add_trusted_host("host2") # Test calling add_trusted_host() on the same host twice. session.add_trusted_host("host2") actual = [(r.levelname, r.message) for r in caplog.records] # Observe that "host0" isn't included in the logs. expected = [ ("INFO", "adding trusted host: 'host1' (from somewhere)"), ("INFO", "adding trusted host: 'host2'"), ("INFO", "adding trusted host: 'host2'"), ] assert actual == expected def test_iter_secure_origins(self) -> None: trusted_hosts = ["host1", "host2", "host3:8080"] session = PipSession(trusted_hosts=trusted_hosts) actual = list(session.iter_secure_origins()) assert len(actual) == 9 # Spot-check that SECURE_ORIGINS is included. assert actual[0] == ("https", "*", "*") assert actual[-3:] == [ ("*", "host1", "*"), ("*", "host2", "*"), ("*", "host3", 8080), ] def test_iter_secure_origins__trusted_hosts_empty(self) -> None: """ Test iter_secure_origins() after passing trusted_hosts=[]. """ session = PipSession(trusted_hosts=[]) actual = list(session.iter_secure_origins()) assert len(actual) == 6 # Spot-check that SECURE_ORIGINS is included. assert actual[0] == ("https", "*", "*") @pytest.mark.parametrize( "location, trusted, expected", [ ("http://pypi.org/something", [], False), ("https://pypi.org/something", [], True), ("git+http://pypi.org/something", [], False), ("git+https://pypi.org/something", [], True), ("git+ssh://git@pypi.org/something", [], True), ("http://localhost", [], True), ("http://127.0.0.1", [], True), ("http://example.com/something/", [], False), ("http://example.com/something/", ["example.com"], True), # Try changing the case. ("http://eXample.com/something/", ["example.cOm"], True), # Test hosts with port. ("http://example.com:8080/something/", ["example.com"], True), # Test a trusted_host with a port. ("http://example.com:8080/something/", ["example.com:8080"], True), ("http://example.com/something/", ["example.com:8080"], False), ("http://example.com:8888/something/", ["example.com:8080"], False), ], ) def test_is_secure_origin( self, caplog: pytest.LogCaptureFixture, location: str, trusted: list[str], expected: bool, ) -> None: class MockLogger: def __init__(self) -> None: self.called = False def warning(self, *args: Any, **kwargs: Any) -> None: self.called = True session = PipSession(trusted_hosts=trusted) actual = session.is_secure_origin(Link(location)) assert actual == expected log_records = [(r.levelname, r.message) for r in caplog.records] if expected: assert not log_records return assert len(log_records) == 1 actual_level, actual_message = log_records[0] assert actual_level == "WARNING" assert "is not a trusted or secure host" in actual_message @pytest.mark.network def test_proxy(self, proxy: str | None) -> None: session = PipSession(trusted_hosts=[]) if not proxy: # if user didn't pass --proxy then try to get it from the system. env_proxy = getproxies().get("http", None) proxy = urlparse(env_proxy).netloc if env_proxy else None if proxy: # set proxy scheme to session.proxies session.proxies = { "http": f"{proxy}", "https": f"{proxy}", "ftp": f"{proxy}", } connection_error = None try: session.request("GET", "https://pypi.org", timeout=1) except requests.exceptions.ConnectionError as e: connection_error = e assert connection_error is None, ( f"Invalid proxy {proxy} or session.proxies: " f"{session.proxies} is not correctly passed to session.request." )
TestPipSession
python
ray-project__ray
rllib/examples/rl_modules/classes/vpg_using_shared_encoder_rlm.py
{ "start": 8551, "end": 9562 }
class ____(TorchRLModule): """ A VPG (vanilla pol. gradient)-style RLModule that doesn't use a shared encoder. Facilitates experiments comparing shared and individual encoder architectures. """ def setup(self): super().setup() # Incoming feature dim from the encoder. embedding_dim = self.model_config["embedding_dim"] hidden_dim = self.model_config["hidden_dim"] self._pi_head = torch.nn.Sequential( torch.nn.Linear(embedding_dim, hidden_dim), torch.nn.ReLU(), torch.nn.Linear(hidden_dim, self.action_space.n), ) self.encoder = VPGIndividualEncoder(self.observation_space, embedding_dim) def _forward(self, batch, **kwargs): if ENCODER_OUT not in batch: batch = self.encoder(batch) embeddings = batch[ENCODER_OUT] logits = self._pi_head(embeddings) return {Columns.ACTION_DIST_INPUTS: logits} # __sphinx_doc_ns_policy_end__
VPGPolicyNoSharedEncoder
python
django__django
tests/admin_views/models.py
{ "start": 18026, "end": 18527 }
class ____(models.Model): question = models.ForeignKey(Question, models.PROTECT) question_with_to_field = models.ForeignKey( Question, models.SET_NULL, blank=True, null=True, to_field="uuid", related_name="uuid_answers", limit_choices_to=~models.Q(question__istartswith="not"), ) related_answers = models.ManyToManyField("self") answer = models.CharField(max_length=20) def __str__(self): return self.answer
Answer
python
doocs__leetcode
solution/1900-1999/1905.Count Sub Islands/Solution.py
{ "start": 0, "end": 560 }
class ____: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: def dfs(i: int, j: int) -> int: ok = grid1[i][j] grid2[i][j] = 0 for a, b in pairwise(dirs): x, y = i + a, j + b if 0 <= x < m and 0 <= y < n and grid2[x][y] and not dfs(x, y): ok = 0 return ok m, n = len(grid1), len(grid1[0]) dirs = (-1, 0, 1, 0, -1) return sum(dfs(i, j) for i in range(m) for j in range(n) if grid2[i][j])
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/scheduler/instigation.py
{ "start": 11404, "end": 11637 }
class ____(Enum): STARTED = "STARTED" SKIPPED = "SKIPPED" SUCCESS = "SUCCESS" FAILURE = "FAILURE" @whitelist_for_serdes( old_storage_names={"JobTick"}, storage_field_names={"tick_data": "job_tick_data"} )
TickStatus
python
coleifer__peewee
tests/results.py
{ "start": 263, "end": 4278 }
class ____(ModelTestCase): database = get_in_memory_db() requires = [User] def test_iteration(self): for i in range(10): User.create(username=str(i)) query = User.select() cursor = query.execute() first_five = [] for i, u in enumerate(cursor): first_five.append(int(u.username)) if i == 4: break self.assertEqual(first_five, lange(5)) names = lambda i: [int(obj.username) for obj in i] self.assertEqual(names(query[5:]), lange(5, 10)) self.assertEqual(names(query[2:5]), lange(2, 5)) for i in range(2): self.assertEqual(names(cursor), lange(10)) def test_count(self): for i in range(5): User.create(username=str(i)) with self.assertQueryCount(1): query = User.select() self.assertEqual(len(query), 5) cursor = query.execute() self.assertEqual(len(cursor), 5) with self.assertQueryCount(1): query = query.where(User.username != '0') cursor = query.execute() self.assertEqual(len(cursor), 4) self.assertEqual(len(query), 4) def test_nested_iteration(self): for i in range(4): User.create(username=str(i)) with self.assertQueryCount(1): query = User.select().order_by(User.username) outer = [] inner = [] for o_user in query: outer.append(int(o_user.username)) for i_user in query: inner.append(int(i_user.username)) self.assertEqual(outer, lange(4)) self.assertEqual(inner, lange(4) * 4) def test_iterator_protocol(self): for i in range(3): User.create(username=str(i)) with self.assertQueryCount(1): query = User.select().order_by(User.id) cursor = query.execute() for _ in range(2): for user in cursor: pass it = iter(cursor) for obj in it: pass self.assertRaises(StopIteration, next, it) self.assertEqual([int(u.username) for u in cursor], lange(3)) self.assertEqual(query[0].username, '0') self.assertEqual(query[2].username, '2') self.assertRaises(StopIteration, next, it) def test_iterator(self): for i in range(3): User.create(username=str(i)) with self.assertQueryCount(1): cursor = User.select().order_by(User.id).execute() usernames = [int(u.username) for u in cursor.iterator()] self.assertEqual(usernames, lange(3)) self.assertTrue(cursor.populated) self.assertEqual(cursor.row_cache, []) with self.assertQueryCount(0): self.assertEqual(list(cursor), []) def test_query_iterator(self): for i in range(3): User.create(username=str(i)) with self.assertQueryCount(1): query = User.select().order_by(User.id) usernames = [int(u.username) for u in query.iterator()] self.assertEqual(usernames, lange(3)) with self.assertQueryCount(0): self.assertEqual(list(query), []) def test_row_cache(self): def assertCache(cursor, n): self.assertEqual([int(u.username) for u in cursor.row_cache], lange(n)) for i in range(10): User.create(username=str(i)) with self.assertQueryCount(1): cursor = User.select().order_by(User.id).execute() cursor.fill_cache(5) self.assertFalse(cursor.populated) assertCache(cursor, 5) cursor.fill_cache(5) assertCache(cursor, 5) cursor.fill_cache(6) assertCache(cursor, 6) self.assertFalse(cursor.populated) cursor.fill_cache(11) self.assertTrue(cursor.populated) assertCache(cursor, 10)
TestCursorWrapper
python
apache__airflow
providers/google/tests/unit/google/cloud/sensors/test_dataproc.py
{ "start": 1477, "end": 6282 }
class ____: def create_job(self, state: int): job = mock.Mock() job.status = mock.Mock() job.status.state = state return job @mock.patch(DATAPROC_PATH.format("DataprocHook")) def test_done(self, mock_hook): job = self.create_job(JobStatus.State.DONE) job_id = "job_id" mock_hook.return_value.get_job.return_value = job sensor = DataprocJobSensor( task_id=TASK_ID, region=GCP_LOCATION, project_id=GCP_PROJECT, dataproc_job_id=job_id, gcp_conn_id=GCP_CONN_ID, timeout=TIMEOUT, ) ret = sensor.poke(context={}) mock_hook.return_value.get_job.assert_called_once_with( job_id=job_id, region=GCP_LOCATION, project_id=GCP_PROJECT ) assert ret @mock.patch(DATAPROC_PATH.format("DataprocHook")) def test_error(self, mock_hook): job = self.create_job(JobStatus.State.ERROR) job_id = "job_id" mock_hook.return_value.get_job.return_value = job sensor = DataprocJobSensor( task_id=TASK_ID, region=GCP_LOCATION, project_id=GCP_PROJECT, dataproc_job_id=job_id, gcp_conn_id=GCP_CONN_ID, timeout=TIMEOUT, ) with pytest.raises(AirflowException, match="Job failed"): sensor.poke(context={}) mock_hook.return_value.get_job.assert_called_once_with( job_id=job_id, region=GCP_LOCATION, project_id=GCP_PROJECT ) @mock.patch(DATAPROC_PATH.format("DataprocHook")) def test_wait(self, mock_hook): job = self.create_job(JobStatus.State.RUNNING) job_id = "job_id" mock_hook.return_value.get_job.return_value = job sensor = DataprocJobSensor( task_id=TASK_ID, region=GCP_LOCATION, project_id=GCP_PROJECT, dataproc_job_id=job_id, gcp_conn_id=GCP_CONN_ID, timeout=TIMEOUT, ) ret = sensor.poke(context={}) mock_hook.return_value.get_job.assert_called_once_with( job_id=job_id, region=GCP_LOCATION, project_id=GCP_PROJECT ) assert not ret @mock.patch(DATAPROC_PATH.format("DataprocHook")) def test_cancelled(self, mock_hook): job = self.create_job(JobStatus.State.CANCELLED) job_id = "job_id" mock_hook.return_value.get_job.return_value = job sensor = DataprocJobSensor( task_id=TASK_ID, region=GCP_LOCATION, project_id=GCP_PROJECT, dataproc_job_id=job_id, gcp_conn_id=GCP_CONN_ID, timeout=TIMEOUT, ) with pytest.raises(AirflowException, match="Job was cancelled"): sensor.poke(context={}) mock_hook.return_value.get_job.assert_called_once_with( job_id=job_id, region=GCP_LOCATION, project_id=GCP_PROJECT ) @mock.patch(DATAPROC_PATH.format("DataprocHook")) def test_missing_region(self, mock_hook): with pytest.raises((TypeError, AirflowException), match="missing keyword argument 'region'"): DataprocJobSensor( task_id=TASK_ID, project_id=GCP_PROJECT, dataproc_job_id="job_id", gcp_conn_id=GCP_CONN_ID, timeout=TIMEOUT, ) @mock.patch(DATAPROC_PATH.format("DataprocHook")) def test_wait_timeout(self, mock_hook): job_id = "job_id" mock_hook.return_value.get_job.side_effect = ServerError("Job are not ready") sensor = DataprocJobSensor( task_id=TASK_ID, region=GCP_LOCATION, project_id=GCP_PROJECT, dataproc_job_id=job_id, gcp_conn_id=GCP_CONN_ID, timeout=TIMEOUT, wait_timeout=300, ) sensor._duration = Mock() sensor._duration.return_value = 200 result = sensor.poke(context={}) assert not result @mock.patch(DATAPROC_PATH.format("DataprocHook")) def test_wait_timeout_raise_exception(self, mock_hook): job_id = "job_id" mock_hook.return_value.get_job.side_effect = ServerError("Job are not ready") sensor = DataprocJobSensor( task_id=TASK_ID, region=GCP_LOCATION, project_id=GCP_PROJECT, dataproc_job_id=job_id, gcp_conn_id=GCP_CONN_ID, timeout=TIMEOUT, wait_timeout=300, ) sensor._duration = Mock() sensor._duration.return_value = 301 with pytest.raises(AirflowException, match="Timeout: dataproc job job_id is not ready after 300s"): sensor.poke(context={})
TestDataprocJobSensor
python
getsentry__sentry
tests/snuba/api/endpoints/test_organization_events_timeseries_logs.py
{ "start": 390, "end": 7073 }
class ____(OrganizationEventsEndpointTestBase): endpoint = "sentry-api-0-organization-events-timeseries" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.start = self.day_ago = before_now(days=1).replace( hour=10, minute=0, second=0, microsecond=0 ) self.end = self.start + timedelta(hours=6) self.two_days_ago = self.day_ago - timedelta(days=1) self.url = reverse( self.endpoint, kwargs={"organization_id_or_slug": self.project.organization.slug}, ) def _do_request(self, data, url=None, features=None): if features is None: features = {"organizations:ourlogs": True} features.update(self.features) with self.feature(features): return self.client.get(self.url if url is None else url, data=data, format="json") def test_count(self) -> None: event_counts = [6, 0, 6, 3, 0, 3] logs = [] for hour, count in enumerate(event_counts): logs.extend( [ self.create_ourlog( {"body": "foo"}, timestamp=self.start + timedelta(hours=hour, minutes=minute), attributes={"status": {"string_value": "success"}}, ) for minute in range(count) ], ) self.store_ourlogs(logs) response = self._do_request( data={ "start": self.start, "end": self.end, "interval": "1h", "yAxis": "count()", "project": self.project.id, "dataset": "logs", }, ) assert response.status_code == 200, response.content assert response.data["meta"] == { "dataset": "logs", "start": self.start.timestamp() * 1000, "end": self.end.timestamp() * 1000, } assert len(response.data["timeSeries"]) == 1 timeseries = response.data["timeSeries"][0] assert len(timeseries["values"]) == 6 assert timeseries["yAxis"] == "count()" assert timeseries["values"] == build_expected_timeseries( self.start, 3_600_000, event_counts, sample_count=event_counts, sample_rate=[1 if val else None for val in event_counts], confidence=[any_confidence if val else None for val in event_counts], ) assert timeseries["meta"] == { "dataScanned": "full", "valueType": "integer", "valueUnit": None, "interval": 3_600_000, } def test_top_events(self) -> None: self.store_ourlogs( [ self.create_ourlog( {"body": "foo"}, timestamp=self.start + timedelta(minutes=1), attributes={"environment": {"string_value": "prod"}}, ), self.create_ourlog( {"body": "foo"}, timestamp=self.start + timedelta(minutes=1), attributes={"environment": {"string_value": "dev"}}, ), self.create_ourlog( {"body": "foo"}, timestamp=self.start + timedelta(minutes=1), attributes={"environment": {"string_value": "prod"}}, ), self.create_ourlog( {"body": "foo"}, timestamp=self.start + timedelta(minutes=1), attributes={"environment": {"string_value": "dev"}}, ), ] ) self.end = self.start + timedelta(minutes=6) response = self._do_request( data={ "start": self.start, "end": self.end, "interval": "1m", "yAxis": "count()", "groupBy": ["environment"], "project": self.project.id, "dataset": "logs", "excludeOther": 0, "topEvents": 2, } ) assert response.status_code == 200, response.content assert response.data["meta"] == { "dataset": "logs", "start": self.start.timestamp() * 1000, "end": self.end.timestamp() * 1000, } assert len(response.data["timeSeries"]) == 2 timeseries = response.data["timeSeries"][0] assert len(timeseries["values"]) == 6 assert timeseries["yAxis"] == "count()" assert timeseries["values"] == build_expected_timeseries( self.start, 60_000, [0, 2, 0, 0, 0, 0], ignore_accuracy=True ) assert timeseries["groupBy"] == [{"key": "environment", "value": "prod"}] assert timeseries["meta"] == { "dataScanned": "full", "valueType": "integer", "valueUnit": None, "interval": 60_000, "isOther": False, "order": 0, } timeseries = response.data["timeSeries"][1] assert len(timeseries["values"]) == 6 assert timeseries["yAxis"] == "count()" assert timeseries["values"] == build_expected_timeseries( self.start, 60_000, [0, 2, 0, 0, 0, 0], ignore_accuracy=True ) assert timeseries["groupBy"] == [{"key": "environment", "value": "dev"}] assert timeseries["meta"] == { "dataScanned": "full", "valueType": "integer", "valueUnit": None, "interval": 60_000, "isOther": False, "order": 1, } def test_zerofill(self) -> None: response = self._do_request( data={ "start": self.start, "end": self.end, "interval": "1h", "yAxis": "count()", "project": self.project.id, "dataset": "logs", }, ) assert response.status_code == 200, response.content assert response.data["meta"] == { "dataset": "logs", "start": self.start.timestamp() * 1000, "end": self.end.timestamp() * 1000, } assert len(response.data["timeSeries"]) == 1 timeseries = response.data["timeSeries"][0] assert len(timeseries["values"]) == 7 assert timeseries["values"] == build_expected_timeseries( self.start, 3_600_000, [0] * 7, )
OrganizationEventsStatsOurlogsMetricsEndpointTest
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_heapq.py
{ "start": 17449, "end": 17573 }
class ____(_TestErrorHandling, __TestCase): module = c_heapq if __name__ == "__main__": run_tests()
TestErrorHandlingC
python
getsentry__sentry
src/sentry/preprod/analytics.py
{ "start": 883, "end": 1103 }
class ____(analytics.Event): organization_id: int project_id: int user_id: int | None = None artifact_id: str @analytics.eventclass("preprod_artifact.api.list_builds")
PreprodArtifactApiGetBuildDetailsEvent
python
bokeh__bokeh
tests/unit/bokeh/core/property/test_validation__property.py
{ "start": 2149, "end": 2929 }
class ____: def test_validate(self) -> None: assert validation_on() with bcpv.validate(False): assert not validation_on() assert validation_on() with bcpv.validate(False): assert not validation_on() with bcpv.validate(True): assert validation_on() assert not validation_on() assert validation_on() bcpv.validate(False) assert not validation_on() bcpv.validate(True) assert validation_on() def test_without_property_validation(self) -> None: @bcpv.without_property_validation def f(): assert not validation_on() assert validation_on() f() assert validation_on()
TestValidationControl
python
django-extensions__django-extensions
tests/management/commands/test_generate_secret_key.py
{ "start": 141, "end": 643 }
class ____(TestCase): """Tests for generate_secret_key command.""" @patch( "django_extensions.management.commands.generate_secret_key.get_random_secret_key" ) @patch("sys.stdout", new_callable=StringIO) def test_should_return_random_secret_key(self, m_stdout, m_get_random_secret): m_get_random_secret.return_value = "random_secret_key" call_command("generate_secret_key") self.assertIn("random_secret_key", m_stdout.getvalue())
GenerateSecretKeyTests
python
getsentry__sentry
src/sentry/organizations/services/organization/service.py
{ "start": 20842, "end": 22104 }
class ____(abc.ABC): @abc.abstractmethod def schedule_signal( self, signal: Signal, organization_id: int, args: Mapping[str, int | str | None], ) -> None: pass def _signal_from_outbox() -> OrganizationSignalService: from sentry.organizations.services.organization.impl import ( OutboxBackedOrganizationSignalService, ) return OutboxBackedOrganizationSignalService() def _signal_from_on_commit() -> OrganizationSignalService: from sentry.organizations.services.organization.impl import ( OnCommitBackedOrganizationSignalService, ) return OnCommitBackedOrganizationSignalService() _organization_check_service: OrganizationCheckService = silo_mode_delegation( { SiloMode.REGION: _region_check_organization, SiloMode.CONTROL: _control_check_organization, SiloMode.MONOLITH: _region_check_organization, } ) _organization_signal_service: OrganizationSignalService = silo_mode_delegation( { SiloMode.REGION: _signal_from_on_commit, SiloMode.CONTROL: _signal_from_outbox, SiloMode.MONOLITH: _signal_from_on_commit, } ) organization_service = OrganizationService.create_delegation()
OrganizationSignalService
python
getsentry__sentry
tests/sentry/seer/explorer/test_explorer_client.py
{ "start": 336, "end": 12993 }
class ____(TestCase): def setUp(self): super().setUp() self.user = self.create_user() self.organization = self.create_organization(owner=self.user) @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") def test_client_init_checks_access(self, mock_access): """Test that client initialization checks access and raises on denial""" mock_access.return_value = (False, "Feature flag not enabled") with pytest.raises(SeerPermissionError) as exc_info: SeerExplorerClient(self.organization, self.user) assert "Feature flag not enabled" in str(exc_info.value) @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") def test_client_init_succeeds_with_access(self, mock_access): """Test that client initialization succeeds with proper access""" mock_access.return_value = (True, None) client = SeerExplorerClient(self.organization, self.user) assert client.organization == self.organization assert client.user == self.user assert client.artifact_schema is None @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") def test_client_init_with_artifact_schema(self, mock_access): """Test that client stores artifact schema""" mock_access.return_value = (True, None) class TestSchema(BaseModel): count: int client = SeerExplorerClient(self.organization, self.user, artifact_schema=TestSchema) assert client.artifact_schema == TestSchema @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") @patch("sentry.seer.explorer.client.requests.post") @patch("sentry.seer.explorer.client.collect_user_org_context") def test_start_run_basic(self, mock_collect_context, mock_post, mock_access): """Test starting a new run collects user context""" mock_access.return_value = (True, None) mock_collect_context.return_value = {"user_id": self.user.id} mock_response = MagicMock() mock_response.json.return_value = {"run_id": 123} mock_post.return_value = mock_response client = SeerExplorerClient(self.organization, self.user) run_id = client.start_run("Test query") assert run_id == 123 mock_collect_context.assert_called_once_with(self.user, self.organization) assert mock_post.called @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") @patch("sentry.seer.explorer.client.requests.post") def test_start_run_with_optional_params(self, mock_post, mock_access): """Test starting a run with optional parameters""" mock_access.return_value = (True, None) mock_response = MagicMock() mock_response.json.return_value = {"run_id": 789} mock_post.return_value = mock_response client = SeerExplorerClient(self.organization, self.user) run_id = client.start_run("Query", on_page_context="some context") assert run_id == 789 call_args = mock_post.call_args assert call_args is not None @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") @patch("sentry.seer.explorer.client.requests.post") def test_start_run_http_error(self, mock_post, mock_access): """Test that HTTP errors are propagated""" mock_access.return_value = (True, None) mock_post.return_value.raise_for_status.side_effect = requests.HTTPError("API Error") client = SeerExplorerClient(self.organization, self.user) with pytest.raises(requests.HTTPError): client.start_run("Test query") @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") @patch("sentry.seer.explorer.client.requests.post") @patch("sentry.seer.explorer.client.collect_user_org_context") def test_start_run_with_categories(self, mock_collect_context, mock_post, mock_access): """Test starting a run with category fields""" mock_access.return_value = (True, None) mock_collect_context.return_value = {"user_id": self.user.id} mock_response = MagicMock() mock_response.json.return_value = {"run_id": 999} mock_post.return_value = mock_response client = SeerExplorerClient( self.organization, self.user, category_key="bug-fixer", category_value="issue-123" ) run_id = client.start_run("Fix bug") assert run_id == 999 body = orjson.loads(mock_post.call_args[1]["data"]) assert body["category_key"] == "bug-fixer" assert body["category_value"] == "issue-123" @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") def test_init_category_key_only_raises_error(self, mock_access): """Test that ValueError is raised when only category_key is provided""" mock_access.return_value = (True, None) with pytest.raises( ValueError, match="category_key and category_value must be provided together" ): SeerExplorerClient(self.organization, self.user, category_key="bug-fixer") @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") def test_init_category_value_only_raises_error(self, mock_access): """Test that ValueError is raised when only category_value is provided""" mock_access.return_value = (True, None) with pytest.raises( ValueError, match="category_key and category_value must be provided together" ): SeerExplorerClient(self.organization, self.user, category_value="issue-123") @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") def test_client_init_with_intelligence_level(self, mock_access): """Test that intelligence_level is stored""" mock_access.return_value = (True, None) client = SeerExplorerClient(self.organization, self.user, intelligence_level="high") assert client.intelligence_level == "high" @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") def test_client_init_default_intelligence_level(self, mock_access): """Test that intelligence_level defaults to 'medium'""" mock_access.return_value = (True, None) client = SeerExplorerClient(self.organization, self.user) assert client.intelligence_level == "medium" @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") @patch("sentry.seer.explorer.client.requests.post") @patch("sentry.seer.explorer.client.collect_user_org_context") def test_start_run_includes_intelligence_level( self, mock_collect_context, mock_post, mock_access ): """Test that intelligence_level is included in the payload""" mock_access.return_value = (True, None) mock_collect_context.return_value = {"user_id": self.user.id} mock_response = MagicMock() mock_response.json.return_value = {"run_id": 555} mock_post.return_value = mock_response client = SeerExplorerClient(self.organization, self.user, intelligence_level="low") run_id = client.start_run("Test query") assert run_id == 555 body = orjson.loads(mock_post.call_args[1]["data"]) assert body["intelligence_level"] == "low" @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") @patch("sentry.seer.explorer.client.requests.post") def test_continue_run_basic(self, mock_post, mock_access): """Test continuing an existing run""" mock_access.return_value = (True, None) mock_response = MagicMock() mock_response.json.return_value = {"run_id": 456} mock_post.return_value = mock_response client = SeerExplorerClient(self.organization, self.user) run_id = client.continue_run(456, "Follow up query") assert run_id == 456 assert mock_post.called @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") @patch("sentry.seer.explorer.client.requests.post") def test_continue_run_with_all_params(self, mock_post, mock_access): """Test continuing a run with all optional parameters""" mock_access.return_value = (True, None) mock_response = MagicMock() mock_response.json.return_value = {"run_id": 789} mock_post.return_value = mock_response client = SeerExplorerClient(self.organization, self.user) run_id = client.continue_run(789, "Follow up", insert_index=2, on_page_context="context") assert run_id == 789 call_args = mock_post.call_args assert call_args is not None @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") @patch("sentry.seer.explorer.client.requests.post") def test_continue_run_http_error(self, mock_post, mock_access): """Test that HTTP errors are propagated""" mock_access.return_value = (True, None) mock_post.return_value.raise_for_status.side_effect = requests.HTTPError("API Error") client = SeerExplorerClient(self.organization, self.user) with pytest.raises(requests.HTTPError): client.continue_run(123, "Test query") @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") @patch("sentry.seer.explorer.client.fetch_run_status") def test_get_run_immediate(self, mock_fetch, mock_access): """Test getting run status without waiting""" mock_access.return_value = (True, None) mock_state = SeerRunState( run_id=123, blocks=[], status="processing", updated_at="2024-01-01T00:00:00Z", ) mock_fetch.return_value = mock_state client = SeerExplorerClient(self.organization, self.user) result = client.get_run(123) assert result.run_id == 123 assert result.status == "processing" mock_fetch.assert_called_once_with(123, self.organization) @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") @patch("sentry.seer.explorer.client.poll_until_done") def test_get_run_with_blocking(self, mock_poll, mock_access): """Test getting run status with polling""" mock_access.return_value = (True, None) mock_state = SeerRunState( run_id=123, blocks=[], status="completed", updated_at="2024-01-01T00:00:00Z", ) mock_poll.return_value = mock_state client = SeerExplorerClient(self.organization, self.user) result = client.get_run(123, blocking=True, poll_interval=1.0, poll_timeout=30.0) assert result.run_id == 123 assert result.status == "completed" mock_poll.assert_called_once_with(123, self.organization, 1.0, 30.0) @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") @patch("sentry.seer.explorer.client.fetch_run_status") def test_get_run_http_error(self, mock_fetch, mock_access): """Test that HTTP errors are propagated""" mock_access.return_value = (True, None) mock_fetch.side_effect = requests.HTTPError("API Error") client = SeerExplorerClient(self.organization, self.user) with pytest.raises(requests.HTTPError): client.get_run(123) @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") @patch("sentry.seer.explorer.client.requests.post") def test_get_runs_basic(self, mock_post, mock_access): """Test getting runs with filters""" mock_access.return_value = (True, None) mock_response = MagicMock() mock_response.json.return_value = { "data": [ { "run_id": 1, "title": "Test", "last_triggered_at": "2024-01-01T00:00:00", "created_at": "2024-01-01T00:00:00", "category_key": "bug-fixer", "category_value": "issue-123", } ] } mock_post.return_value = mock_response client = SeerExplorerClient(self.organization, self.user) runs = client.get_runs(category_key="bug-fixer", category_value="issue-123") assert len(runs) == 1 assert runs[0].category_key == "bug-fixer" body = orjson.loads(mock_post.call_args[1]["data"]) assert body["category_key"] == "bug-fixer" assert body["category_value"] == "issue-123"
TestSeerExplorerClient
python
pytorch__pytorch
test/test_dataloader.py
{ "start": 37018, "end": 41817 }
class ____(TestCase): def setUp(self): super().setUp() self.data = torch.randn(100, 2, 3, 5) self.labels = torch.randperm(50).repeat(2) self.dataset = TensorDataset(self.data, self.labels) self.persistent_workers = False def _get_data_loader(self, dataset, **kwargs): persistent_workers = kwargs.get("persistent_workers", self.persistent_workers) if persistent_workers and kwargs.get("num_workers", 0) == 0: persistent_workers = False kwargs["persistent_workers"] = persistent_workers return DataLoader(dataset, **kwargs) def _test_sequential(self, loader): batch_size = loader.batch_size if batch_size is None: for idx, (sample, target) in enumerate(loader): self.assertEqual(sample, self.data[idx]) self.assertEqual(target, self.labels[idx]) self.assertEqual(idx, len(self.dataset) - 1) else: for i, (sample, target) in enumerate(loader): idx = i * batch_size self.assertEqual(sample, self.data[idx : idx + batch_size]) self.assertEqual(target, self.labels[idx : idx + batch_size]) self.assertEqual(i, math.floor((len(self.dataset) - 1) / batch_size)) def _test_shuffle(self, loader): found_data = dict.fromkeys(range(self.data.size(0)), 0) found_labels = dict.fromkeys(range(self.labels.size(0)), 0) batch_size = loader.batch_size if batch_size is None: for i, (batch_samples, batch_targets) in enumerate(loader): sample, target = (batch_samples, batch_targets) for data_point_idx, data_point in enumerate(self.data): if data_point.eq(sample).all(): self.assertFalse(found_data[data_point_idx]) found_data[data_point_idx] += 1 break self.assertEqual(target, self.labels[data_point_idx]) found_labels[data_point_idx] += 1 self.assertEqual(sum(found_data.values()), (i + 1)) self.assertEqual(sum(found_labels.values()), (i + 1)) self.assertEqual(i, (len(self.dataset) - 1)) else: for i, (batch_samples, batch_targets) in enumerate(loader): for sample, target in zip(batch_samples, batch_targets): for data_point_idx, data_point in enumerate(self.data): if data_point.eq(sample).all(): self.assertFalse(found_data[data_point_idx]) found_data[data_point_idx] += 1 break self.assertEqual(target, self.labels[data_point_idx]) found_labels[data_point_idx] += 1 self.assertEqual(sum(found_data.values()), (i + 1) * batch_size) self.assertEqual(sum(found_labels.values()), (i + 1) * batch_size) self.assertEqual(i, math.floor((len(self.dataset) - 1) / batch_size)) def _test_error(self, loader): it = iter(loader) errors = 0 while True: try: next(it) except NotImplementedError: errors += 1 except StopIteration: self.assertEqual( errors, math.ceil(float(len(loader.dataset)) / loader.batch_size) ) return def test_error_in_init(self): for num_workers in [0, 2]: loader = self._get_data_loader( ErrorIterableDataset(), num_workers=num_workers ) with self.assertRaisesRegex(RuntimeError, "Error in __iter__"): list(iter(loader)) loader = self._get_data_loader( self.dataset, num_workers=2, worker_init_fn=error_worker_init_fn ) with self.assertRaisesRegex(RuntimeError, "Error in worker_init_fn"): list(iter(loader)) def test_typing(self): # Make sure there is no TypeError class SomeDatasetClass(Dataset[list[torch.Tensor]]): pass def _create_dataloader(is_train: bool) -> DataLoader[list[torch.Tensor]]: pass @unittest.skipIf(IS_SANDCASTLE, "subprocess doesn't work in FB internal CI") @unittest.skipIf(IS_WINDOWS, "No 'resource' module on Windows") def test_fd_limit_exceeded(self): # See NOTE [ DataLoader on Linux and open files limit ] import subprocess subprocess.check_output( [ sys.executable, "-c", """\ import torch import resource from torch.utils.data import DataLoader, IterableDataset
TestDataLoader
python
kamyu104__LeetCode-Solutions
Python/number-of-good-binary-strings.py
{ "start": 81, "end": 883 }
class ____(object): def goodBinaryStrings(self, minLength, maxLength, oneGroup, zeroGroup): """ :type minLength: int :type maxLength: int :type oneGroup: int :type zeroGroup: int :rtype: int """ MOD = 10**9+7 result = 0 w = max(oneGroup, zeroGroup)+1 dp = [0]*w for i in xrange(maxLength+1): dp[i%w] = 1 if i == 0 else 0 if i-oneGroup >= 0: dp[i%w] = (dp[i%w]+dp[(i-oneGroup)%w])%MOD if i-zeroGroup >= 0: dp[i%w] = (dp[i%w]+dp[(i-zeroGroup)%w])%MOD if i >= minLength: result = (result+dp[i%w])%MOD return result # Time: O(n), n = maxLength # Space: O(w), w = max(oneGroup, zeroGroup)+1 # dp
Solution
python
fastai__fastai
fastai/layers.py
{ "start": 18689, "end": 19326 }
class ____(Module): "Merge a shortcut with the result of the module by multiplying them." def forward(self, x): return x * x.orig # %% ../nbs/01_layers.ipynb 129 inplace_relu = partial(nn.ReLU, inplace=True) # %% ../nbs/01_layers.ipynb 130 def SEModule(ch, reduction, act_cls=defaults.activation): nf = math.ceil(ch//reduction/8)*8 return SequentialEx(nn.AdaptiveAvgPool2d(1), ConvLayer(ch, nf, ks=1, norm_type=None, act_cls=act_cls), ConvLayer(nf, ch, ks=1, norm_type=None, act_cls=nn.Sigmoid), ProdLayer()) # %% ../nbs/01_layers.ipynb 131
ProdLayer
python
scipy__scipy
scipy/stats/tests/test_resampling.py
{ "start": 34262, "end": 50723 }
class ____: atol = 2.5e-2 # for comparing p-value def get_rvs(self, rvs_in, rs, dtype=None, xp=np): return lambda *args, **kwds: xp.asarray(rvs_in(*args, random_state=rs, **kwds), dtype=dtype) def get_statistic(self, xp): def statistic(x, axis): m = xp.mean(x, axis=axis) v = xp.var(x, axis=axis, correction=1) n = x.shape[axis] return m / (v/n)**0.5 # return stats.ttest_1samp(x, popmean=0., axis=axis).statistic) return statistic def test_input_validation(self, xp): # test that the appropriate error messages are raised for invalid input data = xp.asarray([1., 2., 3.]) def stat(x, axis=None): return xp.mean(x, axis=axis) message = "Array shapes are incompatible for broadcasting." temp = (xp.zeros((2, 5)), xp.zeros((3, 5))) rvs = (stats.norm.rvs, stats.norm.rvs) with pytest.raises(ValueError, match=message): monte_carlo_test(temp, rvs, lambda x, y, axis: 1, axis=-1) message = "`axis` must be an integer." with pytest.raises(ValueError, match=message): monte_carlo_test(data, stats.norm.rvs, stat, axis=1.5) message = "`vectorized` must be `True`, `False`, or `None`." with pytest.raises(ValueError, match=message): monte_carlo_test(data, stats.norm.rvs, stat, vectorized=1.5) message = "`rvs` must be callable or sequence of callables." with pytest.raises(TypeError, match=message): monte_carlo_test(data, None, stat) with pytest.raises(TypeError, match=message): temp = xp.asarray([[1., 2.], [3., 4.]]) monte_carlo_test(temp, [lambda x: x, None], stat) message = "If `rvs` is a sequence..." with pytest.raises(ValueError, match=message): temp = xp.asarray([[1., 2., 3.]]) monte_carlo_test(temp, [lambda x: x, lambda x: x], stat) message = "`statistic` must be callable." with pytest.raises(TypeError, match=message): monte_carlo_test(data, stats.norm.rvs, None) message = "`n_resamples` must be a positive integer." with pytest.raises(ValueError, match=message): monte_carlo_test(data, stats.norm.rvs, stat, n_resamples=-1000) message = "`n_resamples` must be a positive integer." with pytest.raises(ValueError, match=message): monte_carlo_test(data, stats.norm.rvs, stat, n_resamples=1000.5) message = "`batch` must be a positive integer or None." with pytest.raises(ValueError, match=message): monte_carlo_test(data, stats.norm.rvs, stat, batch=-1000) message = "`batch` must be a positive integer or None." with pytest.raises(ValueError, match=message): monte_carlo_test(data, stats.norm.rvs, stat, batch=1000.5) message = "`alternative` must be in..." with pytest.raises(ValueError, match=message): monte_carlo_test(data, stats.norm.rvs, stat, alternative='ekki') # *If* this raises a value error, make sure it has the intended message message = "Signature inspection of statistic" def rvs(size): return xp.asarray(stats.norm.rvs(size=size)) try: monte_carlo_test(data, rvs, xp.mean) except ValueError as e: assert str(e).startswith(message) def test_input_validation_xp(self, xp): def non_vectorized_statistic(x): return xp.mean(x) message = "`statistic` must be vectorized..." sample = xp.asarray([1., 2., 3.]) if is_numpy(xp): monte_carlo_test(sample, stats.norm.rvs, non_vectorized_statistic) return with pytest.raises(ValueError, match=message): monte_carlo_test(sample, stats.norm.rvs, non_vectorized_statistic) with pytest.raises(ValueError, match=message): monte_carlo_test(sample, stats.norm.rvs, xp.mean, vectorized=False) @pytest.mark.xslow def test_batch(self, xp): # make sure that the `batch` parameter is respected by checking the # maximum batch size provided in calls to `statistic` rng = np.random.default_rng(23492340193) x = xp.asarray(rng.standard_normal(size=10)) def statistic(x, axis): batch_size = 1 if x.ndim == 1 else x.shape[0] statistic.batch_size = max(batch_size, statistic.batch_size) statistic.counter += 1 return self.get_statistic(xp)(x, axis=axis) statistic.counter = 0 statistic.batch_size = 0 kwds = {'sample': x, 'statistic': statistic, 'n_resamples': 1000, 'vectorized': True} kwds['rvs'] = self.get_rvs(stats.norm.rvs, np.random.default_rng(328423), xp=xp) res1 = monte_carlo_test(batch=1, **kwds) assert_equal(statistic.counter, 1001) assert_equal(statistic.batch_size, 1) kwds['rvs'] = self.get_rvs(stats.norm.rvs, np.random.default_rng(328423), xp=xp) statistic.counter = 0 res2 = monte_carlo_test(batch=50, **kwds) assert_equal(statistic.counter, 21) assert_equal(statistic.batch_size, 50) kwds['rvs'] = self.get_rvs(stats.norm.rvs, np.random.default_rng(328423), xp=xp) statistic.counter = 0 res3 = monte_carlo_test(**kwds) assert_equal(statistic.counter, 2) assert_equal(statistic.batch_size, 1000) xp_assert_equal(res1.pvalue, res3.pvalue) xp_assert_equal(res2.pvalue, res3.pvalue) @pytest.mark.parametrize('axis', range(-3, 3)) def test_axis_dtype(self, axis, xp): # test that Nd-array samples are handled correctly for valid values # of the `axis` parameter; also make sure non-default dtype is maintained rng = np.random.default_rng(2389234) size = [2, 3, 4] size[axis] = 100 # Determine non-default dtype dtype_default = xp.asarray(1.).dtype dtype_str = 'float32'if ("64" in str(dtype_default)) else 'float64' dtype_np = getattr(np, dtype_str) dtype = getattr(xp, dtype_str) # ttest_1samp is CPU array-API compatible, but it would be good to # include CuPy in this test. We'll perform ttest_1samp with a # NumPy array, but all the rest with be done with fully array-API # compatible code. x = rng.standard_normal(size=size, dtype=dtype_np) expected = stats.ttest_1samp(x, popmean=0., axis=axis) x = xp.asarray(x, dtype=dtype) statistic = self.get_statistic(xp) rvs = self.get_rvs(stats.norm.rvs, rng, dtype=dtype, xp=xp) res = monte_carlo_test(x, rvs, statistic, vectorized=True, n_resamples=20000, axis=axis) ref_statistic = xp.asarray(expected.statistic, dtype=dtype) ref_pvalue = xp.asarray(expected.pvalue, dtype=dtype) xp_assert_close(res.statistic, ref_statistic) xp_assert_close(res.pvalue, ref_pvalue, atol=self.atol) @pytest.mark.parametrize('alternative', ("two-sided", "less", "greater")) def test_alternative(self, alternative, xp): # test that `alternative` is working as expected rng = np.random.default_rng(65723433) x = rng.standard_normal(size=30) ref = stats.ttest_1samp(x, 0., alternative=alternative) x = xp.asarray(x) statistic = self.get_statistic(xp) rvs = self.get_rvs(stats.norm.rvs, rng, xp=xp) res = monte_carlo_test(x, rvs, statistic, alternative=alternative) xp_assert_close(res.statistic, xp.asarray(ref.statistic)) xp_assert_close(res.pvalue, xp.asarray(ref.pvalue), atol=self.atol) # Tests below involve statistics that are not yet array-API compatible. # They can be converted when the statistics are converted. @pytest.mark.slow @pytest.mark.parametrize('alternative', ("less", "greater")) @pytest.mark.parametrize('a', np.linspace(-0.5, 0.5, 5)) # skewness def test_against_ks_1samp(self, alternative, a): # test that monte_carlo_test can reproduce pvalue of ks_1samp rng = np.random.default_rng(65723433) x = stats.skewnorm.rvs(a=a, size=30, random_state=rng) expected = stats.ks_1samp(x, stats.norm.cdf, alternative=alternative) def statistic1d(x): return stats.ks_1samp(x, stats.norm.cdf, mode='asymp', alternative=alternative).statistic norm_rvs = self.get_rvs(stats.norm.rvs, rng) res = monte_carlo_test(x, norm_rvs, statistic1d, n_resamples=1000, vectorized=False, alternative=alternative) assert_allclose(res.statistic, expected.statistic) if alternative == 'greater': assert_allclose(res.pvalue, expected.pvalue, atol=self.atol) elif alternative == 'less': assert_allclose(1-res.pvalue, expected.pvalue, atol=self.atol) @pytest.mark.parametrize('hypotest', (stats.skewtest, stats.kurtosistest)) @pytest.mark.parametrize('alternative', ("less", "greater", "two-sided")) @pytest.mark.parametrize('a', np.linspace(-2, 2, 5)) # skewness def test_against_normality_tests(self, hypotest, alternative, a): # test that monte_carlo_test can reproduce pvalue of normality tests rng = np.random.default_rng(85723405) x = stats.skewnorm.rvs(a=a, size=150, random_state=rng) expected = hypotest(x, alternative=alternative) def statistic(x, axis): return hypotest(x, axis=axis).statistic norm_rvs = self.get_rvs(stats.norm.rvs, rng) res = monte_carlo_test(x, norm_rvs, statistic, vectorized=True, alternative=alternative) assert_allclose(res.statistic, expected.statistic) assert_allclose(res.pvalue, expected.pvalue, atol=self.atol) @pytest.mark.parametrize('a', np.arange(-2, 3)) # skewness parameter def test_against_normaltest(self, a): # test that monte_carlo_test can reproduce pvalue of normaltest rng = np.random.default_rng(12340513) x = stats.skewnorm.rvs(a=a, size=150, random_state=rng) expected = stats.normaltest(x) def statistic(x, axis): return stats.normaltest(x, axis=axis).statistic norm_rvs = self.get_rvs(stats.norm.rvs, rng) res = monte_carlo_test(x, norm_rvs, statistic, vectorized=True, alternative='greater') assert_allclose(res.statistic, expected.statistic) assert_allclose(res.pvalue, expected.pvalue, atol=self.atol) @pytest.mark.xslow @pytest.mark.parametrize('a', np.linspace(-0.5, 0.5, 5)) # skewness def test_against_cramervonmises(self, a): # test that monte_carlo_test can reproduce pvalue of cramervonmises rng = np.random.default_rng(234874135) x = stats.skewnorm.rvs(a=a, size=30, random_state=rng) expected = stats.cramervonmises(x, stats.norm.cdf) def statistic1d(x): return stats.cramervonmises(x, stats.norm.cdf).statistic norm_rvs = self.get_rvs(stats.norm.rvs, rng) res = monte_carlo_test(x, norm_rvs, statistic1d, n_resamples=1000, vectorized=False, alternative='greater') assert_allclose(res.statistic, expected.statistic) assert_allclose(res.pvalue, expected.pvalue, atol=self.atol) @pytest.mark.slow @pytest.mark.parametrize('dist_name', ('norm', 'logistic')) @pytest.mark.parametrize('i', range(5)) def test_against_anderson(self, dist_name, i): # test that monte_carlo_test can reproduce results of `anderson`. Note: # `anderson` does not provide a p-value; it provides a list of # significance levels and the associated critical value of the test # statistic. `i` used to index this list. # find the skewness for which the sample statistic matches one of the # critical values provided by `stats.anderson` def fun(a): rng = np.random.default_rng(394295467) x = stats.tukeylambda.rvs(a, size=100, random_state=rng) expected = stats.anderson(x, dist_name) return expected.statistic - expected.critical_values[i] with warnings.catch_warnings(): warnings.simplefilter("ignore", RuntimeWarning) sol = root(fun, x0=0) assert sol.success # get the significance level (p-value) associated with that critical # value a = sol.x[0] rng = np.random.default_rng(394295467) x = stats.tukeylambda.rvs(a, size=100, random_state=rng) expected = stats.anderson(x, dist_name) expected_stat = expected.statistic expected_p = expected.significance_level[i]/100 # perform equivalent Monte Carlo test and compare results def statistic1d(x): return stats.anderson(x, dist_name).statistic dist_rvs = self.get_rvs(getattr(stats, dist_name).rvs, rng) with warnings.catch_warnings(): warnings.simplefilter("ignore", RuntimeWarning) res = monte_carlo_test(x, dist_rvs, statistic1d, n_resamples=1000, vectorized=False, alternative='greater') assert_allclose(res.statistic, expected_stat) assert_allclose(res.pvalue, expected_p, atol=2*self.atol) def test_p_never_zero(self): # Use biased estimate of p-value to ensure that p-value is never zero # per monte_carlo_test reference [1] rng = np.random.default_rng(2190176673029737545) x = np.zeros(100) res = monte_carlo_test(x, rng.random, np.mean, vectorized=True, alternative='less') assert res.pvalue == 0.0001 def test_against_ttest_ind(self): # test that `monte_carlo_test` can reproduce results of `ttest_ind`. rng = np.random.default_rng(219017667302737545) data = rng.random(size=(2, 5)), rng.random(size=7) # broadcastable rvs = rng.normal, rng.normal def statistic(x, y, axis): return stats.ttest_ind(x, y, axis=axis).statistic res = stats.monte_carlo_test(data, rvs, statistic, axis=-1) ref = stats.ttest_ind(data[0], [data[1]], axis=-1) assert_allclose(res.statistic, ref.statistic) assert_allclose(res.pvalue, ref.pvalue, rtol=2e-2) def test_against_f_oneway(self): # test that `monte_carlo_test` can reproduce results of `f_oneway`. rng = np.random.default_rng(219017667302737545) data = (rng.random(size=(2, 100)), rng.random(size=(2, 101)), rng.random(size=(2, 102)), rng.random(size=(2, 103))) rvs = rng.normal, rng.normal, rng.normal, rng.normal def statistic(*args, axis): return stats.f_oneway(*args, axis=axis).statistic res = stats.monte_carlo_test(data, rvs, statistic, axis=-1, alternative='greater') ref = stats.f_oneway(*data, axis=-1) assert_allclose(res.statistic, ref.statistic) assert_allclose(res.pvalue, ref.pvalue, atol=1e-2) @pytest.mark.fail_slow(2) @pytest.mark.xfail_on_32bit("Statistic may not depend on sample order on 32-bit") def test_finite_precision_statistic(self): # Some statistics return numerically distinct values when the values # should be equal in theory. Test that `monte_carlo_test` accounts # for this in some way. rng = np.random.default_rng(2549824598234528) n_resamples = 9999 def rvs(size): return 1. * stats.bernoulli(p=0.333).rvs(size=size, random_state=rng) x = rvs(100) res = stats.monte_carlo_test(x, rvs, np.var, alternative='less', n_resamples=n_resamples) # show that having a tolerance matters c0 = np.sum(res.null_distribution <= res.statistic) c1 = np.sum(res.null_distribution <= res.statistic*(1+1e-15)) assert c0 != c1 assert res.pvalue == (c1 + 1)/(n_resamples + 1) @make_xp_test_case(power)
TestMonteCarloHypothesisTest
python
apache__airflow
airflow-core/tests/unit/timetables/test_assets_timetable.py
{ "start": 1504, "end": 8950 }
class ____(Timetable): """ A mock Timetable class for testing purposes in Apache Airflow. """ __test__ = False def __init__(self) -> None: """ Initializes the MockTimetable with the current DateTime. """ self._now = DateTime.now() def next_dagrun_info( self, last_automated_data_interval: DataInterval | None, restriction: TimeRestriction ) -> DagRunInfo | None: """ Calculates the next DagRun information based on the provided interval and restrictions. :param last_automated_data_interval: The last automated data interval. :param restriction: The time restriction to apply. """ if last_automated_data_interval is None: next_run_date = self._now else: next_run_date = last_automated_data_interval.end.add(days=1) if restriction.earliest and next_run_date < restriction.earliest: next_run_date = restriction.earliest if restriction.latest and next_run_date > restriction.latest: return None return DagRunInfo.interval(start=next_run_date, end=next_run_date.add(days=1)) def infer_manual_data_interval(self, run_after: DateTime) -> DataInterval: """ Infers the data interval for manual triggers. :param run_after: The datetime after which the run is triggered. """ return DataInterval.exact(run_after) def serialize_timetable(timetable: Timetable) -> str: """ Mock serialization function for Timetable objects. :param timetable: The Timetable object to serialize. """ return "serialized_timetable" def deserialize_timetable(serialized: str) -> MockTimetable: """ Mock deserialization function for Timetable objects. :param serialized: The serialized data of the timetable. """ return MockTimetable() @pytest.fixture def test_timetable() -> MockTimetable: """Pytest fixture for creating a MockTimetable object.""" return MockTimetable() @pytest.fixture def test_assets() -> list[Asset]: """Pytest fixture for creating a list of Asset objects.""" return [Asset(name="test_asset", uri="test://asset")] @pytest.fixture def asset_timetable(test_timetable: MockTimetable, test_assets: list[Asset]) -> AssetOrTimeSchedule: """ Pytest fixture for creating an AssetOrTimeSchedule object. :param test_timetable: The test timetable instance. :param test_assets: A list of Asset instances. """ return AssetOrTimeSchedule(timetable=test_timetable, assets=test_assets) def test_serialization(asset_timetable: AssetOrTimeSchedule, monkeypatch: Any) -> None: """ Tests the serialization method of AssetOrTimeSchedule. :param asset_timetable: The AssetOrTimeSchedule instance to test. :param monkeypatch: The monkeypatch fixture from pytest. """ monkeypatch.setattr( "airflow.serialization.serialized_objects.encode_timetable", lambda x: "mock_serialized_timetable" ) serialized = asset_timetable.serialize() assert serialized == { "timetable": "mock_serialized_timetable", "asset_condition": { "__type": "asset_all", "objects": [ { "__type": "asset", "name": "test_asset", "uri": "test://asset/", "group": "asset", "extra": {}, } ], }, } def test_deserialization(monkeypatch: Any) -> None: """ Tests the deserialization method of AssetOrTimeSchedule. :param monkeypatch: The monkeypatch fixture from pytest. """ monkeypatch.setattr( "airflow.serialization.serialized_objects.decode_timetable", lambda x: MockTimetable() ) mock_serialized_data = { "timetable": "mock_serialized_timetable", "asset_condition": { "__type": "asset_all", "objects": [ { "__type": "asset", "name": "test_asset", "uri": "test://asset/", "group": "asset", "extra": None, } ], }, } deserialized = AssetOrTimeSchedule.deserialize(mock_serialized_data) assert isinstance(deserialized, AssetOrTimeSchedule) def test_infer_manual_data_interval(asset_timetable: AssetOrTimeSchedule) -> None: """ Tests the infer_manual_data_interval method of AssetOrTimeSchedule. :param asset_timetable: The AssetOrTimeSchedule instance to test. """ run_after = DateTime.now() result = asset_timetable.infer_manual_data_interval(run_after=run_after) assert isinstance(result, DataInterval) def test_next_dagrun_info(asset_timetable: AssetOrTimeSchedule) -> None: """ Tests the next_dagrun_info method of AssetOrTimeSchedule. :param asset_timetable: The AssetOrTimeSchedule instance to test. """ last_interval = DataInterval.exact(DateTime.now()) restriction = TimeRestriction(earliest=DateTime.now(), latest=None, catchup=True) result = asset_timetable.next_dagrun_info( last_automated_data_interval=last_interval, restriction=restriction ) assert result is None or isinstance(result, DagRunInfo) def test_generate_run_id(asset_timetable: AssetOrTimeSchedule) -> None: """ Tests the generate_run_id method of AssetOrTimeSchedule. :param asset_timetable: The AssetOrTimeSchedule instance to test. """ run_id = asset_timetable.generate_run_id( run_type=DagRunType.MANUAL, extra_args="test", logical_date=DateTime.now(), run_after=DateTime.now(), data_interval=None, ) assert isinstance(run_id, str) @pytest.fixture def asset_events(mocker) -> list[AssetEvent]: """Pytest fixture for creating mock AssetEvent objects.""" now = DateTime.now() earlier = now.subtract(days=1) later = now.add(days=1) # Create mock source_dag_run objects mock_dag_run_earlier = mocker.MagicMock() mock_dag_run_earlier.data_interval_start = earlier mock_dag_run_earlier.data_interval_end = now mock_dag_run_later = mocker.MagicMock() mock_dag_run_later.data_interval_start = now mock_dag_run_later.data_interval_end = later # Create AssetEvent objects with mock source_dag_run event_earlier = AssetEvent(timestamp=earlier, asset_id=1) event_later = AssetEvent(timestamp=later, asset_id=1) # Use mocker to set the source_dag_run attribute to avoid SQLAlchemy's instrumentation mocker.patch.object(event_earlier, "source_dag_run", new=mock_dag_run_earlier) mocker.patch.object(event_later, "source_dag_run", new=mock_dag_run_later) return [event_earlier, event_later] def test_run_ordering_inheritance(asset_timetable: AssetOrTimeSchedule) -> None: """ Tests that AssetOrTimeSchedule inherits run_ordering from its parent class correctly. :param asset_timetable: The AssetOrTimeSchedule instance to test. """ assert hasattr(asset_timetable, "run_ordering"), ( "AssetOrTimeSchedule should have 'run_ordering' attribute" ) parent_run_ordering = getattr(AssetTriggeredTimetable, "run_ordering", None) assert asset_timetable.run_ordering == parent_run_ordering, "run_ordering does not match the parent class" @pytest.mark.db_test
MockTimetable
python
sympy__sympy
sympy/stats/crv_types.py
{ "start": 43526, "end": 45680 }
class ____(SingleContinuousDistribution): _argnames = ('d1', 'd2') set = Interval(-oo, oo) @staticmethod def check(d1, d2): _value_check(d1 > 0, "Degree of freedom d1 must be positive.") _value_check(d2 > 0, "Degree of freedom d2 must be positive.") def pdf(self, x): d1, d2 = self.d1, self.d2 return (2*d1**(d1/2)*d2**(d2/2) / beta_fn(d1/2, d2/2) * exp(d1*x) / (d1*exp(2*x)+d2)**((d1+d2)/2)) def FisherZ(name, d1, d2): r""" Create a Continuous Random Variable with an Fisher's Z distribution. Explanation =========== The density of the Fisher's Z distribution is given by .. math:: f(x) := \frac{2d_1^{d_1/2} d_2^{d_2/2}} {\mathrm{B}(d_1/2, d_2/2)} \frac{e^{d_1z}}{\left(d_1e^{2z}+d_2\right)^{\left(d_1+d_2\right)/2}} .. TODO - What is the difference between these degrees of freedom? Parameters ========== d1 : `d_1 > 0` Degree of freedom. d2 : `d_2 > 0` Degree of freedom. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import FisherZ, density >>> from sympy import Symbol, pprint >>> d1 = Symbol("d1", positive=True) >>> d2 = Symbol("d2", positive=True) >>> z = Symbol("z") >>> X = FisherZ("x", d1, d2) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) d1 d2 d1 d2 - -- - -- -- -- 2 2 2 2 / 2*z \ d1*z 2*d1 *d2 *\d1*e + d2/ *e ----------------------------------------- /d1 d2\ B|--, --| \2 2 / References ========== .. [1] https://en.wikipedia.org/wiki/Fisher%27s_z-distribution .. [2] https://mathworld.wolfram.com/Fishersz-Distribution.html """ return rv(name, FisherZDistribution, (d1, d2)) #------------------------------------------------------------------------------- # Frechet distribution ---------------------------------------------------------
FisherZDistribution
python
doocs__leetcode
solution/3300-3399/3340.Check Balanced String/Solution.py
{ "start": 0, "end": 179 }
class ____: def isBalanced(self, num: str) -> bool: f = [0, 0] for i, x in enumerate(map(int, num)): f[i & 1] += x return f[0] == f[1]
Solution
python
Lightning-AI__lightning
examples/pytorch/domain_templates/computer_vision_fine_tuning.py
{ "start": 9565, "end": 10298 }
class ____(LightningCLI): def add_arguments_to_parser(self, parser): parser.add_lightning_class_args(MilestonesFinetuning, "finetuning") parser.link_arguments("data.batch_size", "model.batch_size") parser.link_arguments("finetuning.milestones", "model.milestones") parser.link_arguments("finetuning.train_bn", "model.train_bn") parser.set_defaults({ "trainer.max_epochs": 15, "trainer.enable_model_summary": False, "trainer.num_sanity_val_steps": 0, }) def cli_main(): MyLightningCLI(TransferLearningModel, CatDogImageDataModule, seed_everything_default=1234) if __name__ == "__main__": cli_lightning_logo() cli_main()
MyLightningCLI
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/base.py
{ "start": 18566, "end": 19265 }
class ____(SQLCoreOperations[_T_co], TypingOnly): __slots__ = () if typing.TYPE_CHECKING: def of_type( self, class_: _EntityType[Any] ) -> PropComparator[_T_co]: ... def and_( self, *criteria: _ColumnExpressionArgument[bool] ) -> PropComparator[bool]: ... def any( # noqa: A001 self, criterion: Optional[_ColumnExpressionArgument[bool]] = None, **kwargs: Any, ) -> ColumnElement[bool]: ... def has( self, criterion: Optional[_ColumnExpressionArgument[bool]] = None, **kwargs: Any, ) -> ColumnElement[bool]: ...
SQLORMOperations
python
ray-project__ray
python/ray/serve/tests/test_cli_3.py
{ "start": 3026, "end": 18023 }
class ____: @pytest.mark.skipif( sys.platform == "win32", reason="File path incorrect on Windows." ) @pytest.mark.parametrize( "proxy_location,expected", [ ( None, "EveryNode", ), # default ProxyLocation `EveryNode` is used as http_options.location is not specified ("EveryNode", "EveryNode"), ("HeadOnly", "HeadOnly"), ("Disabled", "Disabled"), ], ) def test_proxy_location(self, ray_start_stop, tmp_path, proxy_location, expected): # when the `serve run` cli command is executed # without serve already running (for the first time) # `proxy_location` should be set from the config file if specified def is_proxy_location_correct(expected_proxy_location: str) -> bool: try: response = httpx.get( "http://localhost:8265/api/serve/applications/" ).text response_json = json.loads(response) print("response_json") print(response_json) return response_json["proxy_location"] == expected_proxy_location except httpx.HTTPError: return False def arithmetic_config(with_proxy_location: Union[str, None]) -> str: config_file_name = os.path.join( os.path.dirname(__file__), "test_config_files", "arithmetic.yaml" ) with open(config_file_name, "r") as config_file: arithmetic_config_dict = yaml.safe_load(config_file) config_path = tmp_path / "config.yaml" if with_proxy_location: arithmetic_config_dict["proxy_location"] = with_proxy_location with open(config_path, "w") as f: yaml.dump(arithmetic_config_dict, f) return str(config_path) config_path = arithmetic_config(with_proxy_location=proxy_location) p = subprocess.Popen(["serve", "run", config_path]) wait_for_condition( lambda: is_proxy_location_correct(expected_proxy_location=expected), timeout=10, ) p.send_signal(signal.SIGINT) p.wait() @pytest.mark.parametrize("number_of_kill_signals", (1, 2)) @pytest.mark.skipif( sys.platform == "win32", reason="File path incorrect on Windows." ) def test_run_application(self, ray_start_stop, number_of_kill_signals): """Deploys valid config file and import path via `serve run`.""" # Deploy via config file config_file_name = os.path.join( os.path.dirname(__file__), "test_config_files", "arithmetic.yaml" ) print('Running config file "arithmetic.yaml".') p = subprocess.Popen(["serve", "run", "--address=auto", config_file_name]) wait_for_condition( lambda: httpx.post("http://localhost:8000/", json=["ADD", 0]).json() == 1, timeout=15, ) wait_for_condition( lambda: httpx.post("http://localhost:8000/", json=["SUB", 5]).json() == 3, timeout=15, ) print( "Run successful! Deployments are live and reachable over HTTP. Killing run." ) for _ in range(number_of_kill_signals): p.send_signal(signal.SIGINT) # Equivalent to ctrl-C p.wait() with pytest.raises(httpx.HTTPError): httpx.post("http://localhost:8000/", json=["ADD", 0]).json() print("Kill successful! Deployments are not reachable over HTTP.") print('Running node at import path "ray.serve.tests.test_cli_3.parrot_node".') # Deploy via import path p = subprocess.Popen( ["serve", "run", "--address=auto", "ray.serve.tests.test_cli_3.parrot_node"] ) wait_for_condition( lambda: ping_endpoint("/", params="?sound=squawk") == "squawk" ) print( "Run successful! Deployment is live and reachable over HTTP. Killing run." ) p.send_signal(signal.SIGINT) # Equivalent to ctrl-C p.wait() assert ping_endpoint("/", params="?sound=squawk") == CONNECTION_ERROR_MSG print("Kill successful! Deployment is not reachable over HTTP.") @pytest.mark.skipif( sys.platform == "win32", reason="File path incorrect on Windows." ) def test_run_multi_app(self, ray_start_stop): """Deploys valid multi-app config file via `serve run`.""" # Deploy via config file config_file_name = os.path.join( os.path.dirname(__file__), "test_config_files", "pizza_world.yaml" ) print('Running config file "pizza_world.yaml".') p = subprocess.Popen(["serve", "run", "--address=auto", config_file_name]) wait_for_condition( lambda: httpx.post("http://localhost:8000/app1").text == "wonderful world", timeout=15, ) print('Application "app1" is reachable over HTTP.') wait_for_condition( lambda: httpx.post("http://localhost:8000/app2", json=["ADD", 2]).text == "12 pizzas please!", timeout=15, ) wait_for_condition( lambda: httpx.post("http://localhost:8000/app2", json=["MUL", 2]).text == "20 pizzas please!", timeout=15, ) print( "Run successful! Deployments are live and reachable over HTTP. Killing run." ) p.send_signal(signal.SIGINT) # Equivalent to ctrl-C p.wait() with pytest.raises(httpx.HTTPError): _ = httpx.post("http://localhost:8000/app1").text with pytest.raises(httpx.HTTPError): _ = httpx.post("http://localhost:8000/app2", json=["ADD", 0]).text print("Kill successful! Deployments are not reachable over HTTP.") @pytest.mark.skipif( sys.platform == "win32", reason="File path incorrect on Windows." ) def test_run_deployment_node(self, ray_start_stop): """Test `serve run` with bound args and kwargs.""" # Deploy via import path p = subprocess.Popen( [ "serve", "run", "--address=auto", "ray.serve.tests.test_cli_3.molly_macaw", ] ) wait_for_condition(lambda: ping_endpoint("/") == "Molly is green!", timeout=10) p.send_signal(signal.SIGINT) p.wait() assert ping_endpoint("/") == CONNECTION_ERROR_MSG @pytest.mark.skipif( sys.platform == "win32", reason="File path incorrect on Windows." ) @pytest.mark.parametrize( "import_path", [ "ray.serve.tests.test_cli_3.build_echo_app", "ray.serve.tests.test_cli_3.build_echo_app_typed", ], ) def test_run_builder_with_args(self, ray_start_stop, import_path: str): """Test `serve run` with args passed into a builder function. Tests both the untyped and typed args cases. """ # First deploy without any arguments, should get default response. p = subprocess.Popen( [ "serve", "run", "--address=auto", import_path, ] ) wait_for_condition(lambda: ping_endpoint("") == "DEFAULT", timeout=10) p.send_signal(signal.SIGINT) p.wait() assert ping_endpoint("/") == CONNECTION_ERROR_MSG # Now deploy passing a message as an argument, should get passed message. p = subprocess.Popen( [ "serve", "run", "--address=auto", import_path, "message=hello world", ] ) wait_for_condition(lambda: ping_endpoint("") == "hello world", timeout=10) p.send_signal(signal.SIGINT) p.wait() assert ping_endpoint("/") == CONNECTION_ERROR_MSG @pytest.mark.skipif( sys.platform == "win32", reason="File path incorrect on Windows." ) def test_run_runtime_env(self, ray_start_stop): """Test `serve run` with runtime_env passed in.""" # With import path p = subprocess.Popen( [ "serve", "run", "--address=auto", "ray.serve.tests.test_cli_3.metal_detector_node", "--runtime-env-json", ('{"env_vars": {"buried_item": "lucky coin"} }'), ] ) wait_for_condition( lambda: ping_endpoint("MetalDetector") == "lucky coin", timeout=10 ) p.send_signal(signal.SIGINT) p.wait() # With config p = subprocess.Popen( [ "serve", "run", "--address=auto", os.path.join( os.path.dirname(__file__), "test_config_files", "missing_runtime_env.yaml", ), "--runtime-env-json", json.dumps( { "py_modules": [TEST_DEPLOY_GROUP_PINNED_URI], "working_dir": "http://nonexistentlink-q490123950ni34t", } ), "--working-dir", TEST_DAG_PINNED_URI, ] ) wait_for_condition(lambda: ping_endpoint("") == "wonderful world", timeout=15) p.send_signal(signal.SIGINT) p.wait() @pytest.mark.skipif( sys.platform == "win32", reason="File path incorrect on Windows." ) @pytest.mark.parametrize("config_file", ["basic_graph.yaml", "basic_multi.yaml"]) def test_run_config_port1(self, ray_start_stop, config_file): """Test that `serve run` defaults to port 8000.""" config_file_name = os.path.join( os.path.dirname(__file__), "test_config_files", config_file ) p = subprocess.Popen(["serve", "run", config_file_name]) wait_for_condition( lambda: httpx.post("http://localhost:8000/").text == "wonderful world", timeout=15, ) p.send_signal(signal.SIGINT) p.wait() @pytest.mark.skipif( sys.platform == "win32", reason="File path incorrect on Windows." ) @pytest.mark.parametrize( "config_file", ["basic_graph_http.yaml", "basic_multi_http.yaml"] ) def test_run_config_port2(self, ray_start_stop, config_file): """If config file specifies a port, the default port value should not be used.""" config_file_name = os.path.join( os.path.dirname(__file__), "test_config_files", config_file ) p = subprocess.Popen(["serve", "run", config_file_name]) wait_for_condition( lambda: httpx.post("http://localhost:8005/").text == "wonderful world", timeout=15, ) p.send_signal(signal.SIGINT) p.wait() @pytest.mark.skipif( sys.platform == "win32", reason="File path incorrect on Windows." ) def test_run_teardown(self, ray_start_stop): """Consecutive serve runs should tear down controller so logs can always be seen.""" logs = subprocess.check_output( ["serve", "run", "ray.serve.tests.test_cli_3.constructor_failure_node"], stderr=subprocess.STDOUT, timeout=30, ).decode() assert "Intentionally failing." in logs logs = subprocess.check_output( ["serve", "run", "ray.serve.tests.test_cli_3.constructor_failure_node"], stderr=subprocess.STDOUT, timeout=30, ).decode() assert "Intentionally failing." in logs @pytest.mark.skipif( sys.platform == "win32", reason="File path incorrect on Windows." ) def test_run_route_prefix_and_name_default(self, ray_start_stop): """Test `serve run` without route_prefix and name options.""" p = subprocess.Popen( [ "serve", "run", "--address=auto", "ray.serve.tests.test_cli_3.echo_app", ] ) wait_for_condition(check_app_running, app_name=SERVE_DEFAULT_APP_NAME) assert ping_endpoint("/") == "hello" p.send_signal(signal.SIGINT) p.wait() @pytest.mark.skipif( sys.platform == "win32", reason="File path incorrect on Windows." ) def test_run_route_prefix_and_name_override(self, ray_start_stop): """Test `serve run` with route prefix option.""" p = subprocess.Popen( [ "serve", "run", "--address=auto", "--route-prefix=/hello", "--name=hello_app", "ray.serve.tests.test_cli_3.echo_app", ], ) wait_for_condition(check_app_running, app_name="hello_app") assert "Path '/' not found" in ping_endpoint("/") assert ping_endpoint("/hello") == "hello" p.send_signal(signal.SIGINT) p.wait() @pytest.mark.skipif( sys.platform == "win32", reason="File path incorrect on Windows." ) def test_run_config_request_timeout(self, ray_start_stop): """Test running serve with request timeout in http_options. The config file has 0.1s as the `request_timeout_s` in the `http_options`. First case checks that when the query runs longer than the 0.1s, the deployment returns a task failed message. The second case checks that when the query takes less than 0.1s, the deployment returns a success message. """ config_file_name = os.path.join( os.path.dirname(__file__), "test_config_files", "http_option_request_timeout_s.yaml", ) p = subprocess.Popen(["serve", "run", config_file_name]) # Ensure the http request is killed and failed when the deployment runs longer than # the 0.1 request_timeout_s set in in the config yaml wait_for_condition( lambda: httpx.get("http://localhost:8000/app1?sleep_s=0.11").status_code == 408, ) # Ensure the http request returned the correct response when the deployment runs # shorter than the 0.1 request_timeout_s set up in the config yaml wait_for_condition( lambda: httpx.get("http://localhost:8000/app1?sleep_s=0.09").text == "Task Succeeded!", ) p.send_signal(signal.SIGINT) p.wait() @pytest.mark.skipif( sys.platform == "win32", reason="File path incorrect on Windows." ) def test_run_reload_basic(self, ray_start_stop, tmp_path): """Test `serve run` with reload.""" code_template = """ from ray import serve @serve.deployment
TestRun
python
numpy__numpy
numpy/lib/_index_tricks_impl.py
{ "start": 18871, "end": 19834 }
class ____(AxisConcatenator): """ Translates slice objects to concatenation along the second axis. This is short-hand for ``np.r_['-1,2,0', index expression]``, which is useful because of its common occurrence. In particular, arrays will be stacked along their last axis after being upgraded to at least 2-D with 1's post-pended to the shape (column vectors made out of 1-D arrays). See Also -------- column_stack : Stack 1-D arrays as columns into a 2-D array. r_ : For more detailed documentation. Examples -------- >>> import numpy as np >>> np.c_[np.array([1,2,3]), np.array([4,5,6])] array([[1, 4], [2, 5], [3, 6]]) >>> np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])] array([[1, 2, 3, ..., 4, 5, 6]]) """ __slots__ = () def __init__(self): AxisConcatenator.__init__(self, -1, ndmin=2, trans1d=0) c_ = CClass() @set_module('numpy')
CClass
python
numba__numba
numba/tests/test_caching.py
{ "start": 31448, "end": 32428 }
class ____(BaseCacheTest): # Nested multiprocessing.Pool raises AssertionError: # "daemonic processes are not allowed to have children" _numba_parallel_test_ = False here = os.path.dirname(__file__) usecases_file = os.path.join(here, "cache_usecases.py") modname = "dispatcher_caching_test_fodder" def test_multiprocessing(self): # Check caching works from multiple processes at once (#2028) mod = self.import_module() # Calling a pure Python caller of the JIT-compiled function is # necessary to reproduce the issue. f = mod.simple_usecase_caller n = 3 try: ctx = multiprocessing.get_context('spawn') except AttributeError: ctx = multiprocessing pool = ctx.Pool(n) try: res = sum(pool.imap(f, range(n))) finally: pool.close() self.assertEqual(res, n * (n - 1) // 2) @skip_if_typeguard
TestMultiprocessCache
python
huggingface__transformers
tests/quantization/quanto_integration/test_quanto.py
{ "start": 16770, "end": 17313 }
class ____(unittest.TestCase): def test_quantize_activation(self): quantization_config = QuantoConfig( weights="int8", activations="int8", ) with self.assertRaises(ValueError) as e: AutoModelForCausalLM.from_pretrained("bigscience/bloom-560m", quantization_config=quantization_config) self.assertIn("We don't support quantizing the activations with transformers library", str(e.exception)) @require_optimum_quanto @require_torch_accelerator
QuantoQuantizationActivationTest
python
pytorch__pytorch
test/test_reductions.py
{ "start": 3562, "end": 179273 }
class ____(TestCase): ########################################################################### # ReductionOpInfo unit tests ########################################################################### def _test_dim_keepdim(self, op: ReductionOpInfo, device, *, ndim, **dim_keepdim): """Tests output shape for input with ndim and dim and keepdim kwargs""" shape = torch.randint(2, 5, (ndim,)).tolist() t = make_tensor(shape, dtype=torch.float, device=device) args, kwargs = next(op.generate_args_kwargs(t, **dim_keepdim)) result = op(t, *args, **dim_keepdim, **kwargs) empty_dim_as_none = (op.name == "linalg.vector_norm" or op.name == "_refs.linalg.vector_norm") expected_shape = _reduced_shape(shape, empty_dim_as_none, **dim_keepdim) self.assertEqual(result.shape, expected_shape, f""" expected output shape to be {expected_shape} but got {list(result.shape)} for input shape {shape} and {dim_keepdim} """) # TODO(@heitorschueroff) combine cases with and without keepdim once # there's support for a @parametrize decorator. @ops(reduction_ops, dtypes=OpDTypes.none) def test_dim_default(self, device, op: ReductionOpInfo): """Tests that the default dim reduces all dimensions.""" for ndim in range(3): self._test_dim_keepdim(op, device, ndim=ndim) @ops(reduction_ops, dtypes=OpDTypes.none) def test_dim_default_keepdim(self, device, op: ReductionOpInfo): """Tests that the default dim, when keepdim=True, reduces all dimensions to size 1.""" for ndim in range(3): self._test_dim_keepdim(op, device, ndim=ndim, keepdim=True) @ops(reduction_ops, dtypes=OpDTypes.none) def test_dim_none(self, device, op: ReductionOpInfo): """Tests that dim=None reduces all dimensions.""" for ndim in range(3): self._test_dim_keepdim(op, device, ndim=ndim, dim=None) @ops(reduction_ops, dtypes=OpDTypes.none) def test_dim_none_keepdim(self, device, op: ReductionOpInfo): """Tests that dim=None, when keepdim=True, reduces all dimensions to size 1.""" for ndim in range(3): self._test_dim_keepdim(op, device, ndim=ndim, dim=None, keepdim=True) @ops(reduction_ops, dtypes=OpDTypes.none) def test_dim_single(self, device, op: ReductionOpInfo): """Tests that dim=i reduces dimension i.""" self._test_dim_keepdim(op, device, ndim=0, dim=0) self._test_dim_keepdim(op, device, ndim=1, dim=0) self._test_dim_keepdim(op, device, ndim=2, dim=-1) self._test_dim_keepdim(op, device, ndim=3, dim=1) @ops(reduction_ops, dtypes=OpDTypes.none) def test_dim_single_keepdim(self, device, op: ReductionOpInfo): """Tests that dim=i, when keepdim=True, reduces dimension i to size 1.""" self._test_dim_keepdim(op, device, ndim=0, dim=0, keepdim=True) self._test_dim_keepdim(op, device, ndim=1, dim=0, keepdim=True) self._test_dim_keepdim(op, device, ndim=2, dim=-1, keepdim=True) self._test_dim_keepdim(op, device, ndim=3, dim=1, keepdim=True) @ops(filter(lambda op: op.supports_multiple_dims, reduction_ops), dtypes=OpDTypes.none) def test_dim_empty(self, device, op: ReductionOpInfo): """Tests that dim=[] is a no-op""" self._test_dim_keepdim(op, device, ndim=0, dim=[]) self._test_dim_keepdim(op, device, ndim=2, dim=[]) @ops(filter(lambda op: op.supports_multiple_dims, reduction_ops), dtypes=OpDTypes.none) def test_dim_empty_keepdim(self, device, op: ReductionOpInfo): """Tests that dim=[], when keepdim=True, is a no-op""" self._test_dim_keepdim(op, device, ndim=0, dim=[], keepdim=True) self._test_dim_keepdim(op, device, ndim=2, dim=[], keepdim=True) @ops(filter(lambda op: op.supports_multiple_dims, reduction_ops), dtypes=OpDTypes.none) def test_dim_multi(self, device, op: ReductionOpInfo): """Tests that dim=[i, j, ...] reduces dimensions i, j, ....""" self._test_dim_keepdim(op, device, ndim=1, dim=[0]) self._test_dim_keepdim(op, device, ndim=3, dim=[0, 2]) @ops(filter(lambda op: op.supports_multiple_dims, reduction_ops), dtypes=OpDTypes.none) def test_dim_multi_keepdim(self, device, op: ReductionOpInfo): """Tests that dim=[i, j, ...], when keepdim=True, reduces dimensions i, j, .... to size 1.""" self._test_dim_keepdim(op, device, ndim=1, dim=[0], keepdim=True) self._test_dim_keepdim(op, device, ndim=3, dim=[0, 2], keepdim=True) @ops(filter(lambda op: op.supports_multiple_dims, reduction_ops), dtypes=OpDTypes.none) def test_dim_multi_unsorted(self, device, op: ReductionOpInfo): """Tests that operator correctly handles unsorted dim list.""" self._test_dim_keepdim(op, device, ndim=4, dim=[3, 0, 2]) @ops(filter(lambda op: op.supports_multiple_dims, reduction_ops), dtypes=OpDTypes.none) def test_dim_multi_unsorted_keepdim(self, device, op: ReductionOpInfo): """Tests that operator correctly handles unsorted dim list when keepdim=True.""" self._test_dim_keepdim(op, device, ndim=4, dim=[3, 0, 2], keepdim=True) @ops(filter(lambda op: op.supports_multiple_dims, reduction_ops), dtypes=OpDTypes.none) def test_dim_multi_duplicate(self, device, op: ReductionOpInfo): """Tests that an error is raised if dim has duplicate entries.""" with self.assertRaises(RuntimeError): self._test_dim_keepdim(op, device, ndim=3, dim=[0, 1, 1, 2]) @ops(filter(lambda op: not op.supports_multiple_dims, reduction_ops), dtypes=OpDTypes.none) def test_dim_multi_unsupported(self, device, op: ReductionOpInfo): """Tests that ops claiming to not support multi dim actually don't.""" with self.assertRaises(TypeError): self._test_dim_keepdim(op, device, ndim=3, dim=[0, 2]) @ops(reduction_ops, dtypes=OpDTypes.none) def test_dim_offbounds(self, device, op: ReductionOpInfo): """Tests that passing an off-bounds dim throws""" with self.assertRaises(IndexError): self._test_dim_keepdim(op, device, ndim=2, dim=2) @ops(reduction_ops, dtypes=OpDTypes.none) def test_dim_ndim_limit(self, device, op: ReductionOpInfo): """Tests that an exception is raised when reducing a tensor with more than 64 dims along some specific dimensions. dim=None is ok""" t = make_tensor([1] * 65, dtype=torch.float, device=device) with self.assertRaisesRegex(RuntimeError, "only tensors with up to 64 dims are supported"): op(t, dim=0) @ops(filter(lambda op: op.identity is not None, reduction_ops), dtypes=OpDTypes.supported) def test_identity(self, device, dtype, op: ReductionOpInfo): """Tests that the identity value is an identity for the operator""" t = make_tensor((10,), dtype=dtype, device=device) t[1::2] = op.identity args, kwargs = next(op.generate_args_kwargs(t)) result = op(t[::2], *args, **kwargs) result_with_identity = op(t, *args, **kwargs) self.assertEqual(result, result_with_identity, """ Adding identity value to the input tensor should not change the result. """) # TODO(@heitorschueroff) Update these to use the nan_policy kwarg once # it is added to reduction operators. @ops(filter(lambda op: op.nan_policy == 'propagate', reduction_ops), dtypes=OpDTypes.supported, allowed_dtypes=floating_and_complex_types_and(torch.bfloat16, torch.float16)) def test_nan_policy_propagate(self, device, dtype, op: ReductionOpInfo): """Tests that nan is propagated to the output by default""" t = make_tensor((5,), dtype=dtype, device=device) t[2] = torch.nan args, kwargs = next(op.generate_args_kwargs(t)) result = op(t, *args, **kwargs) self.assertTrue(result.isnan()) @ops(filter(lambda op: op.nan_policy == 'omit', reduction_ops), dtypes=OpDTypes.supported, allowed_dtypes=floating_and_complex_types_and(torch.bfloat16, torch.float16)) def test_nan_policy_omit(self, device, dtype, op: ReductionOpInfo): """Tests that NaN values do not affect the result.""" t = make_tensor((10,), dtype=dtype, device=device) t[1::2] = torch.nan args, kwargs = next(op.generate_args_kwargs(t)) result = op(t[::2], *args, **kwargs) result_with_nan = op(t, *args, **kwargs) self.assertEqual(result, result_with_nan) @ops(reduction_ops, dtypes=OpDTypes.supported) def test_result_dtype(self, device, dtype, op: ReductionOpInfo): """Tests that the result has the correct dtype""" t = make_tensor((5,), dtype=dtype, device=device) args, kwargs = next(op.generate_args_kwargs(t)) result: torch.Tensor = op(t, *args, **kwargs) is_integral = dtype in integral_types_and(torch.bool) if op.promotes_int_to_float and is_integral: self.assertTrue(torch.is_floating_point(result)) elif op.promotes_int_to_int64 and is_integral: self.assertEqual(result.dtype, torch.int64) elif op.result_dtype is not None: self.assertEqual(result.dtype, op.result_dtype) elif op.complex_to_real: _complex_to_real_dtype_map = { torch.complex128: torch.float64, torch.complex64: torch.float32, torch.complex32: torch.float16, } self.assertEqual(result.dtype, _complex_to_real_dtype_map.get(dtype, dtype)) else: self.assertEqual(result.dtype, dtype) @ops(reduction_ops, dtypes=OpDTypes.none) def test_empty_tensor_empty_slice(self, device, op: ReductionOpInfo): """Tests for consistent behavior when reducing over an empty slice. The rules for reducing over an empty slice are as follows: - Return the identity value if the operator has one - Otherwise, return NaN if the operator promotes integral dtype to floating point dtypes. - Otherwise, raise an error See discussion here https://github.com/pytorch/pytorch/issues/61901 """ t = make_tensor((0, 2, 3), dtype=torch.float, device=device) for dim in [0] + [[0, 2]] if op.supports_multiple_dims else []: args, kwargs = next(op.generate_args_kwargs(t, dim=dim)) if op.identity is not None: # Reducing along empty slice should return identity result = op(t, *args, dim=dim, **kwargs) self.assertEqual(result, torch.full_like(result, op.identity)) elif op.promotes_int_to_float: # Reducing along empty slice should return NaN result = op(t, *args, dim=dim, **kwargs) self.assertEqual(result, torch.full_like(result, torch.nan)) else: # Reducing along empty slice should raise an error if isinstance(op, ReductionPythonRefInfo): # ref reductions throw RuntimeError for this with self.assertRaises(RuntimeError): op(t, *args, dim=dim, **kwargs) else: with self.assertRaises(IndexError): op(t, *args, dim=dim, **kwargs) @ops(reduction_ops, dtypes=OpDTypes.none) def test_empty_tensor_nonempty_slice(self, device, op: ReductionOpInfo): """Tests that reducing a nonempty slice of an empty tensor returns an empty tensor with the dimensions reduced.""" t = make_tensor((0, 2, 3), dtype=torch.float, device=device) for dim in [1] + [[1, 2]] if op.supports_multiple_dims else []: args, kwargs = next(op.generate_args_kwargs(t, dim=dim)) result = op(t, *args, dim=dim, **kwargs) self.assertEqual(result.shape, _reduced_shape(t.shape, dim=dim)) def _test_noncontiguous(self, op: ReductionOpInfo, t: torch.Tensor, **reduction_kwargs): """Helper method to test noncontiguous input tensors.""" assert not t.is_contiguous() t_contig = t.contiguous() for args, kwargs in op.generate_args_kwargs(t_contig, **reduction_kwargs): kwargs.update(reduction_kwargs) result = op(t, *args, **kwargs) expected = op(t_contig, *args, **kwargs) self.assertEqual(result, expected) @ops(reduction_ops) def test_noncontiguous_innermost(self, device, dtype, op: ReductionOpInfo): """Tests reducing along noncontiguous innermost dimension.""" t = make_tensor((10, 10), dtype=dtype, device=device, low=-1, high=1) self._test_noncontiguous(op, t[:, ::2], dim=1) @ops(reduction_ops) def test_noncontiguous_outermost(self, device, dtype, op: ReductionOpInfo): """Tests reducing along noncontiguous outermost dimension.""" t = make_tensor((10, 10), dtype=dtype, device=device, low=-1, high=1) self._test_noncontiguous(op, t[::2, :], dim=0) @ops(reduction_ops) def test_noncontiguous_all(self, device, dtype, op: ReductionOpInfo): """Tests reducing all dimensions of a noncontiguous tensor.""" t = make_tensor((5, 5, 5), dtype=dtype, device=device, low=-1, high=1) self._test_noncontiguous(op, t[::2, ::3, 1:-1:2]) @ops(reduction_ops) def test_noncontiguous_transposed(self, device, dtype, op: ReductionOpInfo): """Tests reducing a transposed tensor.""" t = make_tensor((5, 5), dtype=dtype, device=device, low=-1, high=1) self._test_noncontiguous(op, t.T) @ops(reduction_ops) def test_noncontiguous_expanded(self, device, dtype, op: ReductionOpInfo): """Tests reducing a tensor with expanded singleton dimensions.""" t = make_tensor((2, 3), dtype=dtype, device=device, low=-1, high=1) self._test_noncontiguous(op, t.unsqueeze(1).expand(-1, 5, -1)) # NumPy does not support BFloat16 so we don't test that against reference # implementations. We also don't compare dtypes or test for different # keepdim because we already have other tests covering those. # The test_reference_testing in test_ops.py only uses the samples from # sample_inputs_func which do not test as exhaustively as these tests. def _test_ref(self, op: ReductionOpInfo, t: torch.Tensor, **reduction_kwargs): """Compares op against op.ref for the given input and reduction kwargs""" for args, kwargs in op.generate_args_kwargs(t, **reduction_kwargs): kwargs.update(reduction_kwargs) result = op(t, *args, **kwargs) expected = op.ref(t.detach().cpu().numpy(), *args, **kwargs) self.assertEqual(result, expected, exact_dtype=False) @ops(filter(lambda op: op.ref is not None, reduction_ops), allowed_dtypes=all_types_and_complex_and(torch.half, torch.bool)) def test_ref_scalar_input(self, device, dtype, op: ReductionOpInfo): """Compares op against reference for scalar input tensors""" self._test_ref(op, make_tensor([], dtype=dtype, device=device)) @ops(filter(lambda op: op.ref is not None, reduction_ops), allowed_dtypes=all_types_and_complex_and(torch.half, torch.bool)) def test_ref_small_input(self, device, dtype, op: ReductionOpInfo): """Compares op against reference for small input tensors""" t = make_tensor((5, 3, 4, 2), dtype=dtype, device=device, low=-2, high=2, exclude_zero=True) self._test_ref(op, t) for dim in [0, 1, 3] + ([[0, 2], [1, 3]] if op.supports_multiple_dims else []): self._test_ref(op, t, dim=dim) @ops(filter(lambda op: op.ref is not None, reduction_ops), allowed_dtypes=[torch.float64]) def test_ref_large_input_1D(self, device, dtype, op: ReductionOpInfo): """Compares op against reference for a large 1D input tensor to check stability""" self._test_ref(op, make_tensor((2 ** 20,), dtype=dtype, device=device, low=-1, high=1, exclude_zero=True)) @ops(filter(lambda op: op.ref is not None, reduction_ops), allowed_dtypes=[torch.float64]) def test_ref_large_input_2D(self, device, dtype, op: ReductionOpInfo): """Compares op against reference for a large 2D input tensor to test parallelism""" t = make_tensor((32, 2 ** 16), dtype=dtype, device=device, low=-1, high=1, exclude_zero=True) self._test_ref(op, t, dim=1) @largeTensorTest("8gb") @ops(filter(lambda op: op.ref is not None, reduction_ops), allowed_dtypes=[torch.float64]) def test_ref_large_input_64bit_indexing(self, device, dtype, op: ReductionOpInfo): """Compares op against reference for a very large input tensor that requires 64 bit indexing""" self._test_ref(op, make_tensor((275000000,), dtype=dtype, device=device, low=-1, high=1, exclude_zero=True)) @ops(filter(lambda op: op.ref is not None, reduction_ops), allowed_dtypes=all_types_and_complex_and(torch.half, torch.bool)) def test_ref_duplicate_values(self, device, dtype, op: ReductionOpInfo): """Compares op against reference for input tensors with duplicate values""" t = make_tensor((4, 4), dtype=dtype, device=device, low=-2, high=2, exclude_zero=True) t[::2, ::2] = t[1::2, 1::2] self._test_ref(op, t) self._test_ref(op, t, dim=0) self._test_ref(op, t, dim=1) @ops(filter(lambda op: op.ref is not None, reduction_ops), allowed_dtypes=[torch.float32, torch.complex64]) def test_ref_extremal_values(self, device, dtype, op: ReductionOpInfo): """Compares op against reference for input tensors with extremal values""" t = make_tensor((5,), dtype=dtype, device=device, exclude_zero=True) extremals = [0, 1, nan, inf, -inf] for extremal in extremals: t[2] = extremal self._test_ref(op, t) ########################################################################### # TODO: Legacy tests - port to ReductionOpInfo ########################################################################### def test_var_unbiased(self, device): tensor = torch.randn(100, device=device) self.assertEqual(tensor.var(0), tensor.var(0, unbiased=True)) self.assertEqual(tensor.var(), tensor.var(unbiased=True)) self.assertEqual(tensor.var(unbiased=False), tensor.var(0, unbiased=False)) tensor = torch.tensor([1.0, 2.0], device=device) self.assertEqual(tensor.var(unbiased=True), 0.5) self.assertEqual(tensor.var(unbiased=False), 0.25) tensor = torch.tensor([1.0, 2.0, 3.0], device=device) self.assertEqual(tensor.var(unbiased=True), 1.0) self.assertEqual(tensor.var(unbiased=False), 2.0 / 3.0) tensor = torch.randn(100, device=device) self.assertEqual(tensor.std(0), tensor.std(0, unbiased=True)) self.assertEqual(tensor.std(), tensor.std(unbiased=True)) self.assertEqual(tensor.std(unbiased=False), tensor.std(0, unbiased=False)) def test_var_stability(self, device): tensor = torch.tensor([2281.5, 2281.25], device=device) self.assertEqual(tensor.var(dim=0), 0.03125) self.assertEqual(tensor.var(), 0.03125) def test_sum_dim_reduction_uint8_overflow(self, device): example = [[-1, 2, 1], [5, 3, 6]] x = torch.tensor(example, dtype=torch.uint8, device=device) self.assertEqual(x.sum(dtype=torch.uint8).item(), 16) self.assertEqual(x.sum(0, dtype=torch.uint8), torch.tensor([4, 5, 7], dtype=torch.uint8, device=device)) self.assertEqual(x.sum(1, dtype=torch.uint8), torch.tensor([2, 14], dtype=torch.uint8, device=device)) y = torch.tensor(example, dtype=torch.uint8, device=device) torch.sum(x, 0, out=y) self.assertEqual(x.sum(0, dtype=torch.uint8), y) def test_dim_reduction_less_than_64(self, device): sizes = [1] * 65 x = torch.randn(sizes, device=device) ops = [torch.mean, torch.sum, torch.nansum, torch.std, torch.logsumexp, torch.std, torch.var, torch.norm] for op in ops: with self.assertRaisesRegex(RuntimeError, "only tensors with up to 64 dims are supported"): op(x, dim=64) with self.assertRaisesRegex(RuntimeError, "only tensors with up to 64 dims are supported"): op(x, dim=-1) @onlyCPU @dtypes(torch.float, torch.bfloat16) def test_dim_reduction_lastdim(self, device, dtype): x = torch.randn(3, 5, 40, device=device, dtype=dtype) x = x[:, :, 0:40:2] x2 = x.contiguous() ops = [torch.norm, torch.argmax, torch.argmin] for op in ops: y = op(x, dim=-1) y2 = op(x2, dim=-1) self.assertEqual(y, y2) @skipIfNoSciPy @dtypes(torch.float32, torch.double, torch.complex64, torch.complex128) def test_logsumexp(self, device, dtype): from scipy.special import logsumexp a = torch.randn(5, 4, device=device, dtype=dtype) # torch.exp(complex(inf, 0)) yields inf+nan*j instead of inf+0*j on CPU which disagrees with CUDA, C++ std::exp, # numpy and scipy. Skip inf testing on CPU. Related to https://github.com/pytorch/pytorch/issues/95740 if torch.device(device) != torch.device('cpu'): a[0, 0] = inf a[1, :] = -inf actual = a.logsumexp(1) expected = logsumexp(a.cpu().numpy(), 1) self.assertEqual(expected.shape, actual.shape) self.assertEqual(expected, actual) # check that out is actually inplace b = torch.zeros(5, 2, device=device, dtype=dtype) c = b[:, 0] torch.logsumexp(a, 1, out=c) self.assertEqual(expected, b[:, 0]) @skipIfNoSciPy def test_logsumexp_integral_promotion(self, device): from scipy.special import logsumexp # check integral inputs is promoted to floating point e = torch.randint(-100, 100, [5, 4], device=device) actual = e.logsumexp(1).to(torch.float64) expected = logsumexp(e.cpu().numpy(), 1) self.assertEqual(expected.shape, actual.shape) self.assertEqual(expected, actual) @skipIfNoSciPy @dtypes(torch.complex64, torch.complex128) def test_logcumsumexp_complex(self, device, dtype): # logcumsumexp is a more precise way to compute than ``log(cumsum(exp(a)))`` # and faster than ``[log(sum(exp(a[:i]))) for i in range(a.shape[0])]`` # the for-loop above should produce similar precision as logcumsumexp (it's just slower), # so it can be used as the expected values to check our computation # using logsumexp from scipy because by the time of writing this test code, # torch.logsumexp has not been implemented for complex numbers from scipy.special import logsumexp def zero_out_neg_inf(t): t = t.clone() idx = torch.logical_and(~(torch.isfinite(t)), torch.real(t) < 0) t[idx] = torch.real(t[idx]).to(t.dtype) return t def standardize_phase(t): t = torch.real(t) + 1j * (torch.imag(t) % (2 * np.pi)) return t def logcumsumexp_slow(a, dim): res_lst = [] for i in range(a.size(dim)): index = [slice(None, None, None) for _ in range(a.ndim)] index[dim] = slice(None, i + 1, None) a_inp = a[tuple(index)] res_lst.append(logsumexp(a_inp.cpu().numpy(), axis=dim, keepdims=True)) res = np.concatenate(res_lst, axis=dim) return torch.as_tensor(res) def compare_logcumsumexp(a, expected=None): for i in range(a.ndim): actual = torch.logcumsumexp(a, dim=i) # if the expected is not given, then revert to scipy's logsumexp if expected is None: expected2 = logcumsumexp_slow(a, dim=i) else: expected2 = expected # move the imaginary values to (0, 2 * pi) actual = standardize_phase(actual) expected2 = standardize_phase(expected2) # zeroing the imaginary part of the element if the real part is -inf # as the imaginary part cannot be determined exactly and it does not # really matter if we take the exp of the output actual = zero_out_neg_inf(actual) expected2 = zero_out_neg_inf(expected2) self.assertEqual(expected2.shape, actual.shape) self.assertEqual(expected2, actual) # randomly specified values # in this case, scipy.logsumexp should be enough a1 = torch.randn((5, 10), dtype=dtype, device=device) compare_logcumsumexp(a1) # test with some non-normal values a2 = torch.tensor([1e3 + 0j, 1e-18 + 1e4j, 1e2 + 1e-8j], dtype=dtype, device=device) compare_logcumsumexp(a2) # handle special case involving infinites and nans # here we don't use scipy.logsumexp as it gives confusing answer on # some inf cases # see here: inf = float('inf') nan = float('nan') a3_input = torch.tensor([ -inf + 4j, -inf + 1j, 1.2 + 2.1j, 1e10 + 1e20j, inf + 0j, inf + 1j, inf + 3j, nan + 2j, ]) a3_expected = torch.tensor([ -inf + 0j, -inf + 0j, 1.2 + 2.1j, 1e10 + 1e20j, inf + 0j, # scipy's logsumexp gives (inf + 0.7853982j) here, unclear why inf + (np.pi / 4) * 1j, # the imaginary part thanks to some weird behaviour of log(inf + infj) complex(inf, nan), complex(nan, nan), ]) # windows give strange results on the second-to-last results where it gives inf + pi/4 j # instead of inf + nan j if not IS_WINDOWS: compare_logcumsumexp(a3_input, a3_expected) a4_input = torch.tensor([ complex(-inf, inf), complex(-inf, inf), -inf + 1j, 1.2 + 2.1j, complex(2.4, inf), ]) a4_expected = torch.tensor([ -inf + 0j, -inf + 0j, -inf + 0j, 1.2 + 2.1j, complex(nan, nan), ]) if not IS_WINDOWS: compare_logcumsumexp(a4_input, a4_expected) @onlyCPU def test_sum_parallel(self, device): # To use parallel branches we'll need to compare on tensors # that are relatively large. Even if this is run on a single # core machine these tests will still give you signal on # the correctness def _run_test(size): for dim in range(len(size) + 1): nv = np.round(np.random.rand(*size)) # 0s and 1s tv = torch.from_numpy(nv) # Parallelisim is only used if numel is # larger than grainsize defined in Parallel.h self.assertTrue(tv.numel() > 32768) if dim == len(size): nvs = nv.sum() tvs = tv.sum() else: nvs = nv.sum(dim) tvs = tv.sum(dim) diff = np.abs(nvs - tvs.numpy()).sum() self.assertEqual(diff, 0) _run_test([2, 3, 3, 3, 3, 2, 2, 3, 2, 3, 2, 3, 3]) _run_test([4, 4, 4, 4, 4, 4, 4, 4, 4, 4]) _run_test([1, 32 * 8 * 32 * 8]) _run_test([1, 32770]) # TODO: kill map2_ (and similar) uses and update to compare with NumPy # only works on CPU since this uses map2_, which is only supported on CPU def _testCSelection(self, torchfn, mathfn): # Two tensors size = (100, 100) a = torch.rand(*size) b = torch.rand(*size) c = torchfn(a, b) expected_c = torch.zeros(*size) expected_c.map2_(a, b, lambda _, a, b: mathfn(a, b)) self.assertEqual(expected_c, c, atol=0, rtol=0) @onlyCPU def test_max_elementwise(self, device): self._testCSelection(torch.max, max) @onlyCPU def test_min_elementwise(self, device): self._testCSelection(torch.min, min) def test_all_any(self, device): def test(size): x = torch.ones(*size, device=device).byte() self.assertTrue(x.all()) self.assertTrue(x.any()) x[3] = 0 self.assertFalse(x.all()) self.assertTrue(x.any()) x.zero_() self.assertFalse(x.all()) self.assertFalse(x.any()) x.fill_(2) self.assertTrue(x.all()) self.assertTrue(x.any()) x = torch.ones(*size, device=device).bool() self.assertTrue(x.all()) self.assertTrue(x.any()) x[3] = False self.assertFalse(x.all()) self.assertTrue(x.any()) test((10,)) test((5, 5)) def test_all_any_with_dim(self, device): def test(x): r1 = x.prod(dim=0, keepdim=False).byte() r2 = x.all(dim=0, keepdim=False) self.assertEqual(r1.shape, r2.shape) self.assertTrue((r1 == r2).all()) r3 = x.sum(dim=1, keepdim=True).clamp(0, 1).byte() r4 = x.any(dim=1, keepdim=True) self.assertEqual(r3.shape, r4.shape) self.assertTrue((r3 == r4).all()) test(torch.tensor([[0, 0, 0], [0, 0, 1], [0, 1, 1], [1, 1, 1]], device=device, dtype=torch.uint8)) def test_numpy_named_args(self, device): x1 = torch.randn(10, device=device) x2 = torch.randn(10, device=device) res1 = torch.add(input=x1, other=x2) res2 = torch.add(x1=x1, x2=x2) self.assertEqual(res1, res2) x1 = torch.randn(10, 10, 10, device=device) res1 = x1.sum(dim=(0, 2), keepdim=True) res2 = x1.sum(axis=(0, 2), keepdims=True) self.assertEqual(res1, res2) # TODO: kill this and replace with common creation ops def _make_tensors(self, shape, val_range=(-100, 100), use_floating=True, use_integral=True, use_complex=False) -> dict[str, list[torch.Tensor]]: float_types = [torch.double, torch.float] int_types = [torch.int64, torch.int32, torch.int16] complex_types = [torch.complex64, torch.complex128] def make_contiguous(shape, dtype) -> torch.Tensor: if dtype in float_types: val = torch.randn(shape, dtype=dtype) val = val * ((val_range[1] - val_range[0]) / (math.pi * 2.0)) val = val + ((val_range[1] - val_range[0]) / 2.0) val = torch.clamp(val, min=val_range[0], max=val_range[1]) return val result = torch.zeros(shape, dtype=dtype) result.apply_(lambda x: random.randint(val_range[0], val_range[1])) return result def make_non_contiguous(shape, dtype) -> torch.Tensor: contig = make_contiguous(shape, dtype) non_contig = torch.empty(shape + (2, 2), dtype=dtype)[..., 0] non_contig = non_contig.select(-1, -1) non_contig.copy_(contig) self.assertFalse(non_contig.is_contiguous()) return non_contig def make_contiguous_slice(size, dtype) -> torch.Tensor: contig = make_contiguous((1, size), dtype) non_contig = contig[:1, 1:size - 1] self.assertTrue(non_contig.is_contiguous()) return contig types = [] if use_floating: types += float_types if use_integral: types += int_types if use_complex: types += complex_types tensors: dict[str, list[torch.Tensor]] = {"cont": [], "noncont": [], "slice": []} for dtype in types: tensors["cont"].append(make_contiguous(shape, dtype)) tensors["noncont"].append(make_non_contiguous(shape, dtype)) tensors["slice"].append(make_contiguous_slice(sum(list(shape)), dtype)) return tensors # TODO: refactor this to use comparators from common_utils def _assert_matches_numpy(self, t, n): self.assertEqual(n.shape, t.shape) if t.dtype == torch.float: self.assertEqual(n, t, rtol=1e-03, atol=1e-05, equal_nan=True) else: self.assertEqual(n, t, equal_nan=True) # TODO: update this and tests that use it to use the device argument properly def _test_dim_ops(self, pytorch_op, numpy_op, use_floating=True, use_integral=True, use_complex=False): def do_one(tensors_dict, dim): for category, tensors in tensors_dict.items(): if category == "slice": dim = 0 for tensor in tensors: # we have no control over NumPy warnings... with warnings.catch_warnings(): warnings.simplefilter("ignore") expected = numpy_op(tensor.cpu().numpy(), dim) actual = pytorch_op(tensor, dim) self._assert_matches_numpy(actual, expected) if torch.cuda.is_available(): self._assert_matches_numpy(pytorch_op(tensor.cuda(), dim).cpu(), expected) do_one(self._make_tensors((5, 400000), use_floating=use_floating, use_integral=use_integral, use_complex=use_complex), 1) do_one(self._make_tensors((3, 5, 7), use_floating=use_floating, use_integral=use_integral, use_complex=use_complex), 0) do_one(self._make_tensors((3, 5, 7), use_floating=use_floating, use_integral=use_integral, use_complex=use_complex), 1) do_one(self._make_tensors((3, 5, 7), use_floating=use_floating, use_integral=use_integral, use_complex=use_complex), 2) do_one(self._make_tensors((100000, ), use_floating=use_floating, use_integral=use_integral, use_complex=use_complex), -1) do_one(self._make_tensors((50, 50, 50), use_floating=use_floating, use_integral=use_integral, use_complex=use_complex), 0) do_one(self._make_tensors((50, 50, 50), use_floating=use_floating, use_integral=use_integral, use_complex=use_complex), 1) do_one(self._make_tensors((50, 50, 50), use_floating=use_floating, use_integral=use_integral, use_complex=use_complex), 2) do_one(self._make_tensors((50, 50, 50), use_floating=use_floating, use_integral=use_integral, use_complex=use_complex), (1, 2)) do_one(self._make_tensors((50, 50, 50), use_floating=use_floating, use_integral=use_integral, use_complex=use_complex), (1, -1)) do_one(self._make_tensors((50, 50, 50), use_floating=use_floating, use_integral=use_integral, use_complex=use_complex), (0, 2)) do_one(self._make_tensors((50, 50, 50), use_floating=use_floating, use_integral=use_integral, use_complex=use_complex), (0, 2, 1)) @slowTest @onlyCPU def test_sum_dim(self, device): self._test_dim_ops( lambda t, d: t.sum(d), lambda n, d: n.sum(d), use_floating=True, use_integral=True, use_complex=True) @onlyCPU def test_mean_dim(self, device): self._test_dim_ops( lambda t, d: t.mean(d), lambda n, d: n.mean(d), use_integral=False, use_complex=True) @onlyCPU def test_std_dim(self, device): for unbiased in [False, True]: self._test_dim_ops( lambda t, d: t.std(d, unbiased=unbiased), lambda n, d: n.std(d, ddof=1 if unbiased else 0), use_integral=False) @onlyCPU def test_var_dim(self, device): for unbiased in [False, True]: self._test_dim_ops( lambda t, d: t.var(d, unbiased=unbiased), lambda n, d: n.var(d, ddof=1 if unbiased else 0), use_integral=False) @onlyCPU @skipIfNoSciPy def test_logsumexp_dim(self, device): from scipy.special import logsumexp self._test_dim_ops( lambda t, d: t.logsumexp(d), lambda n, d: logsumexp(n, d), use_integral=False) @onlyCPU def test_mean_int_with_optdtype(self, device): a = make_tensor((3, 4, 5), dtype=torch.int64, device=device) # If the optional desired output type is given, the input # is internally cast. a_float = a.to(torch.float32) self.assertEqual(a_float.mean(), a.mean(dtype=torch.float32)) @onlyCPU @dtypes(torch.half, torch.bfloat16, torch.float, torch.double) def test_mean_out_is_alias_of_return(self, dtype, device): a = torch.tensor([[[1.0, 1.0, 1.0, 1.0]], [[2.0, 2.0, 2.0, 2.0]], [[3.0, 3.0, 3.0, 3.0]]], dtype=dtype, device=device) out = torch.empty((1, 1, 4), dtype=dtype, device=device) return_out = torch.mean(a, dim=0, keepdim=True, out=out) target = torch.tensor([[[2.0, 2.0, 2.0, 2.0]]], dtype=dtype, device=device) self.assertTrue(torch._C._is_alias_of(out, return_out)) self.assertTrue(torch.allclose(out, target)) # TODO: update this and tests that use it to handle device properly def _test_reduce_integer_upcast(self, fn, has_out=True, test_complex=True): shape = (3, 4, 5) reduced_shape = fn(torch.ones(shape)).shape def _test_out(dtype, other_dtype): out = torch.ones(reduced_shape, dtype=dtype) result = fn(x, out=out) self.assertIs(out.dtype, result.dtype) self.assertEqual(fn(x.to(dtype)), result, exact_dtype=False) result = fn(x, out=out, dtype=dtype) self.assertIs(out.dtype, result.dtype) self.assertEqual(fn(x.to(dtype)), result, exact_dtype=False) # 'out' is favored over dtype, check error self.assertRaises(RuntimeError, lambda: fn(x, out=out, dtype=other_dtype)) for dtype in [dtype for dtype in get_all_math_dtypes('cpu') if dtype != torch.float16]: x = torch.ones(shape, dtype=dtype) expected_dtype = dtype if dtype.is_floating_point or dtype.is_complex else torch.int64 self.assertIs(expected_dtype, fn(x).dtype) self.assertEqual(fn(x.to(expected_dtype)), fn(x)) if dtype.is_floating_point: other_dtype = torch.float32 if dtype == torch.float64 else torch.float64 elif dtype.is_complex: other_dtype = torch.complex64 if dtype == torch.complex128 else torch.complex128 else: other_dtype = torch.int32 if dtype != torch.int32 else torch.int16 self.assertIs(other_dtype, fn(x, dtype=other_dtype).dtype) self.assertEqual(fn(x.to(other_dtype)), fn(x, dtype=other_dtype), exact_dtype=False) # test mixed int/float/complex if dtype.is_floating_point: mixed_dtypes = [torch.int32, torch.complex64] elif dtype.is_complex: mixed_dtypes = [torch.int32, torch.float32] else: mixed_dtypes = [torch.float32, torch.complex64] for mixed_dtype in mixed_dtypes: self.assertIs(mixed_dtype, fn(x, dtype=mixed_dtype).dtype) self.assertEqual(fn(x.to(mixed_dtype)), fn(x, dtype=mixed_dtype), exact_dtype=False) if has_out: _test_out(dtype, other_dtype) _test_out(dtype, mixed_dtype) @onlyCPU def test_sum_integer_upcast(self, device): self._test_reduce_integer_upcast(lambda x, **kwargs: torch.sum(x, **kwargs), False) self._test_reduce_integer_upcast(lambda x, **kwargs: torch.sum(x, 0, **kwargs)) @onlyCPU def test_prod_integer_upcast(self, device): self._test_reduce_integer_upcast(lambda x, **kwargs: torch.prod(x, **kwargs), False) self._test_reduce_integer_upcast(lambda x, **kwargs: torch.prod(x, 0, **kwargs)) @onlyCPU def test_cumsum_integer_upcast(self, device): self._test_reduce_integer_upcast(lambda x, **kwargs: torch.cumsum(x, 0, **kwargs)) @onlyCPU def test_cumprod_integer_upcast(self, device): self._test_reduce_integer_upcast(lambda x, **kwargs: torch.cumprod(x, 0, **kwargs)) @dtypes(*all_types()) def test_mode(self, device, dtype): SIZE = 10 x = torch.arange(1., SIZE * SIZE + 1, device=device, dtype=dtype).clone().resize_(SIZE, SIZE) x[:2] = 1 x[:, :2] = 1 x0 = x.clone() # Pre-calculated results. res1val = torch.ones(SIZE, device=device, dtype=dtype) # The indices are the position of the last appearance of the mode element. res1ind = torch.ones(SIZE, device=device, dtype=torch.long) res1ind[0] = SIZE - 1 res1ind[1] = SIZE - 1 res2val, res2ind = torch.mode(x, keepdim=False) self.assertEqual(res1val, res2val, atol=0, rtol=0) self.assertEqual(res1ind, res2ind, atol=0, rtol=0) # Test use of result tensor res2val = torch.tensor((), device=device, dtype=dtype) res2ind = torch.tensor((), device=device, dtype=torch.long) torch.mode(x, keepdim=False, out=(res2val, res2ind)) self.assertEqual(res1val, res2val, atol=0, rtol=0) self.assertEqual(res1ind, res2ind, atol=0, rtol=0) # Test non-default dim res2val, res2ind = torch.mode(x, 0, False) self.assertEqual(res1val, res2val, atol=0, rtol=0) self.assertEqual(res1ind, res2ind, atol=0, rtol=0) # input unchanged self.assertEqual(x, x0, atol=0, rtol=0) def _test_mode_intervals(self, shape, intervals, device, dtype, v=1): x = torch.arange(0, shape[1], device=device, dtype=dtype).expand(shape) x = x.contiguous() x[:, v] = intervals[0][0] # Set the value of each interval to the mode "v" for (beg, end) in intervals: x[:, beg:end] = v values, indices = torch.mode(x, -1, False) # Check whether the returned indices correspond to the returned values self.assertTrue((x.gather(1, indices.unsqueeze(1)).t() == values).all()) # Check whether the returned values are the mode self.assertTrue((values == v).all().item()) @onlyCUDA @dtypes(*all_types_and(torch.half, torch.bfloat16)) def test_mode_large(self, device, dtype): # i should be less than (d - 2) / 2 def testset_for_shape(shape, i): d = shape[-1] # Mode only in the middle. self._test_mode_intervals(shape, [(i, d - i)], device, dtype) # Mode in discontiguous parts of the input. self._test_mode_intervals(shape, [(0, i), (i + 1, d - i - 1), (d - i, d)], device, dtype) # More than one line of (65535) thread blocks testset_for_shape((65536, 10), 3) # Max slice size (2048) testset_for_shape((10, 2048), 10) # Naive kernel for big slice sizes (> 2048) testset_for_shape((10, 4096), 10) def test_mode_boolean(self, device): shapes = [ (10, 10), (4, 2048), (1, 4096), ] for shape in shapes: a = torch.zeros(shape, device=device, dtype=torch.bool) a[:, (shape[1] - 1) // 2:] = True values, indices = a.mode(-1) self.assertEqual(values, torch.ones(shape[0], dtype=torch.bool)) indexed = a.gather(1, indices.unsqueeze(1)).squeeze(1) self.assertEqual(values, indexed) a.fill_(False) a[:, shape[1] // 2 + 1:] = True values, indices = a.mode(-1) print(indices) self.assertEqual(values, torch.zeros(shape[0], dtype=torch.bool)) indexed = a.gather(1, indices.unsqueeze(1)).squeeze(1) self.assertEqual(values, indexed) @expectedFailureMeta # mode only supports CPU and CUDA device type @onlyNativeDeviceTypes def test_mode_wrong_dtype(self, device): def test_for_dtypes(x_ty, v_ty, i_ty, message): x = torch.ones(10, device=device, dtype=x_ty) v = torch.ones(10, device=device, dtype=v_ty) i = torch.ones(10, device=device, dtype=i_ty) with self.assertRaisesRegex(RuntimeError, message): torch.mode(x, -1, True, out=(v, i)) err_msg = "expected scalar type .* but got .* for " values_err = err_msg + "values" indices_err = err_msg + "indices" test_for_dtypes(torch.uint8, torch.int8, torch.long, values_err) test_for_dtypes(torch.int8, torch.int16, torch.long, values_err) test_for_dtypes(torch.int32, torch.float32, torch.long, values_err) test_for_dtypes(torch.float32, torch.float64, torch.long, values_err) test_for_dtypes(torch.uint8, torch.uint8, torch.int8, indices_err) test_for_dtypes(torch.int8, torch.int8, torch.int16, indices_err) test_for_dtypes(torch.int32, torch.int32, torch.float32, indices_err) test_for_dtypes(torch.float32, torch.float32, torch.float64, indices_err) @onlyCUDA def test_mode_wrong_device(self, device): # CPU Input Tensor x = torch.ones(2) with self.assertRaisesRegex(RuntimeError, "expected device .* but got .* for values"): values = torch.tensor([], device=device) torch.mode(x, -1, True, out=(values, torch.tensor([], dtype=torch.long))) with self.assertRaisesRegex(RuntimeError, "expected device .* but got .* for indices"): indices = torch.tensor([], device=device) torch.mode(x, -1, True, out=(torch.tensor([]), indices)) # TODO: make work on CUDA, too @onlyCPU def test_accreal_type(self, device) -> None: x = torch.ones(2, 3, 4) self.assertIsInstance(x.double().sum().item(), float) self.assertIsInstance(x.float().sum().item(), float) self.assertIsInstance(x.long().sum().item(), int) self.assertIsInstance(x.int().sum().item(), int) self.assertIsInstance(x.short().sum().item(), int) self.assertIsInstance(x.char().sum().item(), int) self.assertIsInstance(x.byte().sum().item(), int) def test_var_mean_some_dims(self, device): sizes = (4, 6, 7, 5, 3) dims = len(sizes) x = torch.rand(sizes, device=device) for num_of_dims in range(2, dims): dim_list = list(combinations(list(range(dims)), r=num_of_dims)) for dim in dim_list: for unbiased in [False, True]: for keepdim in [False, True]: var1, mean1 = torch.var_mean(x, dim=dim, unbiased=unbiased, keepdim=keepdim) var2 = x.var(dim=dim, unbiased=unbiased, keepdim=keepdim) mean2 = x.mean(dim=dim, keepdim=keepdim) self.assertEqual(var1, var2) self.assertEqual(mean1, mean2) # TODO: this should be a generic opinfo test def test_all_any_empty(self, device): x = torch.ByteTensor().to(device) self.assertTrue(x.all()) self.assertFalse(x.any()) x = torch.BoolTensor().to(device) self.assertTrue(x.all()) self.assertFalse(x.any()) def test_all_issue117215(self, device): info = torch.iinfo(torch.uint8) a = torch.randint(info.min, info.max, (73, 11, 3, 17), dtype=torch.uint8) b = torch.all(a, dim=0) c = a.to(torch.bool).all(dim=0) self.assertEqual(torch.ne(b, c).sum(), 0) @dtypesIfCUDA(torch.half, torch.bfloat16, torch.float, torch.double) @dtypes(torch.half, torch.bfloat16, torch.float, torch.double) def test_max_with_inf(self, device, dtype): a = torch.tensor([[-inf, -inf, inf, 3], [inf, inf, -inf, -1]], dtype=dtype, device=device) self.assertTrue(torch.all(torch.max(a, dim=1).values == inf).item()) self.assertTrue(torch.all(torch.amax(a, dim=1) == inf).item()) self.assertTrue(torch.max(a).item() == inf) self.assertTrue(torch.amax(a).item() == inf) @dtypesIfCUDA(torch.half, torch.bfloat16, torch.float, torch.double) @dtypes(torch.half, torch.float, torch.bfloat16, torch.double) def test_min_with_inf(self, device, dtype): a = torch.tensor([[-inf, -inf, inf, 3], [inf, inf, -inf, -1]], dtype=dtype, device=device) self.assertTrue(torch.all(torch.min(a, dim=1).values == (-inf)).item()) self.assertTrue(torch.all(torch.amin(a, dim=1) == (-inf)).item()) self.assertTrue(torch.min(a).item() == -inf) self.assertTrue(torch.amin(a).item() == -inf) def _test_minmax_helper(self, torchfn, reffn, device, dtype, skip_indices=False): def create_input(shape, device, dtype): if dtype.is_floating_point: return torch.randn(*shape, device=device, dtype=dtype) else: low = 0 if dtype == torch.bool else -1000 high = 2 if dtype == torch.bool else 1000 return torch.randint(low, high, shape, device=device, dtype=dtype) x = create_input((100, 100), device, dtype) self.compare_with_numpy(torchfn, reffn, x) # non contiguous x = create_input((10, 10, 10), device, dtype) x = x[:, 4] self.compare_with_numpy(torchfn, reffn, x) def get_values(x): if isinstance(x, tuple): return x[0] return x # indices if not skip_indices: size = 5 x = create_input((size, size), device, dtype) inputs = (x, x.t()) dims = (0, 1) for xinp, d in product(inputs, dims): self.compare_with_numpy(lambda x: get_values(torchfn(x, d, False)), lambda x: reffn(x, d, keepdims=False), xinp) result = torchfn(xinp, d, False) if isinstance(result, tuple): v, i = result if d == 1: self.assertEqual(xinp[torch.arange(size), i], v, atol=0, rtol=0) else: self.assertEqual(xinp[i, torch.arange(size)], v, atol=0, rtol=0) # nan if dtype.is_floating_point: for index in (0, 4, 99): x = create_input((100,), device, dtype) x[index] = nan if not skip_indices: result = torchfn(x, 0) v = get_values(result) self.assertEqual(v, nan) if isinstance(result, tuple): i = result[1] self.assertEqual(i, index) self.assertEqual(torchfn(x), nan) @dtypesIfCPU(torch.float, torch.double, torch.long, torch.bool, torch.half) @dtypesIfCUDA(torch.half, torch.float, torch.long, torch.bool) @dtypes(torch.half, torch.float, torch.double) def test_max(self, device, dtype): self._test_minmax_helper(torch.max, np.amax, device, dtype) @dtypesIfCPU(torch.float, torch.double, torch.long, torch.bool, torch.half) @dtypesIfCUDA(torch.half, torch.float, torch.long, torch.bool) @dtypes(torch.half, torch.float, torch.double) def test_min(self, device, dtype): self._test_minmax_helper(torch.min, np.amin, device, dtype) @dtypesIfCPU(torch.half, torch.float, torch.double, torch.int, torch.long, torch.bool) @dtypesIfCUDA(torch.half, torch.float, torch.int, torch.long, torch.bool) @dtypes(torch.half, torch.float, torch.double) def test_amin(self, device, dtype): self._test_minmax_helper(torch.amin, np.amin, device, dtype) @dtypesIfCPU(torch.half, torch.float, torch.double, torch.int, torch.long, torch.bool) @dtypesIfCUDA(torch.half, torch.float, torch.int, torch.long, torch.bool) @dtypes(torch.float, torch.double) def test_amax(self, device, dtype): self._test_minmax_helper(torch.amax, np.amax, device, dtype) @onlyNativeDeviceTypes @dtypes(torch.float, torch.double, torch.bfloat16, torch.half) @dtypesIfCUDA(torch.half, torch.float, torch.bfloat16) def test_aminmax(self, device, dtype): def _amin_wrapper(x, dim=None, keepdims=False): return torch.aminmax(x, dim=dim, keepdim=keepdims)[0] def _amax_wrapper(x, dim=None, keepdims=False): return torch.aminmax(x, dim=dim, keepdim=keepdims)[1] self._test_minmax_helper(_amin_wrapper, np.amin, device, dtype) self._test_minmax_helper(_amax_wrapper, np.amax, device, dtype) @onlyNativeDeviceTypes @dtypes(*complex_types()) def test_invalid_0dim_aminmax(self, device, dtype): with self.assertRaisesRegex(RuntimeError, 'not implemented'): torch.aminmax(torch.tensor(1., dtype=dtype, device=device), dim=0) # TODO: bincount isn't a classic reduction -- maybe this test suite is # reductions and summary ops? def test_bincount(self, device): # negative input throws with self.assertRaisesRegex(RuntimeError, '1-d non-negative integral'): torch.bincount(torch.tensor([1, -1], device=device)) # n-d input, with n > 1 throws with self.assertRaisesRegex(RuntimeError, '1-d non-negative integral'): torch.bincount(torch.tensor([[1, 2], [3, 4]], device=device)) # floating input type throws with self.assertRaisesRegex(RuntimeError, 'not implemented'): torch.bincount(torch.tensor([1., 0.3], device=device)) # minlength < 0 throws with self.assertRaisesRegex(RuntimeError, 'minlength should be >= 0'): torch.bincount(torch.tensor([1, 3], device=device), torch.tensor([.2, .2], device=device), minlength=-1) # n-d weights, with n > 1 throws with self.assertRaisesRegex(RuntimeError, '1-d'): torch.bincount(torch.tensor([1, 0], device=device), torch.tensor([[1., 0.3], [1., 0.3]], device=device)) # input and weights dim mismatch with self.assertRaisesRegex(RuntimeError, 'same length'): torch.bincount(torch.tensor([1, 0], device=device), torch.tensor([1., 0.3, 0.5], device=device)) # 1-d input with no elements and default minlength self.assertEqual(torch.bincount(torch.tensor([], device=device, dtype=torch.long)), torch.zeros(0, dtype=torch.long, device=device)) # 1-d input with no elements and specified minlength self.assertEqual(torch.bincount(torch.tensor([], device=device, dtype=torch.long), minlength=10), torch.zeros(10, dtype=torch.long, device=device)) # test tensor method without weights long_counts = torch.tensor( [0, 3, 2, 1, 3], dtype=torch.uint8, device=device).bincount() self.assertEqual( torch.tensor([1, 1, 1, 2], dtype=torch.int64, device=device), long_counts) # test avoiding overflow for uint8 (#76979) count_uint8 = torch.tensor([0, 1, 2, 3, 255], dtype=torch.uint8, device=device).bincount() count_int16 = torch.tensor([0, 1, 2, 3, 255], dtype=torch.int16, device=device).bincount() self.assertEqual(count_uint8, count_int16) # test minlength functionality int_counts = torch.bincount( torch.tensor([1, 1, 1, 1], device=device), minlength=5) self.assertEqual( torch.tensor([0, 4, 0, 0, 0], dtype=torch.int64, device=device), int_counts) # test weights byte_counts = torch.bincount( torch.tensor([0, 1, 1, 1, 4], device=device), torch.tensor([.1, .2, .3, .4, .5], device=device)) self.assertEqual( torch.tensor([0.1, 0.9, 0, 0, 0.5], device=device), byte_counts) byte_counts = torch.bincount( torch.tensor([0, 1, 1, 1, 4], device=device), torch.tensor([1, 2, 3, 4, 5], dtype=torch.int8, device=device)) self.assertEqual( torch.tensor([1, 9, 0, 0, 5], device=device, dtype=torch.float64), byte_counts) # test non-contiguous inputs and weights inputs = torch.tensor([[0, 0], [3, 1], [2, 1], [1, 1], [3, 4]], device=device) weights = torch.tensor([[.1, 1], [.2, 2], [.3, 3], [.4, 4], [.5, 5]], device=device) for i in [0, 1]: assert not inputs[:, i].is_contiguous(), "Inputs are supposed to be non-contiguous" assert not weights[:, i].is_contiguous(), "Weights are supposed to be non-contiguous" # inputs are non-contiguous but weights are contiguous self.assertEqual(inputs[:, 0].bincount(), torch.tensor([1, 1, 1, 2])) # inputs and weights are non-contiguous self.assertEqual( inputs[:, 1].bincount(weights[:, 1]), torch.tensor([1, 9, 0, 0, 5], dtype=torch.float32)) # weights are non-contiguous but inputs are contiguous self.assertEqual(inputs[:, 1].contiguous().bincount(weights[:, 1]), torch.tensor([1, 9, 0, 0, 5], dtype=torch.float32)) # test bincount on non-contiguous slices all0s = torch.zeros((32, 2), dtype=torch.int64, device=device) self.assertEqual(all0s[:, 0].bincount(), torch.tensor([32])) all1s = torch.ones((32, 2), dtype=torch.int64, device=device) self.assertEqual(all1s[:, 0].bincount(), torch.tensor([0, 32])) # test large number of bins - global memory use big_exp = torch.zeros(10000000, device=device) big_exp[-1] = 50.0 big_w = torch.tensor([.5] * 100, device=device) big_out = torch.tensor([9999999] * 100, device=device).bincount(big_w) self.assertEqual(big_exp, big_out) # test large input size big_exp = torch.zeros(2, device=device, dtype=torch.int64) big_exp[1] = 1000000 big_out = torch.ones(1000000, dtype=torch.int8, device=device).bincount() self.assertEqual(big_exp, big_out) # TODO: how many var stability tests are there? def test_var_stability2(self, device): tensor = torch.FloatTensor([2281.5, 2281.25]).to(device) # Stability for inner dim self.assertEqual(tensor.var(0), 0.03125) # General stability self.assertEqual(tensor.var(), 0.03125) # Stability for outer dimensions tensor = tensor.unsqueeze(1) self.assertEqual(tensor.var(0), 0.03125) @onlyCPU @dtypes(torch.bfloat16, torch.float16) def test_sum_noncontig_lowp(self, device, dtype) -> None: dim_sequences = { 2: [0, 1], 3: [0, 1, 2], 4: [0, 1, 2, 3], 5: [0, 1, 2, 3, 4], } def create_noncontig_inputs(x, ndim): if ndim == 2: return x[::2, ::2] elif ndim == 3: return x[::2, ::2, ::2] elif ndim == 4: return x[::2, ::2, ::2, ::2] elif ndim == 5: return x[::2, ::2, ::2, ::2, ::2] def helper(self, shape, reduce_dims, device, dtype): for permute_list in list(permutations(dim_sequences[len(shape)], len(shape))): x = torch.ones(shape, device=device, dtype=dtype) x = create_noncontig_inputs(x, len(shape)) x_trans = x.permute(permute_list) x_sum = torch.sum(x_trans, reduce_dims) x_trans_ref = x_trans.float() x_sum_ref = torch.sum(x_trans_ref, reduce_dims) self.assertEqual(x_sum, x_sum_ref.to(dtype=dtype)) shapes = [ (50, 50), (50, 50, 50), (10, 50, 30, 30), (10, 5, 10, 50, 7), ] for shape in shapes: for i in range(1, len(shape) + 1): reduce_dims = list(combinations(dim_sequences[len(shape)], i)) for reduce_dim in reduce_dims: helper(self, shape, reduce_dim, device, dtype) @onlyCPU @dtypes(torch.bool, torch.double) def test_sum_all(self, device, dtype) -> None: def check_sum_all(tensor: torch.Tensor) -> None: pylist = tensor.reshape(-1).tolist() self.assertEqual(tensor.sum(), sum(pylist)) if dtype != torch.bool: check_sum_all(torch.tensor([1, 2, 3, 4, 5], dtype=dtype, device=device)) check_sum_all(torch.randn(200000, dtype=dtype, device=device)) check_sum_all(torch.randn(2000, 2, dtype=dtype, device=device)[:, 0]) else: check_sum_all(torch.tensor([True, False, True], dtype=torch.bool, device=device)) def _test_memory_format_transformations(self, device, input_generator_fn, transformation_fn, memory_format, compare_data=True, default_is_preserve=False): assert memory_format == torch.channels_last or memory_format == torch.channels_last_3d # xc is a channels last tensor xc = input_generator_fn(device) # xc is not memory dense, but looks like channels last if memory_format == torch.channels_last: xc = xc[..., ::2, ::2] else: xc = xc[..., ::2, ::2, ::2] clone = transformation_fn(xc, memory_format=torch.preserve_format) self.assertFalse(clone.is_contiguous()) self.assertTrue(clone.is_contiguous(memory_format=memory_format)) self.assertFalse(xc.is_contiguous()) self.assertFalse(xc.is_contiguous(memory_format=memory_format)) if compare_data: self.assertEqual(xc, clone.to(xc)) xc = input_generator_fn(device) clone = transformation_fn(xc, memory_format=torch.contiguous_format) self.assertTrue(clone.is_contiguous()) self.assertFalse(clone.is_contiguous(memory_format=memory_format)) if compare_data: self.assertEqual(xc, clone.to(xc)) xc = input_generator_fn(device) clone = transformation_fn(xc) if default_is_preserve: self.assertFalse(clone.is_contiguous()) self.assertTrue(clone.is_contiguous(memory_format=memory_format)) else: self.assertTrue(clone.is_contiguous()) self.assertFalse(clone.is_contiguous(memory_format=memory_format)) if compare_data: self.assertEqual(xc, clone.to(xc)) x = torch.randn((3, 4, 5, 6, 7, 8, 9), device=device) for _ in range(10): permutation = list(range(len(x.shape))) random.shuffle(permutation) x = x.permute(permutation) self.assertEqual(x.stride(), transformation_fn(x, memory_format=torch.preserve_format).stride()) @onlyCPU @dtypes(torch.double) def test_sum_out(self, device, dtype: torch.dtype) -> None: x = torch.rand(100, 100, dtype=dtype, device=device) res1 = torch.sum(x, 1) res2 = torch.tensor((), dtype=dtype, device=device) torch.sum(x, 1, out=res2) self.assertEqual(res1, res2) x = torch.rand(100, 100, 100, dtype=dtype, device=device) res1 = x.sum(2).sum(1) res2 = torch.tensor((), dtype=dtype, device=device) torch.sum(x, (2, 1), out=res2) self.assertEqual(res1, res2) @onlyCUDA @dtypes(torch.float16, torch.float32) def test_prod_gpu(self, device, dtype): x = torch.tensor([2, 3, 6, 9, 8], dtype=dtype, device=device) # Check all combinations: fp16 input - fp16 output, fp16 input - fp32 # output, fp32 input - fp16 output, fp32 input - fp32 output for dtype_output in [torch.float16, torch.float32]: result_expected = torch.tensor(2592, dtype=dtype_output, device=device) output = torch.prod(x, dtype=dtype_output) self.assertEqual(output, result_expected) output = x.prod(dtype=dtype_output) self.assertEqual(output, result_expected) @onlyCPU @dtypes(torch.float) def test_prod(self, device, dtype): x = torch.rand(100, 100, dtype=dtype, device=device) res1 = torch.prod(x, 1) res2 = torch.tensor((), dtype=dtype, device=device) torch.prod(x, 1, out=res2) self.assertEqual(res1, res2) @onlyCPU @dtypes(torch.float16, torch.bfloat16) def test_prod_lowp(self, device, dtype): x = torch.rand(100, 100, dtype=dtype, device=device) x_ref = x.float() res1 = torch.prod(x, 1) res2 = torch.prod(x_ref, 1) self.assertEqual(res1, res2.to(dtype=dtype)) res1 = torch.prod(x, 0) res2 = torch.prod(x_ref, 0) self.assertEqual(res1, res2.to(dtype=dtype)) def test_prod_bool(self, device): vals = [ [True, True], [True, False], [False, False], [], [False] * 256, # https://github.com/pytorch/pytorch/issues/127866 ] for val in vals: result = torch.prod(torch.tensor(val, device=device), dtype=torch.bool).item() expect = np.prod(np.array(val), dtype=bool) self.assertEqual(result, expect) result = torch.prod(torch.tensor(val, device=device)).item() expect = np.prod(np.array(val)) self.assertEqual(result, expect) @onlyCPU def test_max_mixed_devices(self, device): a = torch.randn(10, device=device) if torch.cuda.is_available(): values = torch.randn(10).cuda() indices = torch.cuda.LongTensor() self.assertRaises(RuntimeError, lambda: torch.max(a, 0, out=(values, indices))) self.assertRaises(RuntimeError, lambda: torch.amax(a, 0, out=values)) @onlyCPU def test_min_mixed_devices(self, device): a = torch.randn(10, device=device) if torch.cuda.is_available(): values = torch.randn(10).cuda() indices = torch.cuda.LongTensor() self.assertRaises(RuntimeError, lambda: torch.min(a, 0, out=(values, indices))) self.assertRaises(RuntimeError, lambda: torch.amin(a, 0, out=values)) # TODO: consider refactoring with bincount test def test_bucketization(self, device): values_1d = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9], device=device) values_3d = torch.tensor([[[1, 3, 5], [2, 4, 6]], [[1, 2, 3], [4, 5, 6]]], device=device) # simple 1d boundary and 3d input value boundaries = torch.tensor([1, 2, 3, 4, 5, 6], device=device) expected_result = torch.tensor([[[0, 2, 4], [1, 3, 5]], [[0, 1, 2], [3, 4, 5]]], device=device) output = torch.empty(2, 2, 3, device=device, dtype=torch.int64) self.assertEqual(torch.bucketize(values_3d, boundaries), expected_result) self.assertEqual(torch.bucketize(values_3d, boundaries, out=output), expected_result) expected_result = torch.tensor([[[1, 3, 5], [2, 4, 6]], [[1, 2, 3], [4, 5, 6]]], device=device) self.assertEqual(torch.bucketize(values_3d, boundaries, right=True), expected_result) self.assertEqual(torch.bucketize(values_3d, boundaries, out=output, right=True), expected_result) # simple float 1d boundary and 1d input with output int32 type for dtype in [torch.float32, torch.float16]: values_1d_float = values_1d.to(dtype) boundaries = torch.tensor([0.9, 1, 2, 2, 3, 3, 4, 4.1, 9, 9], device=device, dtype=dtype) expected_result = torch.tensor([1, 2, 4, 6, 8, 8, 8, 8, 8], device=device, dtype=torch.int32) self.assertEqual(torch.searchsorted(boundaries, values_1d_float, out_int32=True), expected_result) self.assertEqual(torch.bucketize(values_1d_float, boundaries, out_int32=True), expected_result) # multiple dimension input with 0 elements boundaries = torch.tensor([1, 2, 3, 4, 5, 6], device=device, dtype=torch.int64) values_0_el = torch.tensor([[[]]], device=device, dtype=torch.int64) expected_result = values_0_el.to(torch.int64) self.assertEqual(torch.searchsorted(boundaries, values_0_el), expected_result) self.assertEqual(torch.bucketize(values_0_el, boundaries), expected_result) # nan input values_nan = torch.tensor([1.0, float('nan'), 2.0, float('nan')], device=device, dtype=torch.float64) boundaries = torch.tensor([0.0, 1.0, 2.0, 3.0], device=device, dtype=torch.float64) expected_result = torch.tensor([1, 4, 2, 4], device=device) self.assertEqual(torch.searchsorted(boundaries, values_nan), expected_result) expected_result = torch.tensor([2, 4, 3, 4], device=device) self.assertEqual(torch.searchsorted(boundaries, values_nan, right=True), expected_result) self.assertEqual(torch.searchsorted(boundaries, values_nan, side='right'), expected_result) # type promotion and non contiguous tensors values_3d_permute = values_3d.permute(2, 1, 0).to(torch.int32) boundaries_permute = values_3d.permute(2, 1, 0).to(torch.float64) expected_result = torch.tensor([[[0, 0], [0, 1]], [[2, 0], [0, 1]], [[2, 0], [0, 0]]], device=device) if self.device_type != 'xla': self.assertWarnsRegex( UserWarning, "tensor is non-contiguous", lambda: self.assertEqual(torch.searchsorted(boundaries_permute, values_3d_permute), expected_result)) else: # All tensors in XLA is contiguous even doing permute, no warning msg will be generate in XLA self.assertEqual(torch.searchsorted(boundaries_permute, values_3d_permute), expected_result) # scalar type boundaries = torch.tensor([1.5, 2.5, 3.5], device=device) expected_result = torch.tensor(1, device=device) self.assertEqual(torch.searchsorted(boundaries, 2), expected_result) self.assertEqual(torch.bucketize(torch.tensor(2, device=device), boundaries), expected_result) expected_result = torch.tensor(3, device=device) scalar_tensor_nan = torch.tensor(float('nan'), device=device) self.assertEqual(torch.searchsorted(boundaries, scalar_tensor_nan), expected_result) self.assertEqual(torch.bucketize(float('nan'), boundaries, right=True), expected_result) # invalid input dimensions boundaries = torch.tensor([[1, 2, 3], [4, 5, 6]], device=device) with self.assertRaisesRegex( RuntimeError, "first N-1 dimensions of boundaries tensor and input value tensor must match"): torch.searchsorted(boundaries, values_3d) with self.assertRaisesRegex( RuntimeError, "boundaries tensor must be 1 dimension"): torch.bucketize(values_3d, boundaries) with self.assertRaisesRegex( RuntimeError, "only when boundaries tensor dimension is 1"): torch.searchsorted(boundaries, 1) # incompatible output tensor's dtype def test_output_dtype(dtype, is_int32): output = values_1d.to(dtype) with self.assertRaisesRegex( RuntimeError, "output tensor's dtype is wrong"): torch.searchsorted(values_1d, values_1d, out=output, out_int32=is_int32) test_output_dtype(torch.float32, False) test_output_dtype(torch.int32, False) test_output_dtype(torch.int64, True) # invalid side argument with self.assertRaisesRegex(RuntimeError, "side can only be 'left' or 'right'"): torch.searchsorted(values_1d, values_1d, side='bad') # invalid sorter argument, wrong size with self.assertRaisesRegex(RuntimeError, "boundary and sorter must have the same size"): sequence = torch.rand_like(values_1d, dtype=torch.float) _, sorted_idx = torch.sort(sequence) torch.searchsorted(sequence, values_1d, sorter=sorted_idx[:-1]) # invalid sorter argument, is not dtype long with self.assertRaisesRegex(RuntimeError, "sorter must be a tensor of long dtype"): sequence = torch.rand_like(values_1d, dtype=torch.float) _, sorted_idx = torch.sort(sequence) torch.searchsorted(sequence, values_1d, sorter=sorted_idx.to(torch.float32)) # invalid sorter value, out of bound (>= innermost size) with self.assertRaisesRegex(RuntimeError, "sorter index out of range"): torch.searchsorted(torch.tensor([1, 2, 3]), 2.5, sorter=torch.tensor([0, 1, 3])) # invalid sorter value, out of bound (< 0) with self.assertRaisesRegex(RuntimeError, "sorter index out of range"): torch.searchsorted(torch.tensor([1, 2, 3]), 2.5, sorter=torch.tensor([-1, 1, 2])) # scalar type bfloat16 if self.device_type == 'cpu': def test_dtype_bfloat16(values_bf16=False, boundaries_bf16=False): values_1d_float = values_1d.to(torch.float32) boundaries = torch.tensor([0.9, 1, 2, 2, 3, 3, 4, 4.1, 9, 9], device=device, dtype=torch.float32) if values_bf16: values_1d_float = values_1d_float.to(torch.bfloat16) if boundaries_bf16: boundaries = boundaries.to(torch.bfloat16) expected_result = torch.tensor([1, 2, 4, 6, 8, 8, 8, 8, 8], device=device, dtype=torch.int32) self.assertEqual(torch.bucketize(values_1d_float, boundaries, out_int32=True), expected_result) test_dtype_bfloat16(True, False) test_dtype_bfloat16(False, True) test_dtype_bfloat16(True, True) @dtypes(*all_types_and(torch.half, torch.bfloat16)) def test_nansum(self, device, dtype): args = product( (True, False), # noncontiguous (0, 1, None), # dim ) zero = torch.zeros((), device=device, dtype=dtype) for noncontiguous, dim in args: # Randomly scale the values scale = random.randint(10, 100) x = make_tensor((17, 17), device=device, dtype=dtype, low=-scale, high=scale, noncontiguous=noncontiguous) if dtype.is_floating_point: nan_mask = x < 0.2 * scale x_nonan = torch.where(nan_mask, zero, x) x[nan_mask] = np.nan else: x_nonan = x dim_kwargs = {} if dim is None else {"dim": dim} expect = torch.sum(x_nonan, **dim_kwargs) actual = torch.nansum(x, **dim_kwargs) self.assertEqual(expect, actual) def _test_reduction_function_with_numpy(self, torch_func, np_func, device, dtype, with_extremal=False, atol=None, rtol=None, exact_dtype=True, with_keepdim=False): # Test 0-d to 3-d tensors. for ndims in range(4): shape = _rand_shape(ndims, min_size=5, max_size=10) for n in range(ndims + 1): for c in combinations(list(range(ndims)), n): for count_dim in permutations(c): # Generate Input. x = _generate_input(shape, dtype, device, with_extremal) if count_dim == (): # Default `dims=None` case self.compare_with_numpy(torch_func, np_func, x, device=None, dtype=None, atol=atol, rtol=rtol, exact_dtype=exact_dtype) else: # With `dims: tuple of ints` case if with_keepdim: torch_func_partial = partial(torch_func, keepdim=True, dim=count_dim) np_func_partial = partial(np_func, keepdims=True, axis=count_dim) else: torch_func_partial = partial(torch_func, dim=count_dim) np_func_partial = partial(np_func, axis=count_dim) self.compare_with_numpy(torch_func_partial, np_func_partial, x, device=None, dtype=None, atol=atol, rtol=rtol, exact_dtype=exact_dtype) @dtypes(*all_types_and_complex_and(torch.half)) def test_count_nonzero(self, device, dtype): self._test_reduction_function_with_numpy(torch.count_nonzero, np.count_nonzero, device, dtype) self._test_reduction_function_with_numpy(torch.count_nonzero, np.count_nonzero, device, dtype, True) # TODO: Investigate why the output is not close to numpy. def _get_relaxed_tolerances_for(self, dtype): if dtype == torch.float16: atol = 0.4 rtol = 1e-2 elif dtype == torch.float32: atol = 7e-05 rtol = 3e-06 else: # Default values atol = None rtol = None return atol, rtol def _test_sum_reduction_vs_numpy(self, torch_fn, np_fn, device, dtype, with_keepdim=False, with_extremal=False): def is_integral(dtype): return dtype in integral_types() exact_dtype = True # On Windows CI, the current version of `numpy` promotes all lower integers # dtypes to int32 while `torch` promotes them to int64. Hence we skip on checking # the exact dtype. # PR : https://github.com/pytorch/pytorch/pull/38628#issuecomment-655905370 if IS_WINDOWS and is_integral(dtype): exact_dtype = False # For uint8, numpy promotes to uint64 while torch promotes to int64. # So we must skip this as well. if dtype == torch.uint8: exact_dtype = False # TODO: Investigate why the output is not close to numpy. atol, rtol = self._get_relaxed_tolerances_for(dtype) self._test_reduction_function_with_numpy(torch_fn, np_fn, device, dtype, atol=atol, rtol=rtol, exact_dtype=exact_dtype, with_keepdim=with_keepdim, with_extremal=with_extremal) @onlyNativeDeviceTypes @dtypes(*set(all_types_and(torch.half)) - {torch.uint8}) def test_sum_vs_numpy(self, device, dtype): self._test_sum_reduction_vs_numpy(torch.sum, np.sum, device, dtype) self._test_sum_reduction_vs_numpy(torch.sum, np.sum, device, dtype, with_extremal=True) self._test_sum_reduction_vs_numpy(torch.sum, np.sum, device, dtype, with_keepdim=True) @onlyNativeDeviceTypes @dtypes(*set(all_types_and(torch.half)) - {torch.uint8}) def test_nansum_vs_numpy(self, device, dtype): self._test_sum_reduction_vs_numpy(torch.nansum, np.nansum, device, dtype) self._test_sum_reduction_vs_numpy(torch.nansum, np.nansum, device, dtype, with_extremal=True) self._test_sum_reduction_vs_numpy(torch.nansum, np.nansum, device, dtype, with_keepdim=True) @onlyCPU @dtypes(*complex_types()) def test_nansum_complex(self, device, dtype): x = torch.randn((3, 3, 3), device=device, dtype=dtype) with self.assertRaisesRegex(RuntimeError, "nansum on CPU does not support complex inputs"): torch.nansum(x) @dtypes(*all_types_and(torch.half)) def test_nansum_out_dtype(self, device, dtype): out_dtype = dtype inp_dtypes = all_types_and(torch.half) if out_dtype.is_floating_point else integral_types() for inp_dtype in inp_dtypes: # TODO: Investigate why the output is not close to numpy. atol, rtol = self._get_relaxed_tolerances_for(dtype) shape = _rand_shape(random.randint(2, 5), min_size=5, max_size=10) x = _generate_input(shape, inp_dtype, device, with_extremal=False) torch_fn = partial(torch.nansum, dtype=out_dtype) np_out_dtype = torch_to_numpy_dtype_dict[out_dtype] np_fn = partial(np.nansum, dtype=np_out_dtype) self.compare_with_numpy(torch_fn, np_fn, x, device=None, dtype=None, atol=atol, rtol=rtol) @dtypes(*all_types_and(torch.half)) def test_argminmax_multiple(self, device, dtype): # Case: All Ones t = torch.ones(3, 3, device=device, dtype=dtype) self.compare_with_numpy(torch.argmax, np.argmax, t) self.compare_with_numpy(torch.argmin, np.argmin, t) # Case: With single `nan` present. if dtype in floating_types_and(torch.half, torch.bfloat16): t[2, 2] = float('nan') self.compare_with_numpy(torch.argmax, np.argmax, t) self.compare_with_numpy(torch.argmin, np.argmin, t) # Case: Randomly Generated Tensors for ndims in range(1, 5): shape = _rand_shape(ndims, min_size=5, max_size=10) for with_extremal in [False, True]: for contiguous in [False, True]: # Generate Input. x = _generate_input(shape, dtype, device, with_extremal) if dtype == torch.half: max_val = torch.max(x.to(torch.float)) min_val = torch.min(x.to(torch.float)) else: max_val = torch.max(x) min_val = torch.min(x) mask = torch.randn(x.shape) > 0.5 x[mask] = torch.tensor(max_val + 1, dtype=dtype) mask = torch.randn(x.shape) > 0.5 x[mask] = torch.tensor(min_val - 1, dtype=dtype) if not contiguous: x = x.T self.compare_with_numpy(torch.argmax, np.argmax, x, device=None, dtype=None) self.compare_with_numpy(torch.argmin, np.argmin, x, device=None, dtype=None) # Verify indices returned by max and min. if dtype != torch.half: rand_dim = random.randint(0, ndims - 1) self.compare_with_numpy(lambda x: torch.max(x, dim=rand_dim)[1], lambda x: np.argmax(x, axis=rand_dim), x, device=None, dtype=None) self.compare_with_numpy(lambda x: torch.min(x, dim=rand_dim)[1], lambda x: np.argmin(x, axis=rand_dim), x, device=None, dtype=None) def verify_against_numpy(t): # Argmax torch_fn = partial(torch.argmax, dim=1) np_fn = partial(np.argmax, axis=1) self.compare_with_numpy(torch_fn, np_fn, t) # Non-contiguous input self.compare_with_numpy(torch_fn, np_fn, t.T) # Verify indices returned by max. if dtype != torch.half: self.compare_with_numpy(lambda x: torch.max(x, dim=1)[1], np_fn, x, device=None, dtype=None) self.compare_with_numpy(lambda x: torch.max(x, dim=1)[1], np_fn, x.T, device=None, dtype=None) # Argmin torch_fn = partial(torch.argmin, dim=1) np_fn = partial(np.argmin, axis=1) self.compare_with_numpy(torch_fn, np_fn, t) # Non-contiguous input self.compare_with_numpy(torch_fn, np_fn, t.T) # Verify indices returned by min. if dtype != torch.half: self.compare_with_numpy(lambda x: torch.min(x, dim=1)[1], np_fn, x, device=None, dtype=None) self.compare_with_numpy(lambda x: torch.min(x, dim=1)[1], np_fn, x.T, device=None, dtype=None) # Case: Sample from issue: https://github.com/pytorch/pytorch/issues/41998 t = torch.tensor([[1, 5], [2, 10], [3, 3]], device=device, dtype=dtype) verify_against_numpy(t) # Case: Sample from issue: https://github.com/pytorch/pytorch/issues/41998 t = torch.tensor([[1, 5], [2, 10], [0, 0]], device=device, dtype=dtype) verify_against_numpy(t) @dtypes(*all_types_and_complex_and(torch.half, torch.bool)) def test_all_any_vs_numpy(self, device, dtype): # Note [all, any uint8 compatibility]: However for compatibility reason, # for `uint8`, they return Tensor of same dtype `uint8`. # Reference: https://github.com/pytorch/pytorch/pull/47878#issuecomment-747108561 exact_dtype = dtype != torch.uint8 def _test_all_any(x): self.compare_with_numpy(torch.all, np.all, x) self.compare_with_numpy(torch.any, np.any, x) def _test_all_any_with_dim(x, dim): torch_fn = partial(torch.all, dim=dim) np_fn = partial(np.all, axis=dim) self.compare_with_numpy(torch_fn, np_fn, x, exact_dtype=exact_dtype) torch_fn = partial(torch.any, dim=dim) np_fn = partial(np.any, axis=dim) self.compare_with_numpy(torch_fn, np_fn, x, exact_dtype=exact_dtype) def _test_out_variant(x, dim): out = torch.empty_like(x) if dtype == torch.bool or dtype == torch.uint8: expected = torch.all(x, dim) torch.all(x, dim, out=out) self.assertEqual(expected, out) expected = torch.any(x, dim) torch.any(x, dim, out=out) self.assertEqual(expected, out) else: with self.assertRaisesRegex(RuntimeError, "all only supports bool tensor for result, got"): torch.all(x, dim, out=out) with self.assertRaisesRegex(RuntimeError, "any only supports bool tensor for result, got"): torch.any(x, dim, out=out) def _test_all_any_with_dim_keepdim(x, dim, keepdim): torch_fn = partial(torch.all, dim=dim, keepdim=keepdim) np_fn = partial(np.all, axis=dim, keepdims=keepdim) self.compare_with_numpy(torch_fn, np_fn, x, exact_dtype=exact_dtype) torch_fn = partial(torch.any, dim=dim, keepdim=keepdim) np_fn = partial(np.any, axis=dim, keepdims=keepdim) self.compare_with_numpy(torch_fn, np_fn, x, exact_dtype=exact_dtype) def _test_output_dtype(x): # This test will fail once the functions return bool output # for uint8 input. expected_dtype = torch.uint8 if dtype == torch.uint8 else torch.bool self.assertEqual(torch.all(x).dtype, expected_dtype) self.assertEqual(torch.any(x).dtype, expected_dtype) self.assertEqual(torch.all(x, dim=0).dtype, expected_dtype) self.assertEqual(torch.any(x, dim=0).dtype, expected_dtype) for ndim in range(5): shape = _rand_shape(ndim, 1, 5) x = _generate_input(shape, dtype, device, with_extremal=False) _test_all_any(x) _test_all_any(x.T) _test_all_any(x[..., ::2]) x = _generate_input(shape, dtype, device, with_extremal=True) _test_all_any(x) _test_all_any(x.T) _test_all_any(x[..., ::2]) x = torch.zeros_like(x) _test_all_any(x) _test_all_any(x.T) _test_all_any(x[..., ::2]) x = torch.ones_like(x) _test_all_any(x) _test_all_any(x.T) _test_all_any(x[..., ::2]) _test_output_dtype(x) for dim in range(ndim): x = _generate_input(shape, dtype, device, with_extremal=False) _test_all_any_with_dim(x, dim) _test_all_any_with_dim(x.T, dim) _test_all_any_with_dim(x[..., ::2], dim) _test_out_variant(x, dim) _test_all_any_with_dim_keepdim(x, dim, keepdim=True) _test_all_any_with_dim_keepdim(x, dim, keepdim=False) x = _generate_input(shape, dtype, device, with_extremal=True) _test_all_any_with_dim(x, dim) _test_all_any_with_dim(x.T, dim) _test_all_any_with_dim(x[..., ::2], dim) _test_out_variant(x, dim) _test_all_any_with_dim_keepdim(x, dim, keepdim=True) _test_all_any_with_dim_keepdim(x, dim, keepdim=False) x = torch.zeros_like(x) _test_all_any_with_dim(x, dim) _test_all_any_with_dim(x.T, dim) _test_all_any_with_dim(x[..., ::2], dim) _test_out_variant(x, dim) _test_all_any_with_dim_keepdim(x, dim, keepdim=True) _test_all_any_with_dim_keepdim(x, dim, keepdim=False) x = torch.ones_like(x) _test_all_any_with_dim(x, dim) _test_all_any_with_dim(x.T, dim) _test_all_any_with_dim(x[..., ::2], dim) _test_out_variant(x, dim) _test_all_any_with_dim_keepdim(x, dim, keepdim=True) _test_all_any_with_dim_keepdim(x, dim, keepdim=False) # TODO: part of this test covers torch.norm, with should be covered by test_linalg @onlyNativeDeviceTypes def test_repeated_dim(self, device): ops = [torch.mean, torch.sum, torch.nansum, torch.std, torch.logsumexp, torch.std, torch.var, torch.norm] x = torch.randn(3, 3, 3, 3, device=device) error_msg = r'appears multiple times in the list of dims' for op in ops: for dim in [(0, 0), (0, -4)]: with self.assertRaisesRegex(RuntimeError, error_msg): op(x, dim=dim) # TODO: update this test to compare against NumPy @onlyCUDA def test_var(self, device): cpu_tensor = torch.randn(2, 3, 3) device_tensor = cpu_tensor.to(device) self.assertEqual(device_tensor.var(), cpu_tensor.var()) self.assertEqual(device_tensor.var(1), cpu_tensor.var(1)) self.assertEqual(device_tensor.var(2), cpu_tensor.var(2)) self.assertEqual(device_tensor.std(), cpu_tensor.std()) self.assertEqual(device_tensor.std(1), cpu_tensor.std(1)) self.assertEqual(device_tensor.var(2), cpu_tensor.var(2)) cpu_tensor = torch.randn(100) device_tensor = cpu_tensor.to(device) self.assertEqual(device_tensor.var(), cpu_tensor.var()) # TODO: update this test to compare against NumPy @onlyCUDA def test_var_large_input(self, device): # Large, not-nice input cpu_tensor = torch.randn(2 * 32 * 1024 + 1, 2, 67) device_tensor = cpu_tensor.to(device) self.assertEqual(cpu_tensor.var(2), device_tensor.var(2)) # TODO: update this to compare against NumPy instead of CPU @onlyCUDA @dtypes(torch.double) def test_sum_noncontig(self, device, dtype): x = torch.randn(1, 75, 57, 20, dtype=dtype, device=device).permute(0, 3, 1, 2) y = x.cpu() self.assertEqual(x.sum().cpu(), y.sum()) self.assertEqual(x.sum(dim=(-1, -2)).cpu(), y.sum(dim=(-1, -2))) self.assertEqual(x.sum(dim=(1, 3)).cpu(), y.sum(dim=(1, 3))) # TODO: update this to compare against NumPy instead of CPU @onlyCUDA def test_min_max_nan(self, device): tests = [(lambda x: x.min(), 'min'), (lambda x: x.max(), 'max'), (lambda x: x.amin(), 'amin'), (lambda x: x.amax(), 'amax'), (lambda x: x.min(0).values, 'min_dim'), (lambda x: x.max(0).values, 'max_dim'), (lambda x: x.amin(0), 'amin_dim'), (lambda x: x.amax(0), 'amax_dim')] for f, name in tests: a = torch.arange(25.0).view(5, 5) a[2, 2] = nan actual = f(a.to(device)).cpu() expected = f(a).cpu() self.assertEqual(torch.isnan(actual), torch.isnan(expected), msg=f'nans for {name}') self.assertEqual(actual[~torch.isnan(actual)], expected[~torch.isnan(expected)], msg=f'nans for {name}') # TODO: make this test generic using OpInfos @onlyCUDA def test_sum_cpu_device_mismatch(self, device): x = torch.randn(20, dtype=torch.float32, device=device) y = torch.randn(1, dtype=torch.float32) err_string = f"Expected out tensor to have device {device}, but got cpu instead" with self.assertRaisesRegex(RuntimeError, err_string): torch.sum(x, dim=[0], dtype=torch.float32, out=y) # tests half to float promotion if self.device_type == 'cuda': x = x.half() with self.assertRaisesRegex(RuntimeError, err_string): torch.sum(x, dim=[0], dtype=torch.float32, out=y) # Assert for illegal dtype would not be raised on XLA @onlyNativeDeviceTypes def test_minmax_illegal_dtype(self, device): x = torch.randn(5, 5, dtype=torch.float32, device=device) valid_values = torch.empty(5, dtype=torch.float32, device=device) valid_indices = torch.empty(5, dtype=torch.long, device=device) illegal_values = torch.empty(5, dtype=torch.int, device=device) illegal_indices = torch.empty(5, dtype=torch.double, device=device) torch.max(x, dim=0, out=(valid_values, valid_indices)) torch.min(x, dim=0, out=(valid_values, valid_indices)) torch.amax(x, dim=0, out=valid_values) torch.amin(x, dim=0, out=valid_values) rmsg = r'scalar type|dtype' with self.assertRaisesRegex(RuntimeError, rmsg): torch.max(x, dim=0, out=(illegal_values, valid_indices)) with self.assertRaisesRegex(RuntimeError, rmsg): torch.min(x, dim=0, out=(illegal_values, valid_indices)) with self.assertRaisesRegex(RuntimeError, rmsg): torch.max(x, dim=0, out=(valid_values, illegal_indices)) with self.assertRaisesRegex(RuntimeError, rmsg): torch.min(x, dim=0, out=(valid_values, illegal_indices)) with self.assertRaisesRegex(RuntimeError, rmsg): torch.max(x, dim=0, out=(illegal_values, illegal_indices)) with self.assertRaisesRegex(RuntimeError, rmsg): torch.min(x, dim=0, out=(illegal_values, illegal_indices)) @dtypes(*all_types_and(torch.half, torch.bfloat16)) def test_dim_arg_reduction_scalar(self, device, dtype): example = 4.0 x = torch.tensor(example, device=device, dtype=dtype) self.assertEqual(x.argmax().item(), 0) self.assertEqual(x.argmax(dim=None).item(), 0) self.assertEqual(x.argmax(dim=0).item(), 0) self.assertEqual(x.argmax(dim=0, keepdim=True), torch.tensor(0, dtype=torch.int64)) x = torch.tensor(example, device=device, dtype=dtype) self.assertEqual(x.argmin().item(), 0) self.assertEqual(x.argmin(dim=None).item(), 0) self.assertEqual(x.argmin(dim=0).item(), 0) self.assertEqual(x.argmin(dim=0, keepdim=True), torch.tensor(0, dtype=torch.int64)) @precisionOverride({torch.float16: 1e-2, torch.bfloat16: 1e-2}) @dtypes(*set(all_types_and(torch.half, torch.bfloat16)) - {torch.uint8}) def test_dim_reduction(self, device, dtype): example = [[-1, 2, 1], [5, 3, 6]] sum_dtype = { torch.bfloat16: torch.bfloat16, torch.double: torch.double, torch.float: torch.float, torch.half: torch.half, torch.int64: torch.int64, torch.int32: torch.int64, torch.int16: torch.int64, torch.int8: torch.int64 } # This won't test for 256bit instructions, since we usually # only work on 1 cacheline (512bit) at a time and these # examples aren't big enough to trigger that. x = torch.tensor(example, device=device, dtype=dtype) self.assertEqual(x.sum().item(), 16) self.assertEqual(x.sum(0), torch.tensor([4, 5, 7], dtype=sum_dtype[dtype])) self.assertEqual(x.sum(1), torch.tensor([2, 14], dtype=sum_dtype[dtype])) y = torch.tensor(example, device=device, dtype=sum_dtype[dtype]) torch.sum(x, 0, out=y) self.assertEqual(x.sum(0), y) # Mean not supported for Int types if dtype in [torch.float16, torch.bfloat16, torch.float32, torch.float64]: x = torch.tensor(example, device=device, dtype=dtype) self.assertEqual(x.mean().item(), 16.0 / 6) self.assertEqual(x.mean(0), torch.tensor([2.0, 2.5, 7.0 / 2], dtype=dtype)) self.assertEqual(x.mean(1), torch.tensor([2.0 / 3, 14.0 / 3], dtype=dtype)) self.assertEqual(x.mean(), x.mean((0, 1))) prod_dtype = { torch.bfloat16: torch.bfloat16, torch.double: torch.double, torch.float: torch.float, torch.float16: torch.float16, torch.int64: torch.int64, torch.int32: torch.int64, torch.int16: torch.int64, torch.int8: torch.int64, } # prod is not supported for float16 & bfloat16 on CPU if not (self.device_type == 'cpu' and dtype in [torch.float16, torch.bfloat16]): x = torch.tensor(example, device=device, dtype=dtype) self.assertEqual(x.prod().item(), -180) self.assertEqual(x.prod(0), torch.tensor([-5, 6, 6], dtype=prod_dtype[dtype])) self.assertEqual(x.prod(1), torch.tensor([-2, 90], dtype=prod_dtype[dtype])) x = torch.tensor(example, device=device, dtype=dtype) self.assertEqual(x.min().item(), -1) self.assertEqual(x.argmin().item(), 0) # TODO: torch.min does not support the same operation as argmin # for the same case, should we enable it? self.assertEqual(x.argmin(dim=None).item(), 0) self.assertEqual(x.min(0), (torch.tensor([-1, 2, 1], dtype=dtype), torch.tensor([0, 0, 0], dtype=torch.int64))) self.assertEqual(x.amin(0), torch.tensor([-1, 2, 1], dtype=dtype)) self.assertEqual(x.argmin(0), torch.tensor([0, 0, 0], dtype=torch.int64)) self.assertEqual(x.min(dim=0, keepdim=True), (torch.tensor([[-1, 2, 1]], dtype=dtype), torch.tensor([[0, 0, 0]], dtype=torch.int64))) self.assertEqual(x.amin(dim=0, keepdim=True), torch.tensor([[-1, 2, 1]], dtype=dtype)) self.assertEqual(x.argmin(dim=0, keepdim=True), torch.tensor([[0, 0, 0]], dtype=torch.int64)) self.assertEqual(x.min(1), (torch.tensor([-1, 3], dtype=dtype), torch.tensor([0, 1], dtype=torch.int64))) self.assertEqual(x.amin(1), torch.tensor([-1, 3], dtype=dtype)) self.assertEqual(x.argmin(1), torch.tensor([0, 1], dtype=torch.int64)) self.assertEqual(x.min(dim=1, keepdim=True), (torch.tensor([[-1], [3]], dtype=dtype), torch.tensor([[0], [1]], dtype=torch.int64))) self.assertEqual(x.amin(dim=1, keepdim=True), torch.tensor([[-1], [3]], dtype=dtype)) self.assertEqual(x.argmin(dim=1, keepdim=True), torch.tensor([[0], [1]], dtype=torch.int64)) # test that non-contiguous tensors work self.assertEqual(x[:, :2].min().item(), -1) self.assertEqual(x[:, :2].amin().item(), -1) self.assertEqual(x[:, :2].argmin().item(), 0) x = torch.tensor(example, device=device, dtype=dtype) self.assertEqual(x.max().item(), 6) self.assertEqual(x.amax().item(), 6) self.assertEqual(x.argmax().item(), 5) self.assertEqual(x.max(0), (torch.tensor([5, 3, 6], dtype=dtype), torch.tensor([1, 1, 1], dtype=torch.int64))) self.assertEqual(x.amax(0), torch.tensor([5, 3, 6], dtype=dtype)) self.assertEqual(x.argmax(dim=0), torch.tensor([1, 1, 1], dtype=torch.int64)) self.assertEqual(x.max(dim=0, keepdim=True), (torch.tensor([[5, 3, 6]], dtype=dtype), torch.tensor([[1, 1, 1]], dtype=torch.int64))) self.assertEqual(x.amax(dim=0, keepdim=True), torch.tensor([[5, 3, 6]], dtype=dtype)) self.assertEqual(x.argmax(dim=0, keepdim=True), torch.tensor([[1, 1, 1]], dtype=torch.int64)) self.assertEqual(x.max(1), (torch.tensor([2, 6], dtype=dtype), torch.tensor([1, 2], dtype=torch.int64))) self.assertEqual(x.amax(1), torch.tensor([2, 6], dtype=dtype)) self.assertEqual(x.argmax(dim=1), torch.tensor([1, 2], dtype=torch.int64)) self.assertEqual(x.max(1, keepdim=True), (torch.tensor([[2], [6]], dtype=dtype), torch.tensor([[1], [2]], dtype=torch.int64))) self.assertEqual(x.amax(1, keepdim=True), torch.tensor([[2], [6]], dtype=dtype)) self.assertEqual(x.argmax(dim=1, keepdim=True), torch.tensor([[1], [2]], dtype=torch.int64)) # test that non-contiguous tensors work self.assertEqual(x[:, :2].max().item(), 5) self.assertEqual(x[:, :2].amax().item(), 5) self.assertEqual(x[:, :2].argmax().item(), 2) @onlyCPU @dtypes(*integral_types_and(torch.bool)) def test_nanmean_integral_types(self, device, dtype): # List of tensor shapes to test shapes = [ (), (0,), (1,), (3, 4, 5), (2, 0, 3), (10, 10, 10), (2, 3, 0, 4), (100,), (1, 1, 1), (5, 5, 5, 5, 5), ] for shape in shapes: # Tensor of the specified shape and dtype t = make_tensor(shape, dtype=dtype, device=device) # Attempt to call torch.nanmean and expect a RuntimeError with self.assertRaisesRegex( RuntimeError, r"nanmean\(\): expected input to have floating point or complex dtype but got \w+" ): torch.nanmean(t) @precisionOverride({torch.float16: 1e-2, torch.bfloat16: 1e-2}) @dtypes(*set(all_types_and(torch.half, torch.bfloat16)) - {torch.uint8}) @parametrize("fn_name", [ "mean", "median", "nanmedian", "mode", "norm", "prod", "std", "sum", "var", "max", "min", "amax", "amin"]) def test_dim_reduction_fns(self, device, dtype, fn_name): def normfn_attr(t, dim, keepdim=False, out=None): attr = torch.norm return attr(t, 2, dim, keepdim, out=out) fn_attr = getattr(torch, fn_name) if fn_name != "norm" else normfn_attr def fn(x, dim, keepdim=False, out=None): ans = fn_attr(x, dim, keepdim=keepdim, out=out) return ans if not isinstance(ans, tuple) else ans[0] def fn_tuple(x, dim, keepdim=False, out=None): return fn_attr(x, dim, keepdim=keepdim, out=out) def test_multidim(x, dim): self.assertEqual(fn(x, dim).unsqueeze(dim), fn(x, dim, keepdim=True)) self.assertEqual(x.ndimension() - 1, fn(x, dim).ndimension()) self.assertEqual(x.ndimension(), fn(x, dim, keepdim=True).ndimension()) # general case x = torch.randn(3, 4, 5, device=device) dim = random.randint(0, 2) test_multidim(x, dim) # check 1-d behavior x = torch.randn(1, device=device) dim = 0 self.assertEqual(fn(x, dim).shape, ()) self.assertEqual(fn(x, dim, keepdim=True).shape, (1,)) # check reducing of a singleton dimension dims = [3, 4, 5] singleton_dim = random.randint(0, 2) dims[singleton_dim] = 1 x = torch.randn(dims, device=device) test_multidim(x, singleton_dim) # check reducing with output kwargs if fn_name in ['median', 'nanmedian', 'mode', 'max', 'min']: y = torch.randn(5, 3, device=device) values = torch.randn(5, 3, device=device) indices = torch.zeros(5, 3, device=device).long() - 1 fn_tuple(y, 1, keepdim=False, out=(values[:, 1], indices[:, 1])) values_expected, indices_expected = fn_tuple(y, 1, keepdim=False) self.assertEqual(values[:, 1], values_expected, msg=f'{fn_name} values with out= kwarg') self.assertEqual(indices[:, 1], indices_expected, msg=f'{fn_name} indices with out= kwarg') return x = torch.randn(5, 3, device=device) y = torch.randn(5, 3, device=device) fn(y, 1, keepdim=False, out=x[:, 1]) expected = fn(y, 1, keepdim=False) self.assertEqual(x[:, 1], expected, msg=f'{fn_name} with out= kwarg') @onlyCUDA @largeTensorTest('10GB') def test_reduction_split(self, device): # Test reduction when there is a 32bit-indexing split # https://github.com/pytorch/pytorch/issues/37583 input_ = torch.randn(5, 14400, 14400, device=device) result = input_.sum(dim=0) expect = input_[0] + input_[1] + input_[2] + input_[3] + input_[4] self.assertEqual(result, expect) @onlyCUDA @dtypes(torch.half, torch.float, torch.double, torch.bfloat16) def test_reduction_vectorize_along_input_corner(self, device, dtype): # 1D case: sum size = 1024 * 1024 * 64 + 3 shift = 1 x = torch.zeros(size, dtype=dtype, device=device) y = x[shift:] for i in range(100): x.zero_() x[i] = 1 self.assertEqual(x.sum(), 1.0) if i < shift: self.assertEqual(y.sum(), 0.0) else: self.assertEqual(y.sum(), 1.0) for i in range(1, 100): x.zero_() x[-i] = 1 self.assertEqual(x.sum(), 1.0) self.assertEqual(y.sum(), 1.0) # 1D case: argmax size = 1024 * 1024 * 64 + 3 shift = 1 ysize = size - shift x = torch.zeros(size, dtype=dtype, device=device) y = x[shift:] for i in range(100): x.zero_() x[i] = 1 self.assertEqual(x.argmax().item(), i) if i >= shift: self.assertEqual(y.argmax().item(), i - shift) for i in range(1, 100): x.zero_() x[-i] = 1 self.assertEqual(x.argmax().item(), size - i) self.assertEqual(y.argmax().item(), ysize - i) # 2D case: sum size = (7, 1024 * 1024 + 3) x = torch.zeros(size, dtype=dtype, device=device) for i in range(100): x.zero_() for j in range(7): x[j][i] = j xs = x.sum(dim=-1) for j in range(7): self.assertEqual(xs[j].item(), float(j)) for i in range(100): x.zero_() for j in range(7): x[j][-i] = j xs = x.sum(dim=-1) for j in range(7): self.assertEqual(xs[j].item(), float(j)) # 2D case: max/argmax size = (7, 1024 * 1024 + 3) x = torch.zeros(size, dtype=dtype, device=device) for i in range(100): x.zero_() for j in range(7): x[j][i] = j + 1 xs1 = x.argmax(dim=-1) xs2 = x.max(dim=-1).indices for j in range(7): self.assertEqual(xs1[j].item(), i) self.assertEqual(xs2[j].item(), i) for i in range(1, 100): x.zero_() for j in range(7): x[j][-i] = j + 1 xs1 = x.argmax(dim=-1) xs2 = x.max(dim=-1).indices for j in range(7): self.assertEqual(xs1[j].item(), size[1] - i) self.assertEqual(xs2[j].item(), size[1] - i) # 2D case: min/argmin size = (7, 1024 * 1024 + 3) x = torch.zeros(size, dtype=dtype, device=device) for i in range(100): x.zero_() for j in range(7): x[j][i] = -(j + 1) xs1 = x.argmin(dim=-1) xs2 = x.min(dim=-1).indices for j in range(7): self.assertEqual(xs1[j].item(), i) self.assertEqual(xs2[j].item(), i) for i in range(1, 100): x.zero_() for j in range(7): x[j][-i] = -(j + 1) xs1 = x.argmin(dim=-1) xs2 = x.min(dim=-1).indices for j in range(7): self.assertEqual(xs1[j].item(), size[1] - i) self.assertEqual(xs2[j].item(), size[1] - i) @onlyCUDA @dtypes(torch.half, torch.float, torch.double, torch.bfloat16) def test_reduction_vectorize_along_output(self, device, dtype): def run_test(input_): M, N = input_.shape input_.zero_() for i in range(min(M, N)): input_[i][i] = 1 output1 = input_.argmax(dim=0) output2 = input_.sum(dim=0) for i in range(min(M, N)): self.assertEqual(output1[i], i) self.assertEqual(output2[i], 1) # vec 4 run_test(torch.zeros(64, 64, dtype=dtype, device=device)) # vec 2 run_test(torch.zeros(64 * 64 + 2, dtype=dtype, device=device)[2:].view(64, 64)) run_test(torch.zeros(64, 62, dtype=dtype, device=device)) run_test(torch.zeros(64, 2, dtype=dtype, device=device)) # vec 1 run_test(torch.zeros(64 * 64 + 1, dtype=dtype, device=device)[1:].view(64, 64)) run_test(torch.zeros(64, 61, dtype=dtype, device=device)) run_test(torch.zeros(64, 1, dtype=dtype, device=device)) @onlyCUDA def test_argminmax_large_axis(self, device): # Regression test for gh-32863 x = torch.zeros(2**31, device=device, dtype=torch.int8) x[-1] = 1 self.assertEqual(x.argmax(0), x.shape[0] - 1) self.assertEqual(x.max(0).indices, x.shape[0] - 1) x[-1] = -1 self.assertEqual(x.argmin(0), x.shape[0] - 1) self.assertEqual(x.min(0).indices, x.shape[0] - 1) def test_argminmax_axis_with_dim_one(self, device): # See: https://github.com/pytorch/pytorch/issues/38922 n = 32768 x = torch.zeros(1, n) self.assertEqual(x.argmax(dim=0), torch.zeros(n, dtype=torch.int64)) self.assertEqual(x.argmin(dim=0), torch.zeros(n, dtype=torch.int64)) self.assertEqual(x.argmax(dim=-2), torch.zeros(n, dtype=torch.int64)) self.assertEqual(x.argmin(dim=-2), torch.zeros(n, dtype=torch.int64)) self.assertEqual(x.argmax(dim=0, keepdim=True), torch.zeros(1, n, dtype=torch.int64)) self.assertEqual(x.argmin(dim=0, keepdim=True), torch.zeros(1, n, dtype=torch.int64)) self.assertEqual(x.argmax(dim=-2, keepdim=True), torch.zeros(1, n, dtype=torch.int64)) self.assertEqual(x.argmin(dim=-2, keepdim=True), torch.zeros(1, n, dtype=torch.int64)) @dtypes(torch.int, torch.long, torch.float, torch.double) @dtypesIfCUDA(torch.int, torch.long, torch.half, torch.float, torch.double) def test_median_real_values(self, device, dtype): # Generate random 0-3D sizes sizes = [random.sample(range(1, 32), i) for i in range(4) for _ in range(2)] for size in sizes: # Create random input tensor t = torch.randn(size, device=device).type(dtype) t_numpy = t.cpu().numpy() res = t.median() self.assertEqual(res, t.nanmedian()) k = int((t.numel() - 1) / 2) self.assertEqual(res, t.view(-1).sort()[0][k]) if t.numel() % 2 == 1: # We can only test against numpy for odd reductions because numpy # returns the mean of the two medians and torch returns the lower self.assertEqual(res.cpu().numpy(), np.median(t_numpy)) for dim in range(t.ndim): res = t.median(dim, True) self.assertEqual(res, t.nanmedian(dim, True)) size = t.size(dim) if t.ndim > 0 else 1 k = int((size - 1) / 2) self.assertEqual(res[0], (t.sort(dim)[0]).select(dim, k).unsqueeze_(dim)) self.assertEqual(res[0], t.gather(dim, res[1])) if size % 2 == 1: # We can only test against numpy for odd reductions because numpy # returns the mean of the two medians and torch returns the lower self.assertEqual(res[0].cpu().numpy(), np.median(t_numpy, dim, keepdims=True), exact_dtype=False) @dtypes(torch.float, torch.double) @dtypesIfCUDA(torch.half, torch.float, torch.double) def test_median_nan_values(self, device, dtype): # Generate random 0-3D sizes sizes = [random.sample(range(1, 32), i) for i in range(4) for _ in range(2)] for size in sizes: # Create random input tensor with nan values t = torch.rand(size, device=device, dtype=dtype) t.masked_fill_(t < 0.1, float('nan')) t_numpy = t.cpu().numpy() for op in [torch.median, torch.nanmedian]: numpy_op = np.median if op == torch.median else np.nanmedian res = op(t) num_nan = t.isnan().sum() if op == torch.median and num_nan > 0: k = t.numel() - 1 else: k = int((t.numel() - num_nan - 1) / 2) self.assertEqual(res, t.view(-1).sort()[0][k]) if (t.numel() - num_nan) % 2 == 1: # We can only test against numpy for odd reductions because numpy # returns the mean of the two medians and torch returns the lower self.assertEqual(res.item(), numpy_op(t.cpu().numpy())) for dim in range(t.ndim): res = op(t, dim, True) size = t.size(dim) if t.ndim > 0 else 1 num_nan = t.isnan().sum(dim, True) if op == torch.median: k = torch.where(num_nan > 0, size - 1, int((size - 1) / 2)) else: k = ((size - num_nan - 1) / 2).type(torch.long) self.assertEqual(res[0], (t.sort(dim)[0]).gather(dim, k)) self.assertEqual(res[0], t.gather(dim, res[1])) # We can only test against numpy for odd reductions because numpy # returns the mean of the two medians and torch returns the lower mask = (size - num_nan) % 2 == 1 res = res[0].masked_select(mask).cpu() ref = numpy_op(t_numpy, dim, keepdims=True)[mask.cpu().numpy()] self.assertEqual(res, torch.from_numpy(ref)) def test_median_corner_cases(self, device): def check(op, a, args, key): t = torch.tensor(a, device=device) res = op(t, *args) if not args: key = torch.tensor(key, device=device) else: if len(key) == 1: key = torch.tensor(key[0], device=device) res = res[0] else: key = (torch.tensor(key[0], device=device), torch.tensor(key[1], device=device)) self.assertEqual(res, key) nan = float('nan') check(torch.median, nan, [], nan) check(torch.median, [], [], nan) check(torch.nanmedian, nan, [], nan) check(torch.median, nan, [0], [nan, 0]) check(torch.nanmedian, nan, [0], [nan, 0]) check(torch.median, [nan], [0, True], [[nan], [0]]) check(torch.nanmedian, [nan], [0, True], [[nan], [0]]) check(torch.median, [nan], [0, True], [[nan], [0]]) check(torch.nanmedian, [nan], [0, True], [[nan], [0]]) # Indices are not deterministic here so can only check values check(torch.median, [[nan, nan], [1, 2]], [0], [[nan, nan]]) check(torch.nanmedian, [[nan, nan], [1, 2]], [0], [[1, 2.]]) check(torch.median, [[nan, nan], [1, 2]], [1], [[nan, 1]]) check(torch.nanmedian, [[nan, nan], [1, 2]], [1], [[nan, 1.]]) # Discontiguous and strided tensors a = torch.arange(12, device=device) self.assertEqual(a[::2].median(), torch.tensor(4, device=device)) self.assertEqual(a[::2].nanmedian(), torch.tensor(4, device=device)) a.resize_(3, 4) self.assertEqual(a.T.median(), torch.tensor(5, device=device)) self.assertEqual(a.T.nanmedian(), torch.tensor(5, device=device)) self.assertEqual(a[::2, ::2].median(-1)[0], torch.tensor([0, 8], device=device)) self.assertEqual(a[::2, ::2].nanmedian(-1)[0], torch.tensor([0, 8], device=device)) a.resize_(2, 3, 2) self.assertEqual(a.T.median(), torch.tensor(5, device=device)) self.assertEqual(a.T.nanmedian(), torch.tensor(5, device=device)) self.assertEqual(a[:, ::2, :].median(-1)[0], torch.tensor([[0, 4], [6, 10]], device=device)) self.assertEqual(a[:, ::2, :].nanmedian(-1)[0], torch.tensor([[0, 4], [6, 10]], device=device)) @skipIfTorchDynamo("https://github.com/pytorch/pytorch/pull/138657 discovers a latent bug") @onlyNativeDeviceTypes @dtypes(torch.float, torch.double) def test_quantile(self, device, dtype): # Generate some random test cases ops = ['quantile', 'nanquantile'] inputs = [tuple(np.random.randint(2, 10, size=i)) for i in range(1, 4)] quantiles = [tuple(np.random.rand(i)) for i in range(5)] keepdims = [True, False] # Add corner cases inputs.extend([0.75, (1,), (1, 1), (1, 2, 1)]) inputs.extend([[float('nan')], [[float('nan'), float('nan')], [1, 2]]]) inputs.extend([[[float('nan'), float('nan')], [float('nan'), 2]]]) quantiles.extend([0.5, [0., 1.], np.random.rand(10)]) # Enumerate all input combinations for op, x, q, keepdim in product(ops, inputs, quantiles, keepdims): if type(x) is tuple: a = torch.randn(x, dtype=dtype, device=device) # Make some random elements NaN a.masked_fill_(torch.randint_like(a, 20) == 0, float('nan')) else: a = torch.tensor(x, dtype=dtype, device=device) q = torch.tensor(q, dtype=dtype, device=device) torch_op = getattr(torch, op) numpy_op = getattr(np, op) # Compute quantile along every dimension and flattened tensor interpolations = ('linear', 'lower', 'higher', 'midpoint', 'nearest') for interpolation, dim in product(interpolations, [None] + list(range(a.ndim))): result = torch_op(a, q, dim=dim, keepdim=keepdim, interpolation=interpolation) expected = numpy_op(a.cpu().numpy(), q.cpu().numpy(), dim, interpolation=interpolation, keepdims=keepdim) self.assertEqual(result.cpu(), torch.from_numpy(np.array(expected)).type(result.type())) # Test out variation out = torch.empty_like(result) torch_op(a, q, dim=dim, keepdim=keepdim, interpolation=interpolation, out=out) self.assertEqual(out.cpu(), result.cpu()) def test_quantile_backward(self, device): def check(a, q, dim, expected_grad, ops=(torch.quantile, torch.nanquantile)): for op in ops: t = torch.tensor(a, device=device, requires_grad=True) op(t, torch.tensor(q, device=device), dim).sum().backward() self.assertEqual(t.grad, expected_grad) check([1., 2, 3], 0.5, 0, [0, 1, 0]) check([1., 2, 3, 4], 0.5, 0, [0, 0.5, 0.5, 0]) check([3., 1, 4, 2], 0.5, 0, [0.5, 0, 0, 0.5]) check([1., 2, 3, 4], [0.25, 0.5, 0.75], 0, [0.25, 1.25, 1.25, 0.25]) check([[1., 2], [2, 1]], 0., 0, [[1, 0], [0, 1]]) check([[1., 2], [4, 3]], 1., 1, [[0, 1], [1, 0]]) check([1, float('nan'), 2], 0.5, 0, [0, 1, 0], [torch.quantile]) check([1, float('nan'), 2], 0.5, 0, [0.5, 0, 0.5], [torch.nanquantile]) def test_quantile_error(self, device): def check(a, q, args, kwargs, message): with self.assertRaisesRegex(RuntimeError, r'quantile\(\) ' + message): at = torch.tensor(a, device=device) qt = torch.tensor(q, device=device) if isinstance(q, list) else q torch.quantile(at, qt, *args, **kwargs) check([], 0.5, [], {}, r'input tensor must be non-empty') check([1.], [[1.]], [], {}, r'q must be a scalar or 1D tensor') check([1], 0.5, [], {}, r'input tensor must be either float or double dtype') check([1.], [1], [], {}, r'q tensor must be same dtype as the input tensor') check([1.], -1., [], {}, r'q must be in the range \[0, 1\] but got -1') check([1.], 1.1, [], {}, r'q must be in the range \[0, 1\] but got 1.1') check([1.], 0.5, [], {'out': torch.empty([], dtype=torch.int32, device=device)}, r'out tensor must be same dtype as the input tensor') check([1.], [1.], [None, False], {'interpolation': 'random_mode'}, r"interpolation must be one of linear, lower, higher, midpoint or nearest, but got random_mode") if self.device_type == "cpu": check([1.], [0.5, 1.1, -1], [], {}, r'q values must be in the range \[0, 1\]') if self.device_type == "cuda": with self.assertRaisesRegex( RuntimeError, r'quantile\(\) q tensor must be on the same device as the input tensor'): torch.randn(1, device=device).quantile(torch.tensor(0.5)) with self.assertRaisesRegex( RuntimeError, r'quantile\(\) out tensor must be on the same device as the input tensor'): torch.quantile(torch.randn(1, device=device), 0.5, out=torch.scalar_tensor(1)) def test_std_mean(self, device): x = torch.rand(100, 50, 20, device=device) for dim in range(x.dim()): for unbiased in [False, True]: for keepdim in [False, True]: std1, mean1 = torch.std_mean(x, dim=dim, unbiased=unbiased, keepdim=keepdim) std2 = x.std(dim=dim, unbiased=unbiased, keepdim=keepdim) mean2 = x.mean(dim=dim, keepdim=keepdim) self.assertEqual(std1, std2) self.assertEqual(mean1, mean2) def test_std_mean_all_dims(self, device): x = torch.rand(100, 50, 20, device=device) for unbiased in [False, True]: std1, mean1 = torch.std_mean(x, unbiased=unbiased) std2 = x.std(unbiased=unbiased) mean2 = x.mean() self.assertEqual(std1, std2) self.assertEqual(mean1, mean2) def test_var_mean(self, device): x = torch.rand(100, 300, 50, device=device) for dim in range(x.dim()): for unbiased in [False, True]: for keepdim in [False, True]: var1, mean1 = torch.var_mean(x, dim=dim, unbiased=unbiased, keepdim=keepdim) var2 = x.var(dim=dim, unbiased=unbiased, keepdim=keepdim) mean2 = x.mean(dim=dim, keepdim=keepdim) self.assertEqual(var1, var2) self.assertEqual(mean1, mean2) def test_var_mean_all_dims(self, device): x = torch.rand(100, 50, 20, device=device) for unbiased in [False, True]: var1, mean1 = torch.var_mean(x, unbiased=unbiased) var2 = x.var(unbiased=unbiased) mean2 = x.mean() self.assertEqual(var1, var2) self.assertEqual(mean1, mean2) def test_std_mean_some_dims(self, device): sizes = (4, 6, 7, 5, 3) dims = len(sizes) x = torch.rand(sizes, device=device) for num_of_dims in range(2, dims): dim_list = list(combinations(list(range(dims)), r=num_of_dims)) for dim in dim_list: for unbiased in [False, True]: for keepdim in [False, True]: std1, mean1 = torch.std_mean(x, dim=dim, unbiased=unbiased, keepdim=keepdim) std2 = x.std(dim=dim, unbiased=unbiased, keepdim=keepdim) mean2 = x.mean(dim=dim, keepdim=keepdim) self.assertEqual(std1, std2) self.assertEqual(mean1, mean2) def _compare_std_var_with_numpy(self, op, device, dtype, input, dim, keepdim, unbiased, use_out): a = input.cpu().numpy() if input.dtype is not torch.bfloat16 else input.float().cpu().numpy() numpy_kwargs = { 'axis' : dim, 'keepdims' : keepdim, 'ddof' : 1 if unbiased else 0, } if dim is None: del numpy_kwargs['axis'] del numpy_kwargs['keepdims'] if op == 'var': torch_op = torch.var numpy_op = np.var elif op == 'std': torch_op = torch.std numpy_op = np.std else: self.fail("Unknown op!") numpy_result = numpy_op(a, **numpy_kwargs) if dim is None and use_out is False: torch_result = torch_op(input, unbiased) elif dim is not None and use_out is False: torch_result = torch_op(input, dim, unbiased, keepdim) elif dim is not None and use_out is True: out = torch.empty(0, device=device, dtype=dtype) torch_result = torch_op(input, dim, unbiased, keepdim, out=out) else: out = torch.empty(0, device=device, dtype=dtype) torch_result = torch_op(input, dim, unbiased, keepdim, out=out) exact_dtype = input.dtype not in (torch.bfloat16, torch.complex32, torch.complex64, torch.complex128) self.assertEqual(torch_result, numpy_result, exact_dtype=exact_dtype) @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble) def test_var_vs_numpy(self, device, dtype): _size = (20, 20) for test_case in product((torch.randn(_size, device=device, dtype=dtype),), (None, 0, 1), (False, True), (False, True), (False, True),): self._compare_std_var_with_numpy('var', device, dtype, *test_case) @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble) def test_std_vs_numpy(self, device, dtype): _size = (20, 20) for test_case in product((torch.randn(_size, device=device, dtype=dtype),), (None, 0, 1), (False, True), (False, True), (False, True),): self._compare_std_var_with_numpy('std', device, dtype, *test_case) @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble) def test_var_correction_vs_numpy(self, device, dtype): _size = (20, 20) test_args = [ *product( # dim (None, 0, 1), # correction (None, 0, 10, 30), # keepdim (False, True), ), [None, -100, True], # Negative correction ] tensor = make_tensor(_size, device=device, dtype=dtype) array = tensor.cpu().numpy() for dim, correction, keepdim in test_args: numpy_kwargs = dict(axis=dim, ddof=correction, keepdims=keepdim) if correction is None: # NumPy default is not compatible with torch.std (gh-50010) numpy_kwargs['ddof'] = 1 numpy_res = np.asarray(np.var(array, **numpy_kwargs)) torch_res = torch.var(tensor, dim=dim, correction=correction, keepdim=keepdim) # inf vs. nan results are sensitive to machine precision, # just treat them as equivalent numpy_res[np.isinf(numpy_res)] = np.nan torch_res[torch_res.isinf()] = np.nan self.assertEqual(torch_res, numpy_res) @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble) def test_std_correction_vs_numpy(self, device, dtype): _size = (20, 20) test_args = [ *product( # dim (None, 0, 1), # correction (None, 0, 10, 30), # keepdim (False, True), ), [None, -100, True], # Negative correction ] tensor = make_tensor(_size, device=device, dtype=dtype) array = tensor.cpu().numpy() for dim, correction, keepdim in test_args: numpy_kwargs = dict(axis=dim, ddof=correction, keepdims=keepdim) if correction is None: # NumPy default is incompatible with torch.std (gh-50010) numpy_kwargs['ddof'] = 1 numpy_res = np.asarray(np.std(array, **numpy_kwargs)) torch_res = torch.std(tensor, dim=dim, correction=correction, keepdim=keepdim) # inf vs. nan results are sensitive to machine precision, # just treat them as equivalent numpy_res[np.isinf(numpy_res)] = np.nan torch_res[torch_res.isinf()] = np.nan self.assertEqual(torch_res, numpy_res) @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble) def test_std_mean_correction(self, device, dtype): _size = (20, 20) test_args = [ *product( # dim (None, 0, 1), # correction (None, 0, 10, 30), # keepdim (False, True), ), [None, -100, True], # Negative correction ] tensor = make_tensor(_size, device=device, dtype=dtype) for dim, correction, keepdim in test_args: kwargs = dict(dim=dim, correction=correction, keepdim=keepdim) std1 = torch.std(tensor, **kwargs) if dim is not None: mean1 = torch.mean(tensor, dim=dim, keepdim=keepdim) else: mean1 = torch.mean(tensor) if keepdim: mean1 = mean1.reshape((1,) * tensor.ndim) std2, mean2 = torch.std_mean(tensor, **kwargs) self.assertEqual(std1, std2) self.assertEqual(mean1, mean2) @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble) def test_var_mean_correction(self, device, dtype): _size = (20, 20) test_args = [ *product( # dim (None, 0, 1), # correction (None, 0, 10, 30), # keepdim (False, True), ), [None, -100, True], # Negative correction ] tensor = make_tensor(_size, device=device, dtype=dtype) for dim, correction, keepdim in test_args: kwargs = dict(dim=dim, correction=correction, keepdim=keepdim) var1 = torch.var(tensor, **kwargs) if dim is not None: mean1 = torch.mean(tensor, dim=dim, keepdim=keepdim) else: mean1 = torch.mean(tensor) if keepdim: mean1 = mean1.reshape((1,) * tensor.ndim) var2, mean2 = torch.var_mean(tensor, **kwargs) self.assertEqual(var1, var2) self.assertEqual(mean1, mean2) @dtypes(torch.float, torch.double, torch.cfloat, torch.cdouble) def test_warn_invalid_degrees_of_freedom(self, device, dtype): def _assert_warning(_func, _tensor, _correction): with warnings.catch_warnings(record=True) as w: _func(_tensor, dim=-1, correction=_correction) self.assertIn('degrees of freedom is <= 0', str(w[0].message)) correction = 20 size = (10, correction) tensor = make_tensor(size, dtype=dtype, device=device) for f in [torch.std, torch.var, torch.var_mean, torch.std_mean]: _assert_warning(f, tensor, correction) def test_amin_amax_some_dims(self, device): sizes = (4, 6, 7, 5, 3) dims = len(sizes) x = torch.rand(sizes, device=device) for num_of_dims in range(2, dims): dim_list = list(combinations(list(range(dims)), r=num_of_dims)) for dim in dim_list: for keepdim in [False, True]: amin1 = torch.amin(x, dim=dim, keepdim=keepdim) amax1 = torch.amax(x, dim=dim, keepdim=keepdim) amin2 = x amax2 = x for i, d in enumerate(dim): if not keepdim: d -= i amin2 = torch.amin(amin2, dim=d, keepdim=keepdim) amax2 = torch.amax(amax2, dim=d, keepdim=keepdim) self.assertEqual(amin1, amin2) self.assertEqual(amax1, amax2) def test_histc(self, device): # negative nbins throws with self.assertRaisesRegex(RuntimeError, 'bins must be > 0'): torch.histc(torch.tensor([1], dtype=torch.float, device=device), bins=-1) # empty tensor actual = torch.histc(torch.tensor([], device=device), min=0, max=3) expected = torch.zeros(100, dtype=torch.float, device=device) self.assertEqual(expected, actual) # without nbins actual = torch.histc( torch.tensor([2, 5], dtype=torch.float, device=device)) expected = torch.zeros(100, dtype=torch.float, device=device) expected[0] = 1 expected[99] = 1 self.assertEqual(expected, actual) # tensor with the same element actual = torch.histc(torch.ones(5, dtype=torch.float, device=device), bins=5) self.assertEqual( torch.tensor([0, 0, 5, 0, 0], dtype=torch.float, device=device), actual) # no element falls between [min, max] actual = torch.histc( torch.ones(5, dtype=torch.float, device=device), bins=5, min=2, max=3) self.assertEqual( torch.tensor([0, 0, 0, 0, 0], dtype=torch.float, device=device), actual) # element falls below min + integral bin size and actual = torch.histc( torch.tensor([2, 4, 2, 2, 5, 4], dtype=torch.float, device=device), bins=5, min=1, max=5) self.assertEqual( torch.tensor([0, 3, 0, 2, 1], dtype=torch.float, device=device), actual) # non-integral bin size actual = torch.histc( torch.tensor([1, 2, 1], dtype=torch.float, device=device), bins=4, min=0, max=3) self.assertEqual( torch.tensor([0, 2, 1, 0], dtype=torch.float, device=device), actual) # double input actual = torch.histc( torch.tensor([1, 2, 1], dtype=torch.double, device=device), bins=4, min=0, max=3) self.assertEqual( torch.tensor([0, 2, 1, 0], dtype=torch.double, device=device), actual) self.assertEqual(actual.dtype, torch.double) # mixed input actual = torch.histc( torch.tensor([1., 2, 1], dtype=torch.float, device=device), bins=4, min=0, max=3) self.assertEqual( torch.tensor([0, 2, 1, 0], dtype=torch.float, device=device), actual) self.assertEqual(actual.dtype, torch.float) # scalar input and 1 bin -- should return a 1-dimensional tensor, not a scalar. actual = torch.histc( torch.tensor(0, dtype=torch.float, device=device), bins=1, min=0, max=3) self.assertEqual( torch.tensor([1], dtype=torch.float, device=device), actual) # tensors with inf; min, max not provided -- should throw a RuntimeError with self.assertRaisesRegex(RuntimeError, r'range of \[[\w,+\-\.\ ]+\] is not finite'): torch.histc(torch.tensor([float("inf")], dtype=torch.float, device=device)) with self.assertRaisesRegex(RuntimeError, r'range of \[[\w,+\-\.\ ]+\] is not finite'): torch.histc(torch.tensor([float("-inf")], dtype=torch.float, device=device)) with self.assertRaisesRegex(RuntimeError, r'range of \[[\w,+\-\.\ ]+\] is not finite'): torch.histc(torch.tensor([float("-inf"), float("inf")], dtype=torch.float, device=device)) with self.assertRaisesRegex(RuntimeError, r'range of \[[\w,+\-\.\ ]+\] is not finite'): torch.histc(torch.tensor([1., 2., float("inf")], dtype=torch.float, device=device)) # tensors with inf; min, max provided self.assertEqual( torch.histc(torch.tensor([float("inf")], dtype=torch.float, device=device), bins=1, min=0, max=3), torch.tensor([0], dtype=torch.float, device=device)) self.assertEqual( torch.histc(torch.tensor([1., 2., float("inf")], dtype=torch.float, device=device), bins=4, max=3), torch.tensor([0, 1, 1, 0], dtype=torch.float, device=device)) # tensor with nan; min, max not provided -- should throw a RuntimeError with self.assertRaisesRegex(RuntimeError, r'range of \[nan, nan\] is not finite'): torch.histc(torch.tensor([float("nan")], dtype=torch.float, device=device)) # tensor with nan; min, max provided -- nan is ignored self.assertEqual( torch.histc(torch.tensor([1., 2., float("nan")], dtype=torch.float, device=device), bins=4, max=3), torch.tensor([0, 1, 1, 0], dtype=torch.float, device=device)) # tensors with min > max -- should throw a RuntimeError with self.assertRaisesRegex(RuntimeError, "max must be larger than min"): torch.histc(torch.tensor([1., 2., 3.], dtype=torch.float, device=device), bins=4, min=5, max=1) # test against numpy.histogram() def test_against_np(tensor, bins=100, min=0, max=0): if min == 0 and max == 0: min = tensor.min().item() max = tensor.max().item() nparr = tensor.cpu().numpy() actual = torch.histc(tensor, bins=bins, min=min, max=max) expected = torch.from_numpy(np.histogram(nparr, bins=bins, range=(min, max))[0]) actual_cpu = actual.cpu() # NB: Numpy returns a int64 tensor, like normal people... self.assertEqual(actual, expected.to(actual_cpu)) test_against_np(torch.tensor([1., 2, 1], device=device)) test_against_np(torch.randn(5000, device=device)) # Test bins arg test_against_np(torch.randn(301, device=device), bins=10) # Test truncated range test_against_np(torch.randn(201, device=device), min=0.1, max=1) noncontig = torch.randn(100, 3, device=device)[:, 2] test_against_np(noncontig) multidim = torch.randn(3, 5, 7, 2, device=device) test_against_np(multidim) expanded = torch.randn(1, 5, 1, 2, device=device).expand(3, 5, 7, 2) test_against_np(expanded) linear = torch.linspace(0, 0.99 - 5.0e-7, 101).to(device) test_against_np(linear, bins=20, min=0, max=0.99) @onlyCPU @dtypes(torch.bfloat16, torch.half) def test_histc_lowp(self, device, dtype): actual = torch.histc( torch.tensor([1, 2, 1], dtype=dtype, device=device), bins=4, min=0, max=3) self.assertEqual( torch.tensor([0, 2, 1, 0], dtype=dtype, device=device), actual) self.assertEqual(actual.dtype, dtype) @dtypes(torch.uint8, torch.int8, torch.int, torch.long, torch.float, torch.double) def test_histc_min_max_errors(self, device, dtype): with self.assertRaisesRegex(RuntimeError, "max must be larger than min"): torch.histc(torch.tensor([1., 2., 3.], dtype=dtype, device=device), bins=4, min=5, max=1) @dtypes(torch.float, torch.double) def test_histc_min_max_corner_cases(self, device, dtype): actual = torch.histc( torch.tensor([1., 2, 1], dtype=dtype, device=device), bins=4, min=5, max=5) self.assertEqual( torch.tensor([2, 0, 0, 1], dtype=dtype, device=device), actual) @onlyCPU @dtypes(torch.float, torch.double) def test_histc_value_corner_cases(self, device, dtype): min_val = torch.finfo(dtype).min actual = torch.histc( torch.tensor([min_val, min_val, min_val], dtype=dtype, device=device), bins=4) self.assertEqual(3.0, actual.sum()) max_val = torch.finfo(dtype).max actual = torch.histc( torch.tensor([max_val, max_val, max_val], dtype=dtype, device=device), bins=4) self.assertEqual(3.0, actual.sum()) @onlyCUDA @dtypes(torch.uint8, torch.int8, torch.int, torch.long) def test_histc_min_max_corner_cases_cuda(self, device, dtype): actual = torch.histc( torch.tensor([1., 2, 1], dtype=dtype, device=device), bins=4, min=5, max=5) self.assertEqual( torch.tensor([2, 0, 0, 1], dtype=dtype, device=device), actual) """ Runs torch.histogram and numpy.histogram on the specified input parameters and asserts that their output is equal. """ def _test_histogram_numpy(self, t, bins, bin_range, weights, density, eq_func=None): def to_np(t): if not torch.is_tensor(t): return t return t.cpu().numpy() # Wrapper around numpy.histogram performing conversions between torch tensors and numpy arrays. def reference_histogram(t, bins, bin_range, weights, density, dtype): np_t, np_bins, np_weights = map(to_np, [t, bins, weights]) np_hist, np_bin_edges = np.histogram( np_t, np_bins, range=bin_range, weights=np_weights, density=density ) return ( torch.from_numpy(np_hist).to(dtype), torch.from_numpy(np_bin_edges).to(dtype), ) if eq_func is None: eq_func = self.assertEqual # Doesn't pass a 'range' kwarg unless necessary because the override of # histogram with Tensor bins doesn't accept one. if bin_range: actual_hist, actual_bin_edges = torch.histogram( t, bins, range=bin_range, weight=weights, density=density ) else: actual_hist, actual_bin_edges = torch.histogram( t, bins, weight=weights, density=density ) expected_hist, expected_bin_edges = reference_histogram( t, bins, bin_range, weights, density, actual_hist.dtype ) """ Works around linspace discrepancies by passing torch's constructed bin_edges to numpy. When bin edges are not explicitly defined, histogram uses the linspace operator internally to construct the sequence of bin edges. In some cases, torch.linspace output differs slightly from numpy.linspace output. Issue: https://github.com/pytorch/pytorch/issues/58758 """ if not torch.is_tensor(bins): eq_func(actual_bin_edges, expected_bin_edges, atol=1e-5, rtol=1e-5) # Calls numpy.histogram again, passing torch's actual_bin_edges as the bins # argument. expected_hist, expected_bin_edges = reference_histogram( t, actual_bin_edges, bin_range, weights, density, actual_hist.dtype, ) eq_func(actual_hist, expected_hist) eq_func(actual_bin_edges, expected_bin_edges) # Test passing non-contiguous output tensors hist_out = make_tensor( expected_hist.shape, device=expected_hist.device, dtype=expected_hist.dtype, noncontiguous=True, ) bin_edges_out = make_tensor( expected_bin_edges.shape, device=expected_bin_edges.device, dtype=expected_bin_edges.dtype, noncontiguous=True, ) # Doesn't pass a 'range' kwarg unless necessary because the override of # histogram with Tensor bins doesn't accept one. if bin_range: torch.histogram( t, bins, range=bin_range, weight=weights, density=density, out=(hist_out, bin_edges_out), ) else: torch.histogram( t, bins, weight=weights, density=density, out=(hist_out, bin_edges_out) ) eq_func(hist_out, expected_hist) eq_func(bin_edges_out, expected_bin_edges) @onlyCPU @dtypes(torch.float32) def test_histogram(self, device, dtype): shapes = ( (), (0,), (1,), (1, 5), (3, 5), (1, 5, 1), (2, 3, 5)) for contig, bins_contig, bin_ct, weighted, density, shape in \ product([True, False], [True, False], range(1, 10), [True, False], [True, False], shapes): values = make_tensor(shape, dtype=dtype, device=device, low=-9, high=9, noncontiguous=not contig) weights = make_tensor(shape, dtype=dtype, device=device, low=0, high=9, noncontiguous=not contig) if weighted else None # Tests passing just the bin_ct self._test_histogram_numpy(values, bin_ct, None, weights, density) # Tests with caller-specified histogram range bin_range = sorted((random.uniform(-9, 9), random.uniform(-9, 9))) self._test_histogram_numpy(values, bin_ct, bin_range, weights, density) # Tests with range min=max bin_range[1] = bin_range[0] self._test_histogram_numpy( values, bin_ct, bin_range, weights, density, # TODO: investigate why torch.histogram differs from numpy.histogram # so strongly on this particular test. There seems to be more # differences here than the linspace issue, which is itself fairly # easily patched around. Likely, the other tests also differ # significantly, but below the default threshold for assertEqual. eq_func=partial(self.assertEqual, rtol=3e-5, atol=0.0), ) # Tests with caller-specified bin edges bin_edges = make_tensor(bin_ct + 1, dtype=dtype, device=device, low=-9, high=9).msort() if not bins_contig: # Necessary because msort always produces contiguous output bin_edges_noncontig = make_tensor(bin_ct + 1, dtype=dtype, device=device, noncontiguous=not bins_contig) bin_edges_noncontig.copy_(bin_edges) bin_edges = bin_edges_noncontig self.assertEqual(bin_edges.is_contiguous(), bins_contig) self._test_histogram_numpy(values, bin_edges, None, weights, density) # Tests with input tensor in which all elements are equal elt = random.uniform(-9, 9) values = make_tensor(shape, dtype=dtype, device=device, low=elt, high=elt, noncontiguous=not contig) self._test_histogram_numpy(values, bin_ct, bin_range, weights, density) self._test_histogram_numpy(values, bin_edges, None, weights, density) # Tests with input equal to bin_edges weights = ( make_tensor(bin_ct + 1, dtype=dtype, device=device, low=0, high=9, noncontiguous=not contig) if weighted else None ) self._test_histogram_numpy(bin_edges, bin_edges, None, weights, density) # Tests values of default args for bin_ct, shape in product(range(1, 10), shapes): values = make_tensor(shape, dtype=dtype, device=device, low=-9, high=9) (actual_hist, actual_bin_edges) = torch.histogram(values, bin_ct) (expected_hist, expected_bin_edges) = torch.histogram( values, bin_ct, range=None, weight=None, density=False) self.assertEqual(actual_hist, expected_hist) self.assertEqual(actual_bin_edges, expected_bin_edges) """ Runs torch.histogramdd and numpy.histogramdd on the specified input parameters and asserts that their output is equal. """ def _test_histogramdd_numpy(self, t, bins, bin_range, weights, density): def to_np(t): if type(t) is list: return list(map(to_np, t)) if not torch.is_tensor(t): return t return t.cpu().numpy() # Wrapper around numpy.histogram performing conversions between torch tensors and numpy arrays. def reference_histogramdd(t, bins, bin_range, weights, density, dtype): (np_t, np_bins, np_weights) = map(to_np, [t, bins, weights]) # numpy.histogramdd accepts only (N, D) shapes D = np_t.shape[-1] N = np.prod(np_t.shape[:-1]) reshaped_t = np.reshape(np_t, (N, D)) reshaped_wt = np.reshape(np_weights, (N,)) if np_weights is not None else None # numpy.histogramdd throws an error for D=0 if D == 0: return (torch.tensor(float('nan') if density else 0.), []) # numpy.histogramdd expects range to be specified as a sequence of D (lower, upper) tuples reshaped_range = None if not bin_range else [(bin_range[2 * i], bin_range[2 * i + 1]) for i in range(D)] (np_hist, np_bin_edges) = np.histogramdd(reshaped_t, np_bins, range=reshaped_range, weights=reshaped_wt, density=density) return (torch.from_numpy(np_hist).to(dtype), [torch.from_numpy(t).to(dtype) for t in np_bin_edges]) (actual_hist, actual_bin_edges) = torch.histogramdd(t, bins, range=bin_range, weight=weights, density=density) (expected_hist, expected_bin_edges) = reference_histogramdd(t, bins, bin_range, weights, density, actual_hist.dtype) D = len(actual_bin_edges) self.assertEqual(D, len(expected_bin_edges)) """ Works around linspace discrepancies by passing torch's constructed bin_edges to numpy. When bin edges are not explicitly defined, histogram uses the linspace operator internally to construct the sequence of bin edges. In some cases, torch.linspace output differs slightly from numpy.linspace output. Issue: https://github.com/pytorch/pytorch/issues/58758 """ if not torch.is_tensor(bins): for dim in range(D): self.assertEqual(actual_bin_edges[dim], expected_bin_edges[dim], atol=1e-5, rtol=1e-5) # Calls numpy.histogram again, passing torch's actual_bin_edges as the bins argument (expected_hist, expected_bin_edges) = reference_histogramdd( t, actual_bin_edges, bin_range, weights, density, actual_hist.dtype) self.assertEqual(D, len(expected_bin_edges)) self.assertEqual(actual_hist, expected_hist) for dim in range(D): self.assertEqual(actual_bin_edges[dim], expected_bin_edges[dim]) @onlyCPU @dtypes(torch.float32) def test_histogramdd(self, device, dtype): shapes = ( (1, 5), (3, 5), (1, 5, 1), (2, 3, 5), (7, 7, 7, 7), (16, 8, 4, 2), (10, 10, 10), (7, 0, 3), (5, 0),) for contig, bins_contig, weighted, density, shape in \ product([True, False], [True, False], [True, False], [True, False], shapes): D = shape[-1] values = make_tensor(shape, dtype=dtype, device=device, low=-9, high=9, noncontiguous=not contig) weights = ( make_tensor(shape[:-1], dtype=dtype, device=device, low=0, high=9, noncontiguous=not contig) if weighted else None ) # Tests passing a single bin count bin_ct = random.randint(1, 5) self._test_histogramdd_numpy(values, bin_ct, None, weights, density) # Tests passing a bin count for each dimension bin_ct = [random.randint(1, 5) for dim in range(D)] self._test_histogramdd_numpy(values, bin_ct, None, weights, density) # Tests with caller-specified histogram range bin_range_tuples = [sorted((random.uniform(-9, 9), random.uniform(-9, 9))) for dim in range(D)] bin_range = [elt for t in bin_range_tuples for elt in t] self._test_histogramdd_numpy(values, bin_ct, bin_range, weights, density) # Tests with range min=max for dim in range(D): bin_range[2 * dim + 1] = bin_range[2 * dim] self._test_histogramdd_numpy(values, bin_ct, bin_range, weights, density) # Tests with caller-specified bin edges bin_edges = [make_tensor(ct + 1, dtype=dtype, device=device, low=-9, high=9).msort() for ct in bin_ct] if not bins_contig: # Necessary because msort always produces contiguous output bin_edges_noncontig = [ make_tensor(ct + 1, dtype=dtype, device=device, noncontiguous=not bins_contig) for ct in bin_ct ] for dim in range(D): bin_edges_noncontig[dim].copy_(bin_edges[dim]) bin_edges = bin_edges_noncontig for dim in range(D): self.assertEqual(bin_edges[dim].is_contiguous(), bins_contig) self._test_histogramdd_numpy(values, bin_edges, None, weights, density) @onlyCPU @dtypes(torch.float32) def test_histogram_error_handling(self, device, dtype): with self.assertRaisesRegex(RuntimeError, 'not implemented for'): values = make_tensor((), dtype=torch.int32, device=device) torch.histogram(values, 1) inconsistent_dtype = torch.float32 if dtype != torch.float32 else torch.float64 with self.assertRaisesRegex(RuntimeError, 'input tensor and bins tensors should have the same dtype'): values = make_tensor((), dtype=dtype, device=device) bins = make_tensor((), dtype=inconsistent_dtype, device=device) torch.histogram(values, bins) with self.assertRaisesRegex(RuntimeError, 'input tensor and weight tensor should have the same dtype'): values = make_tensor((), dtype=dtype, device=device) weight = make_tensor((), dtype=inconsistent_dtype, device=device) torch.histogram(values, 1, weight=weight) with self.assertRaisesRegex(RuntimeError, 'input tensor and hist tensor should have the same dtype'): values = make_tensor((), dtype=dtype, device=device) hist = make_tensor((), dtype=inconsistent_dtype, device=device) bin_edges = make_tensor((), dtype=dtype, device=device) torch.histogram(values, 1, out=(hist, bin_edges)) with self.assertRaisesRegex(RuntimeError, 'input tensor and bin_edges tensor should have the same dtype'): values = make_tensor((), dtype=dtype, device=device) hist = make_tensor((), dtype=dtype, device=device) bin_edges = make_tensor((), dtype=inconsistent_dtype, device=device) torch.histogram(values, 1, out=(hist, bin_edges)) with self.assertRaisesRegex(RuntimeError, 'bins tensor should have one dimension'): t = make_tensor((2, 2), dtype=dtype, device=device) torch.histogram(t, t) with self.assertRaisesRegex(RuntimeError, 'bins tensor should have at least 1 element'): t = make_tensor((0), dtype=dtype, device=device) torch.histogram(t, t) with self.assertRaisesRegex(RuntimeError, 'bins must be > 0'): values = make_tensor((), dtype=dtype, device=device) torch.histogram(values, -1) with self.assertRaisesRegex(RuntimeError, 'if weight tensor is provided it should have the same shape \ as the input tensor excluding its innermost dimension'): values = make_tensor((2, 2), dtype=dtype, device=device) weight = make_tensor((1), dtype=dtype, device=device) torch.histogram(values, 1, weight=weight) with self.assertRaisesRegex(TypeError, 'received an invalid combination of arguments'): values = make_tensor((), dtype=dtype, device=device) bin_edges = make_tensor((), dtype=dtype, device=device) torch.histogram(values, bin_edges, range=(0, 1)) with self.assertRaisesRegex(RuntimeError, 'min should not exceed max'): values = make_tensor((), dtype=dtype, device=device) torch.histogram(values, 2, range=(1, 0)) with self.assertRaisesRegex(RuntimeError, r'range \[nan, nan\] is not finite'): values = torch.tensor([float("nan")], device=device, dtype=dtype) torch.histogram(values, 2) # Tests to ensure that reduction functions employing comparison operators are usable when there # exists a zero dimension (i.e. when the tensors are empty) in the tensor. These tests specifically # cater to functions where specifying the `dim` parameter is necessary. def test_tensor_compare_ops_empty(self, device): shape = (2, 0, 4) master_input = torch.randn(shape, device=device) np_input = np.empty(shape) test_functions = [ ('amax', torch.amax, np.amax), ('amin', torch.amin, np.amin), ('max', lambda *args, **kwargs: torch.max(*args, **kwargs).values, np.max), ('min', lambda *args, **kwargs: torch.min(*args, **kwargs).values, np.min), ('median', lambda *args, **kwargs: torch.median(*args, **kwargs).values, np.median), ] for name, fn, np_function in test_functions: # Check if reduction happens along the specified dim with and without keepdim. Check with # numpy to maintain compatibility with numpy functions. error_msg = f"test function: {name}" self.assertEqual(torch.empty((2, 0), device=device), fn(master_input, dim=2), msg=error_msg) self.assertEqual(np_function(np_input, axis=2), fn(master_input, dim=2).cpu().numpy(), msg=error_msg, exact_dtype=False) self.assertEqual(torch.empty((2, 0), device=device), fn(master_input, dim=-1), msg=error_msg) self.assertEqual(np_function(np_input, axis=-1), fn(master_input, dim=-1).cpu().numpy(), msg=error_msg, exact_dtype=False) self.assertEqual(torch.empty((2, 0, 1), device=device), fn(master_input, dim=2, keepdim=True), msg=error_msg) self.assertEqual(np_function(np_input, axis=2, keepdims=True), fn(master_input, dim=2, keepdim=True).cpu().numpy(), msg=error_msg, exact_dtype=False) self.assertEqual(torch.empty((2, 0, 1), device=device), fn(master_input, dim=-1, keepdim=True), msg=error_msg) self.assertEqual(np_function(np_input, axis=-1, keepdims=True), fn(master_input, dim=-1, keepdim=True).cpu().numpy(), msg=error_msg, exact_dtype=False) # Check if function raises error on specified zero'd dimension as reduction dim. self.assertRaisesRegex(IndexError, "Expected reduction dim", lambda: fn(master_input, dim=1)) # Tests to ensure that reduction of zero-dim tensors (i.e. empty tensors) using comparison operators # raises an error if no `dim` parameter is specified. This exists separately from tests in # test_tensot_compare_ops_empty because not specifying a `dim` parameter in the former tests does # not throw errors. Also, checking the return type of argmax requires supplying a different dtype # argument than that for the input tensor. There is also variation in numpy testing. def test_tensor_compare_ops_argmax_argmix_kthvalue_dim_empty(self, device): shape = (2, 0, 4) master_input = torch.randn(shape, device=device) np_input = np.empty(shape) test_functions = [ ('argmax', torch.argmax, {'dtype': torch.int64}, np.argmax), ('argmin', torch.argmin, {'dtype': torch.int64}, np.argmin), ('kthvalue', lambda *args, k=1, **kwargs: torch.kthvalue(*args, k=1, **kwargs).values, {}, lambda *args, k=1, axis=None, **kwargs: np.partition(*args, k, **kwargs).take(k - 1, axis=axis)) ] for name, fn, dtype, np_function in test_functions: error_msg = f"test function: {name}" self.assertEqual(torch.empty((2, 0), device=device, **dtype), fn(master_input, dim=2), msg=error_msg) self.assertEqual( np_function(np_input, axis=2), fn(master_input, dim=2).cpu().numpy(), msg=error_msg, exact_dtype=False ) self.assertEqual(torch.empty((2, 0), device=device, **dtype), fn(master_input, dim=-1), msg=error_msg) self.assertEqual( np_function(np_input, axis=-1), fn(master_input, dim=-1).cpu().numpy(), msg=error_msg, exact_dtype=False ) # keepdim variant does not exist for numpy self.assertEqual(torch.empty((2, 0, 1), device=device, **dtype), fn(master_input, dim=2, keepdim=True), msg=error_msg) self.assertEqual(torch.empty((2, 0, 1), device=device, **dtype), fn(master_input, dim=-1, keepdim=True), msg=error_msg) # Check if function raises error on specified zero'd dimension as reduction dim. self.assertRaisesRegex(IndexError, "Expected reduction dim", lambda: fn(master_input, dim=1)) if name != 'kthvalue': self.assertRaisesRegex(IndexError, "Expected reduction dim", lambda: fn(master_input)) # Tests to ensure that reduction of zero-dim tensors (i.e. empty tensors) using math operators works when a # non-zero dim is specified for the reduction and throws an error when the dim specified is 0. Although # there is some repetition with test_tensor_compare_ops_optional_dim_empty and test_tensor_compare_ops_empty, # these tests are kept separate since tests for math operators also require checking for correctness of the # returned data using allclose() or isinf() which does not exists in the former tests. @skipIfNoSciPy def test_tensor_reduce_ops_empty(self, device): from scipy.special import logsumexp shape = (2, 0, 4) master_input = torch.randn(shape, device=device) np_input = np.empty(shape) test_functions = [ ('prod', torch.prod, 1., np.prod), ('sum', torch.sum, 0., np.sum), ('norm', torch.norm, 0., np.linalg.norm), ('mean', torch.mean, nan, np.mean), ('var', torch.var, nan, np.var), ('std', torch.std, nan, np.std), ('logsumexp', torch.logsumexp, -inf, logsumexp), ] for name, fn, return_value, np_function in test_functions: # Check if reduction happens along the specified dimension. error_msg = f"test function: {name}" self.assertEqual(torch.empty((2, 0), device=device), fn(master_input, dim=2), msg=error_msg) self.assertEqual(np_function(np_input, axis=2), fn(master_input, dim=2).cpu().numpy(), msg=error_msg, exact_dtype=False) self.assertEqual(torch.empty((2, 0), device=device), fn(master_input, dim=-1), msg=error_msg) self.assertEqual(np_function(np_input, axis=-1), fn(master_input, dim=-1).cpu().numpy(), msg=error_msg, exact_dtype=False) self.assertEqual(torch.empty((2, 0, 1), device=device), fn(master_input, dim=2, keepdim=True), msg=error_msg) self.assertEqual(np_function(np_input, axis=2, keepdims=True), fn(master_input, dim=2, keepdim=True), msg=error_msg, exact_dtype=False) self.assertEqual(torch.empty((2, 0, 1), device=device), fn(master_input, dim=-1, keepdim=True), msg=error_msg) self.assertEqual(np_function(np_input, axis=-1, keepdims=True), fn(master_input, dim=-1, keepdim=True), msg=error_msg, exact_dtype=False) self.assertEqual(torch.full((2, 4), return_value, device=device), fn(master_input, dim=1), msg=error_msg) self.assertEqual(torch.full((2, 4), return_value, device=device), fn(master_input, dim=-2), msg=error_msg) self.assertEqual(torch.full((2, 1, 4), return_value, device=device), fn(master_input, dim=1, keepdim=True), msg=error_msg) self.assertEqual(torch.full((2, 1, 4), return_value, device=device), fn(master_input, dim=-2, keepdim=True), msg=error_msg) if name != 'logsumexp': # The scipy function does not work for reduction the zero dimension self.assertEqual(np.float32(np_function(np_input, axis=1)), fn(master_input, dim=1).cpu().numpy(), msg=error_msg) self.assertEqual(np.float32(np_function(np_input, axis=-2)), fn(master_input, dim=-2).cpu().numpy(), msg=error_msg) self.assertEqual(np.float32(np_function(np_input, axis=1, keepdims=True)), fn(master_input, dim=1, keepdim=True).cpu().numpy(), msg=error_msg) self.assertEqual(np.float32(np_function(np_input, axis=-2, keepdims=True)), fn(master_input, dim=-2, keepdim=True).cpu().numpy(), msg=error_msg) # logsumexp throws a type error when not specifying dim so test separately. self.assertEqual(torch.full((), return_value, device=device), fn(master_input), msg=error_msg) else: self.assertRaises(TypeError, lambda: fn(master_input)) # Tests to ensure that any() and all() functions work with zero-dim tensors. Kept separate from # other tests for checking reduction with zero-dim tensors because these tests have significantly # different testing behaviour than that used for the former tests. def test_reduction_empty_any_all(self, device): shape = (2, 0, 4) x = torch.randn(shape, device=device) for dtype in all_types_and_complex_and(torch.half, torch.bool): # Refer: [all, any uint8 compatibility] if dtype == torch.uint8: out_dtype = torch.uint8 else: out_dtype = torch.bool # output of all/any is bool irrespective of input dtype xb = x.to(dtype) # any self.assertEqual((2, 0), xb.any(2).shape) self.assertEqual((2, 0, 1), xb.any(2, keepdim=True).shape) self.assertEqual(torch.zeros((2, 4), device=device, dtype=out_dtype), xb.any(1)) self.assertEqual(torch.zeros((2, 1, 4), device=device, dtype=out_dtype), xb.any(1, keepdim=True)) self.assertEqual(torch.zeros((), device=device, dtype=out_dtype), xb.any()) # all self.assertEqual((2, 0), xb.all(2).shape) self.assertEqual((2, 0, 1), xb.all(2, keepdim=True).shape) self.assertEqual(torch.ones((2, 4), device=device, dtype=out_dtype), xb.all(1)) self.assertEqual(torch.ones((2, 1, 4), device=device, dtype=out_dtype), xb.all(1, keepdim=True)) self.assertEqual(torch.ones((), device=device, dtype=out_dtype), xb.all()) # TODO: can these be merged with their respective OpInfos? def test_reduce_dtype(self, device): def test_reduction(op, has_no_dim, takes_dtype=True): x = torch.randn(3, 3, dtype=torch.float, requires_grad=True, device=device) if has_no_dim: grad1, = torch.autograd.grad([op(x)], [x]) grad2, = torch.autograd.grad([op(x, dtype=torch.double)], [x]) self.assertEqual(grad1, grad2) self.assertEqual(grad2.dtype, torch.float) gi = torch.randn(op(x, dim=0).shape, dtype=torch.float, device=device) grad1, = torch.autograd.grad([op(x, dim=0)], [x], gi) if takes_dtype: grad2, = torch.autograd.grad([op(x, dim=0, dtype=torch.double)], [x], gi.double()) else: grad2, = torch.autograd.grad([op(x.double(), dim=0)], [x], gi.double()) self.assertEqual(grad1, grad2) self.assertEqual(grad2.dtype, torch.float) test_reduction(torch.sum, True) test_reduction(torch.prod, True) test_reduction(torch.cumsum, False) test_reduction(torch.cumprod, False) test_reduction(torch.logcumsumexp, False, takes_dtype=False) @ops(reference_masked_ops) def test_reference_masked(self, device, dtype, op): """Test masked reduction operations on strided-only tensors using numpy reductions as reference. """ def to_numpy(input): if input.dtype is torch.bfloat16: return input.cpu().to(torch.float32).numpy() else: return input.cpu().numpy() samples = op.sample_inputs_func(op, device, dtype, requires_grad=False) for sample_input in samples: t = sample_input.input actual = op(t, *sample_input.args, **sample_input.kwargs) exact_dtype = not (t.dtype is torch.bfloat16 or (op.promotes_int_to_float and not torch.is_floating_point(t))) expected = op.ref(to_numpy(t), *sample_input.args, **dict( # `identity` is mapped to numpy reduction `initial` argument identity=torch.masked._reduction_identity(op.name, t), **sample_input.kwargs)) # Workaround https://github.com/pytorch/pytorch/issues/66556 expected = np.asarray(expected) # transform numpy scalars to numpy.ndarray instances # Numpy differs, producing uint32 on Windows if expected.dtype in [np.uint64, np.uint32]: exact_dtype = False msg = ("Failed to produce expected results! Input tensor was" f" {t}, torch result is {actual}, and reference result is" f" {expected}.") if t.numel() < 10 else None self.assertEqual(actual, expected, msg, exact_dtype=exact_dtype) @onlyCUDA @largeTensorTest("8GB") @dtypes(torch.half, torch.chalf, torch.bfloat16) def test_reductions_large_half_tensors(self, device, dtype): t = torch.ones(2**31, device=device, dtype=dtype) t[2**30:] = -1 expected = torch.tensor(0, device=device, dtype=dtype) self.assertEqual(torch.sum(t), expected) # mean_cuda is not implemented for ComplexHalf err_msg = "not implemented for 'ComplexHalf'" ctx = self.assertRaisesRegex( RuntimeError, err_msg) if dtype is torch.chalf else contextlib.nullcontext() with ctx: self.assertEqual(torch.mean(t), expected) def test_scalar_tensor_as_dim_argument(self): """Tests that scalar tensors work correctly as dimension arguments. This tests the fix for the PythonArgParser bug where scalar Tensors passed to IntList/SymIntList parameters would be incorrectly handled. """ x = torch.ones(1, 2, 3, 4, 5) # Scalar tensors should work correctly (same as passing an int) result_tensor = x.sum(dim=torch.tensor(3)) result_int = x.sum(dim=3) self.assertEqual(result_tensor.shape, result_int.shape) self.assertEqual(result_tensor.shape, torch.Size([1, 2, 3, 5])) # Test with different integer dtypes for dtype in [torch.int32, torch.int64, torch.int16, torch.int8]: dim_tensor = torch.tensor(1, dtype=dtype) result = x.sum(dim=dim_tensor) expected = x.sum(dim=1) self.assertEqual(result.shape, expected.shape) @skipIfTorchDynamo("Test uses random.randint which creates FakeTensors") def test_scalar_tensor_dim_compiled_mode(self): """Tests that scalar FakeTensors from random.randint work correctly in compiled mode.""" def foo(): x = torch.ones(2, 2, 2) return x.sum(dim=random.randint(0, 0)) @torch.compile def foo_compile(): x = torch.ones(2, 2, 2) return x.sum(dim=random.randint(0, 0)) result_eager = foo() result_compiled = foo_compile() self.assertEqual(result_eager.shape, result_compiled.shape) self.assertEqual(result_eager.shape, torch.Size([2, 2])) instantiate_device_type_tests(TestReductions, globals()) if __name__ == '__main__': run_tests()
TestReductions
python
google__jax
jax/_src/checkify.py
{ "start": 4448, "end": 4905 }
class ____(JaxException): def __init__(self, traceback_info, primitive_name): super().__init__(traceback_info) self.prim = primitive_name def tree_flatten(self): return ([], (self.traceback_info, self.prim)) @classmethod def tree_unflatten(cls, metadata, _): return cls(*metadata) def get_effect_type(self): return ErrorEffect(NaNError, ()) def __str__(self): return f'nan generated by primitive: {self.prim}.'
NaNError
python
ray-project__ray
release/train_tests/benchmark/config.py
{ "start": 196, "end": 428 }
class ____(BaseModel): train_batch_size: int = 32 limit_training_rows: int = 1000000 # Use -1 for unlimited validation_batch_size: int = 256 limit_validation_rows: int = 50000 # Use -1 for unlimited
DataLoaderConfig
python
doocs__leetcode
solution/2800-2899/2844.Minimum Operations to Make a Special Number/Solution.py
{ "start": 0, "end": 360 }
class ____: def minimumOperations(self, num: str) -> int: @cache def dfs(i: int, k: int) -> int: if i == n: return 0 if k == 0 else n ans = dfs(i + 1, k) + 1 ans = min(ans, dfs(i + 1, (k * 10 + int(num[i])) % 25)) return ans n = len(num) return dfs(0, 0)
Solution
python
keon__algorithms
tests/test_backtrack.py
{ "start": 11653, "end": 12190 }
class ____(unittest.TestCase): def test_subsets_unique(self): nums1 = [1, 2, 2] answer1 = [(1, 2), (1,), (1, 2, 2), (2,), (), (2, 2)] self.assertEqual(sorted(subsets_unique(nums1)), sorted(answer1)) nums2 = [1, 2, 3, 4] answer2 = [(1, 2), (1, 3), (1, 2, 3, 4), (1,), (2,), (3,), (1, 4), (1, 2, 3), (4,), (), (2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4), (3, 4), (2, 4)] self.assertEqual(sorted(subsets_unique(nums2)), sorted(answer2))
TestSubsetsUnique
python
huggingface__transformers
src/transformers/models/lfm2/modeling_lfm2.py
{ "start": 5978, "end": 6935 }
class ____(nn.Module): def __init__(self, config: Lfm2Config): super().__init__() intermediate_size = config.intermediate_size if config.block_auto_adjust_ff_dim: intermediate_size = int(2 * intermediate_size / 3) # custom dim factor multiplier if config.block_ffn_dim_multiplier is not None: intermediate_size = int(config.block_ffn_dim_multiplier * intermediate_size) intermediate_size = config.block_multiple_of * ( (intermediate_size + config.block_multiple_of - 1) // config.block_multiple_of ) self.w1 = nn.Linear(config.hidden_size, intermediate_size, bias=False) self.w3 = nn.Linear(config.hidden_size, intermediate_size, bias=False) self.w2 = nn.Linear(intermediate_size, config.hidden_size, bias=False) def forward(self, x): return self.w2(F.silu(self.w1(x)) * self.w3(x))
Lfm2MLP
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 72219, "end": 72451 }
class ____(Elemwise): _parameters = ["frame", "divisions"] operation = staticmethod(_return_input) _preserves_partitioning_information = True def _divisions(self): return self.operand("divisions")
SetDivisions
python
allegroai__clearml
clearml/backend_api/services/v2_20/tasks.py
{ "start": 246027, "end": 251145 }
class ____(Request): """ Enqueue tasks :param ids: IDs of the tasks to enqueue :type ids: Sequence[str] :param status_reason: Reason for status change :type status_reason: str :param status_message: Extra information regarding status change :type status_message: str :param queue: Queue id. If not provided and no queue name is passed then tasks are added to the default queue. :type queue: str :param validate_tasks: If set then tasks are validated before enqueue :type validate_tasks: bool :param queue_name: The name of the queue. If the queue does not exist then it is auto-created. Cannot be used together with the queue id :type queue_name: str """ _service = "tasks" _action = "enqueue_many" _version = "2.20" _schema = { "definitions": {}, "properties": { "ids": { "description": "IDs of the tasks to enqueue", "items": {"type": "string"}, "type": "array", }, "queue": { "description": "Queue id. If not provided and no queue name is passed then tasks are added to the default queue.", "type": "string", }, "queue_name": { "description": "The name of the queue. If the queue does not exist then it is auto-created. Cannot be used together with the queue id", "type": "string", }, "status_message": { "description": "Extra information regarding status change", "type": "string", }, "status_reason": { "description": "Reason for status change", "type": "string", }, "validate_tasks": { "default": False, "description": "If set then tasks are validated before enqueue", "type": "boolean", }, }, "required": ["ids"], "type": "object", } def __init__( self, ids: List[str], status_reason: Optional[str] = None, status_message: Optional[str] = None, queue: Optional[str] = None, validate_tasks: Optional[bool] = False, queue_name: Optional[str] = None, **kwargs: Any ) -> None: super(EnqueueManyRequest, self).__init__(**kwargs) self.ids = ids self.status_reason = status_reason self.status_message = status_message self.queue = queue self.validate_tasks = validate_tasks self.queue_name = queue_name @schema_property("ids") def ids(self) -> List[str]: return self._property_ids @ids.setter def ids(self, value: List[str]) -> None: if value is None: self._property_ids = None return self.assert_isinstance(value, "ids", (list, tuple)) self.assert_isinstance(value, "ids", six.string_types, is_array=True) self._property_ids = value @schema_property("status_reason") def status_reason(self) -> Optional[str]: return self._property_status_reason @status_reason.setter def status_reason(self, value: Optional[str]) -> None: if value is None: self._property_status_reason = None return self.assert_isinstance(value, "status_reason", six.string_types) self._property_status_reason = value @schema_property("status_message") def status_message(self) -> Optional[str]: return self._property_status_message @status_message.setter def status_message(self, value: Optional[str]) -> None: if value is None: self._property_status_message = None return self.assert_isinstance(value, "status_message", six.string_types) self._property_status_message = value @schema_property("queue") def queue(self) -> Optional[str]: return self._property_queue @queue.setter def queue(self, value: Optional[str]) -> None: if value is None: self._property_queue = None return self.assert_isinstance(value, "queue", six.string_types) self._property_queue = value @schema_property("validate_tasks") def validate_tasks(self) -> Optional[bool]: return self._property_validate_tasks @validate_tasks.setter def validate_tasks(self, value: Optional[bool]) -> None: if value is None: self._property_validate_tasks = None return self.assert_isinstance(value, "validate_tasks", (bool,)) self._property_validate_tasks = value @schema_property("queue_name") def queue_name(self) -> Optional[str]: return self._property_queue_name @queue_name.setter def queue_name(self, value: Optional[str]) -> None: if value is None: self._property_queue_name = None return self.assert_isinstance(value, "queue_name", six.string_types) self._property_queue_name = value
EnqueueManyRequest
python
dask__distributed
distributed/diskutils.py
{ "start": 3182, "end": 9407 }
class ____: """ An on-disk workspace that tracks disposable work directories inside it. If a process crashes or another event left stale directories behind, this will be detected and the directories purged. """ base_dir: str _global_lock_path: str _purge_lock_path: str # Keep track of all locks known to this process, to avoid several # WorkSpaces to step on each other's toes _known_locks: ClassVar[set[str]] = set() def __init__(self, base_dir: str): self.base_dir = self._init_workspace(base_dir) self._global_lock_path = os.path.join(self.base_dir, "global.lock") self._purge_lock_path = os.path.join(self.base_dir, "purge.lock") def _init_workspace(self, base_dir: str) -> str: """Create base_dir if it doesn't exist. If base_dir already exists but it's not writeable, change the name. """ base_dir = os.path.abspath(base_dir) try_dirs = [base_dir] # Note: WINDOWS constant doesn't work with `mypy --platform win32` if sys.platform != "win32": # - os.getlogin() raises OSError on containerized environments # - os.getuid() does not exist in Windows try_dirs.append(f"{base_dir}-{os.getuid()}") for try_dir in try_dirs: try: os.makedirs(try_dir) except FileExistsError: try: with tempfile.TemporaryFile(dir=try_dir): pass except PermissionError: continue return try_dir # If we reached this, we're likely in a containerized environment where /tmp # has been shared between containers through a mountpoint, every container # has an external $UID, but the internal one is the same for all. return tempfile.mkdtemp(prefix=base_dir + "-") def _global_lock(self, **kwargs): return locket.lock_file(self._global_lock_path, **kwargs) def _purge_lock(self, **kwargs): return locket.lock_file(self._purge_lock_path, **kwargs) def _purge_leftovers(self): if not is_locking_enabled(): return [] # List candidates with the global lock taken, to avoid purging # a lock file that was just created but not yet locked # (see WorkDir.__init__) lock = self._global_lock(timeout=0) try: lock.acquire() except locket.LockError: # No need to waste time here if someone else is busy doing # something on this workspace return [] else: try: candidates = list(self._list_unknown_locks()) finally: lock.release() # No need to hold the global lock here, especially as purging # can take time. Instead take the purge lock to avoid two # processes purging at once. purged = [] lock = self._purge_lock(timeout=0) try: lock.acquire() except locket.LockError: # No need for two processes to purge one after another pass else: try: for path in candidates: if self._check_lock_or_purge(path): purged.append(path) finally: lock.release() return purged def _list_unknown_locks(self): for p in glob.glob(os.path.join(self.base_dir, "*" + DIR_LOCK_EXT)): try: st = os.stat(p) except OSError: # May have been removed in the meantime pass else: # XXX restrict to files owned by current user? if stat.S_ISREG(st.st_mode): yield p if sys.version_info >= (3, 12): def _purge_directory(self, dir_path): shutil.rmtree(dir_path, onexc=self._on_remove_error) else: def _purge_directory(self, dir_path): def onerror(func, path, exc_info): return self._on_remove_error(func, path, exc_info[1]) shutil.rmtree(dir_path, onerror=onerror) def _check_lock_or_purge(self, lock_path): """ Try locking the given path, if it fails it's in use, otherwise the corresponding directory is deleted. Return True if the lock was stale. """ assert lock_path.endswith(DIR_LOCK_EXT) if lock_path in self._known_locks: # Avoid touching a lock that we know is already taken return False logger.debug("Checking lock file %r...", lock_path) lock = locket.lock_file(lock_path, timeout=0) try: lock.acquire() except locket.LockError: # Lock file still in use, ignore return False try: # Lock file is stale, therefore purge corresponding directory dir_path = lock_path[: -len(DIR_LOCK_EXT)] if os.path.exists(dir_path): logger.info("Found stale lock file and directory %r, purging", dir_path) self._purge_directory(dir_path) finally: lock.release() # Clean up lock file after we released it safe_unlink(lock_path) return True def _on_remove_error(self, func, path, exc): logger.error("Failed to remove %r (failed in %r): %s", path, func, str(exc)) def new_work_dir(self, **kwargs): """ Create and return a new WorkDir in this WorkSpace. Either the *prefix* or *name* parameter should be given (*prefix* is preferred as it avoids potential collisions) Parameters ---------- prefix : str (optional) The prefix of the temporary subdirectory name for the workdir name : str (optional) The subdirectory name for the workdir """ try: self._purge_leftovers() except OSError: logger.error( "Failed to clean up lingering worker directories in path: %s ", exc_info=True, ) return WorkDir(self, **kwargs)
WorkSpace
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_slots/SLOT001.py
{ "start": 159, "end": 216 }
class ____(Tuple[str, int, float]): # SLOT001 pass
Bad
python
Pylons__pyramid
tests/test_config/test_i18n.py
{ "start": 358, "end": 6146 }
class ____(unittest.TestCase): def _makeOne(self, *arg, **kw): from pyramid.config import Configurator config = Configurator(*arg, **kw) return config def test_set_locale_negotiator(self): from pyramid.interfaces import ILocaleNegotiator config = self._makeOne(autocommit=True) def negotiator(request): # pragma: no cover pass config.set_locale_negotiator(negotiator) self.assertEqual( config.registry.getUtility(ILocaleNegotiator), negotiator ) def test_set_locale_negotiator_dottedname(self): from pyramid.interfaces import ILocaleNegotiator config = self._makeOne(autocommit=True) config.set_locale_negotiator('tests.test_config.dummyfactory') self.assertEqual( config.registry.getUtility(ILocaleNegotiator), dummyfactory ) def test_add_translation_dirs_missing_dir(self): from pyramid.exceptions import ConfigurationError config = self._makeOne() config.add_translation_dirs('/wont/exist/on/my/system') self.assertRaises(ConfigurationError, config.commit) def test_add_translation_dirs_no_specs(self): from pyramid.interfaces import ITranslationDirectories config = self._makeOne() config.add_translation_dirs() self.assertEqual( config.registry.queryUtility(ITranslationDirectories), None ) def test_add_translation_dirs_asset_spec(self): from pyramid.interfaces import ITranslationDirectories config = self._makeOne(autocommit=True) config.add_translation_dirs('tests.pkgs.localeapp:locale') self.assertEqual( config.registry.getUtility(ITranslationDirectories), [locale] ) def test_add_translation_dirs_asset_spec_existing_translation_dirs(self): from pyramid.interfaces import ITranslationDirectories config = self._makeOne(autocommit=True) directories = ['abc'] config.registry.registerUtility(directories, ITranslationDirectories) config.add_translation_dirs('tests.pkgs.localeapp:locale') result = config.registry.getUtility(ITranslationDirectories) self.assertEqual(result, [locale, 'abc']) def test_add_translation_dirs_multiple_specs(self): from pyramid.interfaces import ITranslationDirectories config = self._makeOne(autocommit=True) config.add_translation_dirs( 'tests.pkgs.localeapp:locale', 'tests.pkgs.localeapp:locale2' ) self.assertEqual( config.registry.getUtility(ITranslationDirectories), [locale, locale2], ) def test_add_translation_dirs_multiple_specs_multiple_calls(self): from pyramid.interfaces import ITranslationDirectories config = self._makeOne(autocommit=True) config.add_translation_dirs( 'tests.pkgs.localeapp:locale', 'tests.pkgs.localeapp:locale2' ) config.add_translation_dirs('tests.pkgs.localeapp:locale3') self.assertEqual( config.registry.getUtility(ITranslationDirectories), [locale3, locale, locale2], ) def test_add_translation_dirs_override_multiple_specs_multiple_calls(self): from pyramid.interfaces import ITranslationDirectories config = self._makeOne(autocommit=True) config.add_translation_dirs( 'tests.pkgs.localeapp:locale', 'tests.pkgs.localeapp:locale2' ) config.add_translation_dirs( 'tests.pkgs.localeapp:locale3', override=True ) self.assertEqual( config.registry.getUtility(ITranslationDirectories), [locale, locale2, locale3], ) def test_add_translation_dirs_invalid_kwargs(self): config = self._makeOne(autocommit=True) with self.assertRaises(TypeError): config.add_translation_dirs('tests.pkgs.localeapp:locale', foo=1) def test_add_translation_dirs_abspath(self): from pyramid.interfaces import ITranslationDirectories config = self._makeOne(autocommit=True) config.add_translation_dirs(locale) self.assertEqual( config.registry.getUtility(ITranslationDirectories), [locale] ) def test_add_translation_dirs_uses_override_out_of_order(self): from pyramid.interfaces import ITranslationDirectories config = self._makeOne() config.add_translation_dirs('tests.pkgs.localeapp:locale') config.override_asset( 'tests.pkgs.localeapp:locale/', 'tests.pkgs.localeapp:locale2/' ) config.commit() self.assertEqual( config.registry.getUtility(ITranslationDirectories), [locale2] ) def test_add_translation_dirs_doesnt_use_override_w_autocommit(self): from pyramid.interfaces import ITranslationDirectories config = self._makeOne(autocommit=True) config.add_translation_dirs('tests.pkgs.localeapp:locale') config.override_asset( 'tests.pkgs.localeapp:locale/', 'tests.pkgs.localeapp:locale2/' ) self.assertEqual( config.registry.getUtility(ITranslationDirectories), [locale] ) def test_add_translation_dirs_uses_override_w_autocommit(self): from pyramid.interfaces import ITranslationDirectories config = self._makeOne(autocommit=True) config.override_asset( 'tests.pkgs.localeapp:locale/', 'tests.pkgs.localeapp:locale2/' ) config.add_translation_dirs('tests.pkgs.localeapp:locale') self.assertEqual( config.registry.getUtility(ITranslationDirectories), [locale2] )
TestI18NConfiguratorMixin
python
sqlalchemy__sqlalchemy
test/ext/test_associationproxy.py
{ "start": 47493, "end": 47640 }
class ____: def __init__(self, name): self.name = name def __call__(self, obj): return getattr(obj, self.name)
PickleKeyFunc
python
kamyu104__LeetCode-Solutions
Python/maximum-product-of-two-integers-with-no-common-bits.py
{ "start": 67, "end": 733 }
class ____(object): def maxProduct(self, nums): """ :type nums: List[int] :rtype: int """ l = max(nums).bit_length() dp = [0]*(1<<l) for x in nums: dp[x] = x for i in xrange(l): for j in xrange(0, 1<<l, 1<<(i+1)): for k in xrange(j, j+(1<<i)): if dp[k] > dp[k+(1<<i)]: dp[k+(1<<i)] = dp[k] result = 0 for x in nums: if x*dp[((1<<l)-1)^x] > result: result = x*dp[((1<<l)-1)^x] return result # Time: O(n + rlogr), r = max(nums) # Space: O(r) # dp, bitmasks
Solution
python
getsentry__sentry
src/sentry/grouping/enhancer/matchers.py
{ "start": 5731, "end": 10041 }
class ____(EnhancementMatch): # Global registry of matchers instances: dict[InstanceKey, EnhancementMatch] = {} field: MatchFrameKey | None = None @classmethod def from_key(cls, key: str, pattern: str, negated: bool) -> EnhancementMatch: instance_key = (key, pattern, negated) if instance_key in cls.instances: instance = cls.instances[instance_key] else: instance = cls.instances[instance_key] = cls._from_key(key, pattern, negated) metrics.gauge("grouping.enhancer.matchers.registry_size", len(cls.instances)) return instance @classmethod def _from_key(cls, key: str, pattern: str, negated: bool) -> EnhancementMatch: subclass = { "package": PackageMatch, "path": PathMatch, "family": FamilyMatch, "app": InAppMatch, "function": FunctionMatch, "module": ModuleMatch, "category": CategoryMatch, "type": ExceptionTypeMatch, "value": ExceptionValueMatch, "mechanism": ExceptionMechanismMatch, }[MATCHERS[key]] return subclass(key, pattern, negated) def __init__(self, key: str, pattern: str, negated: bool = False): super().__init__() try: self.key = MATCHERS[key] except KeyError: raise InvalidEnhancerConfig("Unknown matcher '%s'" % key) self.pattern = pattern self._encoded_pattern = pattern.encode("utf-8") self.negated = negated @property def description(self) -> str: pattern_contains_whitespace = self.pattern.split() != [self.pattern] return "{}{}:{}".format( "!" if self.negated else "", self.key, self.pattern if not pattern_contains_whitespace else f'"{self.pattern}"', ) def matches_frame( self, frames: list[MatchFrame], idx: int, exception_data: dict[str, Any], cache: ReturnValueCache, ) -> bool: match_frame = frames[idx] rv = self._positive_frame_match(match_frame, exception_data, cache) if self.negated: rv = not rv return rv def _positive_frame_match( self, match_frame: MatchFrame, exception_data: dict[str, Any], cache: ReturnValueCache ) -> bool: # Implement in subclasses raise NotImplementedError def _to_config_structure(self, version: int) -> str: """ Convert the matcher into a string of the form <match_type><match_pattern> where match_type is a single letter code for the match type (see MATCH_KEYS) match_pattern is the value to match against This will be preceded by a `!` if the match is negated. Families against which to match are also converted to single-letter abbreviations, and in-app booleans are converted to 0 or 1. """ # Convert the families to match into a string of single letter abbreviations (so # `javascript,native` becomes `JN`, for example) if self.key == "family": family_abbreviations = [FAMILIES.get(family) for family in self.pattern.split(",")] value_to_match = "".join( # Filter out Nones (which come from unrecognized families) [abbreviation for abbreviation in family_abbreviations if abbreviation] ) elif self.key == "app": boolified_pattern = bool_from_string(self.pattern) value_to_match = ( "1" if boolified_pattern is True else "0" if boolified_pattern is False else "" ) else: value_to_match = self.pattern match_type_abbreviation = MATCH_KEYS[self.key] return ("!" if self.negated else "") + match_type_abbreviation + value_to_match def path_like_match(pattern: bytes, value: bytes) -> bool: """Stand-alone function for use with ``_cached``""" if glob_match(value, pattern, ignorecase=False, doublestar=True, path_normalize=True): return True if not value.startswith(b"/") and glob_match( b"/" + value, pattern, ignorecase=False, doublestar=True, path_normalize=True ): return True return False
FrameMatch
python
ray-project__ray
python/ray/experimental/util/types.py
{ "start": 418, "end": 526 }
class ____(_CollectiveOp): reduceOp: ReduceOp = ReduceOp.SUM @PublicAPI(stability="alpha")
ReduceScatterOp
python
django__django
tests/auth_tests/models/no_password.py
{ "start": 437, "end": 640 }
class ____(AbstractBaseUser): password = None last_login = None username = models.CharField(max_length=50, unique=True) USERNAME_FIELD = "username" objects = UserManager()
NoPasswordUser
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol10.py
{ "start": 423, "end": 550 }
class ____(ImplementsBase): def c(self) -> None: pass a: ProtocolExtended a = ImplementsExtended()
ImplementsExtended
python
encode__django-rest-framework
tests/test_one_to_one_with_inheritance.py
{ "start": 242, "end": 433 }
class ____(RESTFrameworkModel): child_model = models.OneToOneField(ChildModel, on_delete=models.CASCADE) child_name = models.CharField(max_length=100) # Serializers
ChildAssociatedModel
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_select.py
{ "start": 1409, "end": 2520 }
class ____(fixtures.TablesTest): __sparse_driver_backend__ = True @classmethod def define_tables(cls, metadata): Table( "some_table", metadata, Column("id", Integer, primary_key=True), Column("data", String(100)), ) @classmethod def insert_data(cls, connection): connection.execute( cls.tables.some_table.insert(), [ {"id": 1, "data": "collate data1"}, {"id": 2, "data": "collate data2"}, ], ) def _assert_result(self, select, result): with config.db.connect() as conn: eq_(conn.execute(select).fetchall(), result) @testing.requires.order_by_collation def test_collate_order_by(self): collation = testing.requires.get_order_by_collation(testing.config) self._assert_result( select(self.tables.some_table).order_by( self.tables.some_table.c.data.collate(collation).asc() ), [(1, "collate data1"), (2, "collate data2")], )
CollateTest
python
pytorch__pytorch
torch/distributed/checkpoint/hf_storage.py
{ "start": 7760, "end": 15411 }
class ____(FileSystemReader): """ A reader that reads a checkpoint in the huggingface safetensors format. """ def __init__(self, path: str, thread_count: int = 1) -> None: """ Initialize the huggingface reader pointing to path. Args: path: directory where the checkpoint will be read from. thread_count: Number of threads to use to read distributed checkpoint. Default to 1. """ super().__init__(path=path) self.thread_count = thread_count def _process_read_request(self, f, req: ReadItem, planner: LoadPlanner) -> None: """Helper function to process a single read request.""" # Create slices for each dimension based on offsets and lengths slices = tuple( slice(offset, offset + length) for offset, length in zip(req.storage_offsets, req.lengths) ) tensor = f.get_slice(req.storage_index.fqn)[slices] target_tensor = planner.resolve_tensor(req).detach() if target_tensor.size() != tensor.size(): raise AssertionError( f"req {req.storage_index} mismatch sizes {target_tensor.size()} vs {tensor.size()}" ) target_tensor.copy_(tensor) planner.commit_tensor(req, target_tensor) def _read_files_from_queue( self, file_queue: queue.Queue, result_queue: queue.Queue, planner: LoadPlanner, ) -> None: from safetensors import safe_open # type: ignore[import] try: while True: file_name, reqs = file_queue.get_nowait() with safe_open(filename=file_name, framework="pt") as f: for req in reqs: self._process_read_request(f, req, planner) result_queue.put(True) # Signal that this file has been processed except queue.Empty: pass def read_data(self, plan: LoadPlan, planner: LoadPlanner) -> Future[None]: from safetensors import safe_open # type: ignore[import] per_file: dict[str, list[ReadItem]] = {} for read_item in plan.items: item_md: _HFStorageInfo = self.storage_data[read_item.storage_index] file_name = item_md.relative_path per_file.setdefault(file_name, []).append(read_item) if self.thread_count <= 1 or len(per_file) <= 1: for file_name, reqs in per_file.items(): with safe_open(filename=file_name, framework="pt") as f: for req in reqs: self._process_read_request(f, req, planner) else: # Use parallel implementation with thread pool file_queue: queue.Queue = queue.Queue() result_queue: queue.Queue = queue.Queue() # Fill the queue with files to process for file_name, reqs in per_file.items(): file_queue.put((file_name, reqs)) # Create and start worker threads threads = [] num_threads = min(self.thread_count, len(per_file)) for _ in range(num_threads): t = threading.Thread( target=self._read_files_from_queue, args=(file_queue, result_queue, planner), ) t.start() threads.append(t) # Wait for all threads to complete for t in threads: t.join() # Check if all files were processed processed_count = 0 try: while True: result_queue.get_nowait() processed_count += 1 except queue.Empty: pass if processed_count != len(per_file): raise AssertionError( f"Not all files were processed: {processed_count} out of {len(per_file)}" ) fut: Future = Future() fut.set_result(None) return fut # pyrefly: ignore [bad-override] def read_metadata(self) -> Metadata: from safetensors import safe_open # type: ignore[import] from safetensors.torch import _getdtype # type: ignore[import] state_dict_metadata: dict[str, TensorStorageMetadata] = {} storage_data: dict[MetadataIndex, _HFStorageInfo] = {} safetensors_files = [] for file in self.fs.ls(self.path): if file.endswith(SUFFIX): safetensors_files.append(file) for safetensor_file in safetensors_files: with safe_open(safetensor_file, framework="pt") as f: keys = f.keys() extra_metadata = f.metadata() dcp_sharding_info = None if extra_metadata and extra_metadata.get(CUSTOM_METADATA_KEY): dcp_sharding_info = json.loads( extra_metadata.get(CUSTOM_METADATA_KEY) ) for key in keys: shape = f.get_slice(key).get_shape() dtype = f.get_slice(key).get_dtype() # construct state_dict_metadata if dcp_sharding_info is not None: offset = dcp_sharding_info[key][SAVED_OFFSETS_KEY] else: offset = [0] * len(shape) if key not in state_dict_metadata: state_dict_metadata[key] = TensorStorageMetadata( properties=TensorProperties(dtype=_getdtype(dtype)), size=torch.Size( [saved + offset for saved, offset in zip(shape, offset)] ), chunks=[ ChunkStorageMetadata( offsets=torch.Size(offset), sizes=torch.Size(shape), ) ], ) else: state_dict_metadata[key].chunks.append( ChunkStorageMetadata( torch.Size(offset), sizes=torch.Size(shape) ) ) size = list(state_dict_metadata[key].size) for i in range(len(size)): size[i] = max(size[i], shape[i] + offset[i]) state_dict_metadata[key].size = torch.Size(size) # construct storage data if dcp_sharding_info is not None: metadata_index = MetadataIndex( fqn=key, offset=dcp_sharding_info[key][SAVED_OFFSETS_KEY] ) else: metadata_index = MetadataIndex(fqn=key, offset=[0] * len(shape)) storage_data[metadata_index] = _HFStorageInfo( relative_path=safetensor_file, shape=torch.Size(shape), dtype=_getdtype(dtype), ) metadata = Metadata( state_dict_metadata=state_dict_metadata, # type: ignore[arg-type] storage_data=storage_data, ) if getattr(metadata, "storage_meta", None) is None: metadata.storage_meta = StorageMeta() metadata.storage_meta.load_id = self.load_id # type: ignore[union-attr] return metadata
HuggingFaceStorageReader
python
apache__airflow
dev/breeze/src/airflow_breeze/commands/ui_commands.py
{ "start": 4503, "end": 28289 }
class ____(NamedTuple): """ Represents a locale and its set of translation keys for a file (or None if file missing). Attributes: locale: The locale code (e.g., 'en', 'pl'). keys: A set of translation keys for the file, or None if the file is missing for this locale. """ locale: str keys: set[str] | None def get_plural_base(key: str, suffixes: list[str]) -> str | None: for suffix in suffixes: if key.endswith(suffix): return key[: -len(suffix)] return None def expand_plural_keys(keys: set[str], lang: str) -> set[str]: """ For a set of keys, expand all plural bases to include all required suffixes for the language. """ console = get_console() suffixes = PLURAL_SUFFIXES.get(lang) if not suffixes: console.print( f"\n[red]Error: No plural suffixes defined for language '{lang}'[/red].\n" f'[bright_blue]Most languages use ["_one", "_other"] array for suffixes, ' f"but you can check and play your language at https://jsfiddle.net/6bpxsgd4\n" ) sys.exit(1) base_to_suffixes: dict[str, set[str]] = {} for key in keys: base = get_plural_base(key, suffixes) if base: base_to_suffixes.setdefault(base, set()).add(key[len(base) :]) expanded = set(keys) for base in base_to_suffixes.keys(): for suffix in suffixes: expanded.add(base + suffix) return expanded def get_locale_files() -> list[LocaleFiles]: return [ LocaleFiles( locale=locale_dir.name, files=[f.name for f in locale_dir.iterdir() if f.suffix == ".json"] ) for locale_dir in LOCALES_DIR.iterdir() if locale_dir.is_dir() ] def load_json(filepath: Path) -> Any: return json.loads(filepath.read_text(encoding="utf-8")) def flatten_keys(d: dict, prefix: str = "") -> list[str]: keys: list[str] = [] for k, v in d.items(): full_key = f"{prefix}.{k}" if prefix else k if isinstance(v, dict): keys.extend(flatten_keys(v, full_key)) else: keys.append(full_key) return keys def compare_keys( locale_files: list[LocaleFiles], ) -> tuple[dict[str, LocaleSummary], dict[str, dict[str, int]]]: """ Compare all non-English locales with English locale only. Returns a tuple: - summary dict: filename -> LocaleSummary(missing, extra) - missing_counts dict: filename -> {locale: count_of_missing_keys} """ all_files: set[str] = set() for lf in locale_files: all_files.update(lf.files) summary: dict[str, LocaleSummary] = {} missing_counts: dict[str, dict[str, int]] = {} for filename in all_files: key_sets: list[LocaleKeySet] = [] for lf in locale_files: keys = set() if filename in lf.files: path = LOCALES_DIR / lf.locale / filename try: data = load_json(path) keys = set(flatten_keys(data)) except Exception as e: get_console().print(f"Error loading {path}: {e}") key_sets.append(LocaleKeySet(locale=lf.locale, keys=keys)) keys_by_locale = {ks.locale: ks.keys for ks in key_sets} en_keys = keys_by_locale.get("en", set()) or set() # Expand English keys for all required plural forms in each language expanded_en_keys = {lang: expand_plural_keys(en_keys, lang) for lang in keys_by_locale.keys()} missing_keys: dict[str, list[str]] = {} extra_keys: dict[str, list[str]] = {} missing_counts[filename] = {} for ks in key_sets: if ks.locale == "en": continue required_keys = expanded_en_keys.get(ks.locale, en_keys) if ks.keys is None: missing_keys[ks.locale] = list(required_keys) extra_keys[ks.locale] = [] missing_counts[filename][ks.locale] = len(required_keys) else: missing = list(required_keys - ks.keys) missing_keys[ks.locale] = missing extra_keys[ks.locale] = list(ks.keys - required_keys) missing_counts[filename][ks.locale] = len(missing) summary[filename] = LocaleSummary(missing_keys=missing_keys, extra_keys=extra_keys) return summary, missing_counts def print_locale_file_table(locale_files: list[LocaleFiles], language: str | None = None) -> None: if language and language == "en": return console = get_console() console.print("[bold underline]Locales and their files:[/bold underline]", style="cyan") from rich.table import Table table = Table(show_header=True, header_style="bold magenta") table.add_column("Locale") table.add_column("Files") filtered = sorted( locale_files if language is None else [lf for lf in locale_files if lf.locale in (language, "en")] ) for lf in filtered: table.add_row(lf.locale, ", ".join(lf.files)) console.print(table) def print_file_set_differences(locale_files: list[LocaleFiles], language: str | None = None) -> bool: if language and language == "en": return False console = get_console() filtered = ( locale_files if language is None else [lf for lf in locale_files if lf.locale in (language, "en")] ) all_file_sets = {lf.locale: set(lf.files) for lf in filtered} file_sets: list[set[str]] = list(all_file_sets.values()) found_difference = False en_files = set(all_file_sets["en"]) if len(file_sets) > 1 and any(file_sets[0] != fs for fs in file_sets[1:]): found_difference = True console.print("[bold red]Error: Locales have different set of translation files![/bold red]") all_locales_sorted = sorted(all_file_sets.keys()) for locale in all_locales_sorted: files_missing = sorted(en_files - all_file_sets[locale]) if files_missing: console.print( f"[yellow]{locale:<6}[/yellow] Missing {len(files_missing):>2}: {files_missing} " ) files_extra = sorted(all_file_sets[locale] - en_files) if files_extra: console.print(f"[red]{locale:<6}[/red] Extra {len(files_extra):>2}: {files_extra} ") return found_difference def print_language_summary(locale_files: list[LocaleFiles], summary: dict[str, LocaleSummary]) -> bool: found_difference = False console = get_console() from rich.panel import Panel for lf in sorted(locale_files): locale = lf.locale file_missing: dict[str, list[str]] = {} file_extra: dict[str, list[str]] = {} for filename, diff in sorted(summary.items()): missing_keys = diff.missing_keys.get(locale, []) extra_keys = diff.extra_keys.get(locale, []) if missing_keys: file_missing[filename] = missing_keys if extra_keys: file_extra[filename] = extra_keys if file_missing or file_extra: if locale == "en": continue console.print(Panel(f"[bold yellow]{locale}[/bold yellow]", style="blue")) if file_missing: found_difference = True console.print("[red] Missing keys (need to be added):[/red]") for filename, keys in file_missing.items(): console.print(f" [magenta]{filename}[/magenta]:") for k in keys: console.print(f" [yellow]{k}[/yellow]") if file_extra: found_difference = True console.print("[red] Extra keys (need to be removed/updated):[/red]") for filename, keys in file_extra.items(): console.print(f" [magenta]{filename}[/magenta]:") for k in keys: console.print(f" [yellow]{k}[/yellow]") return found_difference def count_todos(obj) -> int: """Count TODO: translate entries in a dict or list.""" if isinstance(obj, dict): return sum(count_todos(v) for v in obj.values()) if isinstance(obj, list): return sum(count_todos(v) for v in obj) if isinstance(obj, str) and obj.strip().startswith("TODO: translate"): return 1 return 0 def print_translation_progress(locale_files, missing_counts, summary): console = get_console() from rich.table import Table tables = defaultdict(lambda: Table(show_lines=True)) all_files = set() coverage_per_language = {} # Collect total coverage per language for lf in locale_files: all_files.update(lf.files) has_todos = False for lf in sorted(locale_files): lang = lf.locale if lang == "en": continue table = tables[lang] table.title = f"Translation Progress: {lang}" table.add_column("File", style="bold cyan") table.add_column("Missing", style="red") table.add_column("Extra", style="yellow") table.add_column("TODOs", style="magenta") table.add_column("Translated", style="green") table.add_column("Total", style="bold") table.add_column("Coverage", style="bold") table.add_column("Completed", style="bold") total_missing = 0 total_extra = 0 total_todos = 0 total_translated = 0 total_total = 0 for filename in sorted(all_files): file_path = Path(LOCALES_DIR / lang / filename) # Always get total from English version en_path = Path(LOCALES_DIR / "en" / filename) if en_path.exists(): with open(en_path) as f: en_data = json.load(f) file_total = sum(1 for _ in flatten_keys(en_data)) else: file_total = 0 if file_path.exists(): with open(file_path) as f: data = json.load(f) file_missing = missing_counts.get(filename, {}).get(lang, 0) file_extra = len(summary.get(filename, LocaleSummary({}, {})).extra_keys.get(lang, [])) file_todos = count_todos(data) if file_todos > 0: has_todos = True file_translated = file_total - file_missing # Coverage: translated / total file_coverage_percent = 100 * file_translated / file_total if file_total else 100 # Complete percent: (translated - todos) / translated file_actual_translated = file_translated - file_todos complete_percent = 100 * file_actual_translated / file_translated if file_translated else 100 style = ( "bold green" if file_missing == 0 and file_extra == 0 and file_todos == 0 else ( "yellow" if file_missing < file_total or file_extra > 0 or file_todos > 0 else "red" ) ) else: file_missing = file_total file_extra = len(summary.get(filename, LocaleSummary({}, {})).extra_keys.get(lang, [])) file_todos = 0 file_translated = 0 file_coverage_percent = 0 complete_percent = 0 style = "red" table.add_row( f"[bold reverse]{filename}[/bold reverse]", str(file_missing), str(file_extra), str(file_todos), str(file_translated), str(file_total), f"{file_coverage_percent:.1f}%", f"{complete_percent:.1f}%", style=style, ) total_missing += file_missing total_extra += file_extra total_todos += file_todos total_translated += file_translated total_total += file_total # Calculate totals for this language total_coverage_percent = 100 * total_translated / total_total if total_total else 100 total_actual_translated = total_translated - total_todos total_complete_percent = 100 * total_actual_translated / total_translated if total_translated else 100 coverage_per_language[lang] = total_coverage_percent table.add_row( "All files", str(total_missing), str(total_extra), str(total_todos), str(total_translated), str(total_total), f"{total_coverage_percent:.1f}%", f"{total_complete_percent:.1f}%", style="red" if total_complete_percent < 100 else "bold green", ) for _lang, table in tables.items(): console.print(table) return has_todos, coverage_per_language def add_missing_translations(language: str, summary: dict[str, LocaleSummary]): """ Add missing translations for the selected language. It does it by copying them from English and prefixing with 'TODO: translate:'. Ensures all required plural forms for the language are added. """ console = get_console() suffixes = PLURAL_SUFFIXES.get(language, ["_one", "_other"]) for filename, diff in summary.items(): missing_keys = set(diff.missing_keys.get(language, [])) if not missing_keys: continue en_path = LOCALES_DIR / "en" / filename lang_path = LOCALES_DIR / language / filename try: en_data = load_json(en_path) except Exception as e: console.print(f"[red]Failed to load English file {en_path}: {e}[/red]") continue try: lang_data = load_json(lang_path) except Exception: lang_data = {} # Start with an empty dict if the file doesn't exist # Helper to recursively add missing keys, including plural forms def add_keys(src, dst, prefix=""): for k, v in src.items(): full_key = f"{prefix}.{k}" if prefix else k base = get_plural_base(full_key, suffixes) if base and any(full_key == base + s for s in suffixes): for suffix in suffixes: plural_key = base + suffix key_name = plural_key.split(".")[-1] if plural_key in missing_keys: dst[key_name] = f"TODO: translate: {v}" continue if full_key in missing_keys: if isinstance(v, dict): dst[k] = {} add_keys(v, dst[k], full_key) else: dst[k] = f"TODO: translate: {v}" else: if isinstance(v, dict): if k not in dst or not isinstance(dst[k], dict): dst[k] = {} add_keys(v, dst[k], full_key) add_keys(en_data, lang_data) def sort_dict_keys(obj): if isinstance(obj, dict): return {k: sort_dict_keys(obj[k]) for k in sorted(obj.keys(), key=natural_sort_key)} return obj lang_data = sort_dict_keys(lang_data) lang_path.parent.mkdir(parents=True, exist_ok=True) with open(lang_path, "w", encoding="utf-8") as f: json.dump(lang_data, f, ensure_ascii=False, indent=2) f.write("\n") # Ensure newline at the end of the file console.print(f"[green]Added missing translations to {lang_path}[/green]") def remove_extra_translations(language: str, summary: dict[str, LocaleSummary]): """ Remove extra translations for the selected language. Removes keys that are present in the language file but missing in the English file. """ console = get_console() for filename, diff in summary.items(): extra_keys = set(diff.extra_keys.get(language, [])) if not extra_keys: continue lang_path = LOCALES_DIR / language / filename try: lang_data = load_json(lang_path) except Exception as e: console.print(f"[yellow]Failed to load {language} file {lang_path}: {e}[/yellow]") continue # Helper to recursively remove extra keys def remove_keys(dst, prefix=""): keys_to_remove = [] for k, v in list(dst.items()): full_key = f"{prefix}.{k}" if prefix else k if full_key in extra_keys: keys_to_remove.append(k) elif isinstance(v, dict): remove_keys(v, full_key) # Remove empty dictionaries after recursion if not v: keys_to_remove.append(k) for k in keys_to_remove: del dst[k] remove_keys(lang_data) def sort_dict_keys(obj): if isinstance(obj, dict): return {k: sort_dict_keys(obj[k]) for k in sorted(obj.keys(), key=natural_sort_key)} return obj lang_data = sort_dict_keys(lang_data) with open(lang_path, "w", encoding="utf-8") as f: json.dump(lang_data, f, ensure_ascii=False, indent=2) f.write("\n") # Ensure newline at the end of the file console.print(f"[green]Removed {len(extra_keys)} extra translations from {lang_path}[/green]") @click.group(cls=BreezeGroup, name="ui", help="Tools for UI development and maintenance") def ui_group(): pass @ui_group.command( name="check-translation-completeness", help="Check completeness of UI translations.", ) @click.option( "--language", "-l", default=None, help="Show summary for a single language (e.g. en, de, pl, etc.)", ) @click.option( "--add-missing", is_flag=True, default=False, help="Add missing translations for all languages except English, prefixed with 'TODO: translate:'.", ) @click.option( "--remove-extra", is_flag=True, default=False, help="Remove extra translations that are present in the language but missing in English.", ) @option_verbose @option_dry_run def check_translation_completeness( language: str | None = None, add_missing: bool = False, remove_extra: bool = False ): locale_files = get_locale_files() console = get_console() print_locale_file_table(locale_files, language) found_difference = print_file_set_differences(locale_files, language) summary, missing_counts = compare_keys(locale_files) console.print("\n[bold underline]Summary of differences by language:[/bold underline]", style="cyan") if add_missing and language != "en": # Loop through all languages except 'en' and add missing translations if language: language_files = [lf for lf in locale_files if lf.locale == language] else: language_files = [lf for lf in locale_files if lf.locale != "en"] for lf in language_files: filtered_summary = {} for filename, diff in summary.items(): filtered_summary[filename] = LocaleSummary( missing_keys={lf.locale: diff.missing_keys.get(lf.locale, [])}, extra_keys={lf.locale: diff.extra_keys.get(lf.locale, [])}, ) add_missing_translations(lf.locale, filtered_summary) # After adding, re-run the summary for all languages summary, missing_counts = compare_keys(get_locale_files()) if remove_extra and language != "en": # Loop through all languages except 'en' and remove extra translations if language: language_files = [lf for lf in locale_files if lf.locale == language] else: language_files = [lf for lf in locale_files if lf.locale != "en"] for lf in language_files: filtered_summary = {} for filename, diff in summary.items(): filtered_summary[filename] = LocaleSummary( missing_keys={lf.locale: diff.missing_keys.get(lf.locale, [])}, extra_keys={lf.locale: diff.extra_keys.get(lf.locale, [])}, ) remove_extra_translations(lf.locale, filtered_summary) # After removing, re-run the summary for all languages summary, missing_counts = compare_keys(get_locale_files()) if language: locales = [lf.locale for lf in locale_files] if language not in locales: console.print(f"[red]Language '{language}' not found among locales: {', '.join(locales)}[/red]") sys.exit(2) if language == "en": console.print("[bold red]Cannot check completeness for English language![/bold red]") sys.exit(2) else: filtered_summary = {} for filename, diff in summary.items(): filtered_summary[filename] = LocaleSummary( missing_keys={language: diff.missing_keys.get(language, [])}, extra_keys={language: diff.extra_keys.get(language, [])}, ) lang_diff = print_language_summary( [lf for lf in locale_files if lf.locale == language], filtered_summary ) found_difference = found_difference or lang_diff else: lang_diff = print_language_summary(locale_files, summary) found_difference = found_difference or lang_diff has_todos, coverage_per_language = print_translation_progress( [lf for lf in locale_files if language is None or lf.locale == language], missing_counts, summary, ) if not found_difference and not has_todos: console.print("\n[green]All translations are complete![/green]\n\n") else: console.print("\n[red]Some translations are not complete![/red]\n\n") # Print summary of total coverage per language if coverage_per_language: from rich.table import Table summary_table = Table(show_header=True, header_style="bold magenta") summary_table.title = "Total Coverage per Language" summary_table.add_column("Language", style="cyan") summary_table.add_column("Coverage", style="green") for lang, coverage in sorted(coverage_per_language.items()): if coverage >= 95: coverage_str = f"[bold green]{coverage:.1f}%[/bold green]" elif coverage > 80: coverage_str = f"[bold yellow]{coverage:.1f}%[/bold yellow]" else: coverage_str = f"[red]{coverage:.1f}%[/red]" summary_table.add_row(lang, coverage_str) console.print(summary_table) @ui_group.command( name="compile-assets", help="Compiles ui assets.", ) @click.option( "--dev", help="Run development version of assets compilation - it will not quit and automatically " "recompile assets on-the-fly when they are changed.", is_flag=True, ) @click.option( "--force-clean", help="Force cleanup of compile assets before building them.", is_flag=True, ) @option_verbose @option_dry_run def compile_ui_assets(dev: bool, force_clean: bool): perform_environment_checks() assert_prek_installed() compile_ui_assets_result = run_compile_ui_assets( dev=dev, run_in_background=False, force_clean=force_clean ) if compile_ui_assets_result.returncode != 0: get_console().print("[warn]New assets were generated[/]") sys.exit(0)
LocaleKeySet
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/hooks/elasticache_replication_group.py
{ "start": 954, "end": 12089 }
class ____(AwsBaseHook): """ Interact with Amazon ElastiCache. Provide thick wrapper around :external+boto3:py:class:`boto3.client("elasticache") <ElastiCache.Client>`. :param max_retries: Max retries for checking availability of and deleting replication group If this is not supplied then this is defaulted to 10 :param exponential_back_off_factor: Multiplication factor for deciding next sleep time If this is not supplied then this is defaulted to 1 :param initial_poke_interval: Initial sleep time in seconds If this is not supplied then this is defaulted to 60 seconds Additional arguments (such as ``aws_conn_id``) may be specified and are passed down to the underlying AwsBaseHook. .. seealso:: - :class:`airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook` """ TERMINAL_STATES = frozenset({"available", "create-failed", "deleting"}) def __init__( self, max_retries: int = 10, exponential_back_off_factor: float = 1, initial_poke_interval: float = 60, *args, **kwargs, ): self.max_retries = max_retries self.exponential_back_off_factor = exponential_back_off_factor self.initial_poke_interval = initial_poke_interval kwargs["client_type"] = "elasticache" super().__init__(*args, **kwargs) def create_replication_group(self, config: dict) -> dict: """ Create a Redis (cluster mode disabled) or a Redis (cluster mode enabled) replication group. .. seealso:: - :external+boto3:py:meth:`ElastiCache.Client.create_replication_group` :param config: Configuration for creating the replication group :return: Response from ElastiCache create replication group API """ return self.conn.create_replication_group(**config) def delete_replication_group(self, replication_group_id: str) -> dict: """ Delete an existing replication group. .. seealso:: - :external+boto3:py:meth:`ElastiCache.Client.delete_replication_group` :param replication_group_id: ID of replication group to delete :return: Response from ElastiCache delete replication group API """ return self.conn.delete_replication_group(ReplicationGroupId=replication_group_id) def describe_replication_group(self, replication_group_id: str) -> dict: """ Get information about a particular replication group. .. seealso:: - :external+boto3:py:meth:`ElastiCache.Client.describe_replication_groups` :param replication_group_id: ID of replication group to describe :return: Response from ElastiCache describe replication group API """ return self.conn.describe_replication_groups(ReplicationGroupId=replication_group_id) def get_replication_group_status(self, replication_group_id: str) -> str: """ Get current status of replication group. .. seealso:: - :external+boto3:py:meth:`ElastiCache.Client.describe_replication_groups` :param replication_group_id: ID of replication group to check for status :return: Current status of replication group """ return self.describe_replication_group(replication_group_id)["ReplicationGroups"][0]["Status"] def is_replication_group_available(self, replication_group_id: str) -> bool: """ Check if replication group is available or not. :param replication_group_id: ID of replication group to check for availability :return: True if available else False """ return self.get_replication_group_status(replication_group_id) == "available" def wait_for_availability( self, replication_group_id: str, initial_sleep_time: float | None = None, exponential_back_off_factor: float | None = None, max_retries: int | None = None, ) -> bool: """ Check if replication group is available or not by performing a describe over it. :param replication_group_id: ID of replication group to check for availability :param initial_sleep_time: Initial sleep time in seconds If this is not supplied then this is defaulted to class level value :param exponential_back_off_factor: Multiplication factor for deciding next sleep time If this is not supplied then this is defaulted to class level value :param max_retries: Max retries for checking availability of replication group If this is not supplied then this is defaulted to class level value :return: True if replication is available else False """ sleep_time = initial_sleep_time or self.initial_poke_interval exponential_back_off_factor = exponential_back_off_factor or self.exponential_back_off_factor max_retries = max_retries or self.max_retries num_tries = 0 status = "not-found" stop_poking = False while not stop_poking and num_tries <= max_retries: status = self.get_replication_group_status(replication_group_id=replication_group_id) stop_poking = status in self.TERMINAL_STATES self.log.info( "Current status of replication group with ID %s is %s", replication_group_id, status ) if not stop_poking: num_tries += 1 # No point in sleeping if all tries have exhausted if num_tries > max_retries: break self.log.info("Poke retry %s. Sleep time %s seconds. Sleeping...", num_tries, sleep_time) time.sleep(sleep_time) sleep_time *= exponential_back_off_factor if status != "available": self.log.warning('Replication group is not available. Current status is "%s"', status) return False return True def wait_for_deletion( self, replication_group_id: str, initial_sleep_time: float | None = None, exponential_back_off_factor: float | None = None, max_retries: int | None = None, ): """ Delete a replication group ensuring it is either deleted or can't be deleted. :param replication_group_id: ID of replication to delete :param initial_sleep_time: Initial sleep time in second If this is not supplied then this is defaulted to class level value :param exponential_back_off_factor: Multiplication factor for deciding next sleep time If this is not supplied then this is defaulted to class level value :param max_retries: Max retries for checking availability of replication group If this is not supplied then this is defaulted to class level value :return: Response from ElastiCache delete replication group API and flag to identify if deleted or not """ deleted = False sleep_time = initial_sleep_time or self.initial_poke_interval exponential_back_off_factor = exponential_back_off_factor or self.exponential_back_off_factor max_retries = max_retries or self.max_retries num_tries = 0 response = None while not deleted and num_tries <= max_retries: try: status = self.get_replication_group_status(replication_group_id=replication_group_id) self.log.info( "Current status of replication group with ID %s is %s", replication_group_id, status ) # Can only delete if status is `available` # Status becomes `deleting` after this call so this will only run once if status == "available": self.log.info("Initiating delete and then wait for it to finish") response = self.delete_replication_group(replication_group_id=replication_group_id) except self.conn.exceptions.ReplicationGroupNotFoundFault: self.log.info("Replication group with ID '%s' does not exist", replication_group_id) deleted = True # This should never occur as we only issue a delete request when status is `available` # which is a valid status for deletion. Still handling for safety. except self.conn.exceptions.InvalidReplicationGroupStateFault as exp: # status Error Response # creating - Cache cluster <cluster_id> is not in a valid state to be deleted. # deleting - Replication group <replication_group_id> has status deleting which is not valid # for deletion. # modifying - Replication group <replication_group_id> has status deleting which is not valid # for deletion. message = exp.response["Error"]["Message"] self.log.warning("Received error message from AWS ElastiCache API : %s", message) if not deleted: num_tries += 1 # No point in sleeping if all tries have exhausted if num_tries > max_retries: break self.log.info("Poke retry %s. Sleep time %s seconds. Sleeping...", num_tries, sleep_time) time.sleep(sleep_time) sleep_time *= exponential_back_off_factor return response, deleted def ensure_delete_replication_group( self, replication_group_id: str, initial_sleep_time: float | None = None, exponential_back_off_factor: float | None = None, max_retries: int | None = None, ) -> dict: """ Delete a replication group ensuring it is either deleted or can't be deleted. :param replication_group_id: ID of replication to delete :param initial_sleep_time: Initial sleep time in second If this is not supplied then this is defaulted to class level value :param exponential_back_off_factor: Multiplication factor for deciding next sleep time If this is not supplied then this is defaulted to class level value :param max_retries: Max retries for checking availability of replication group If this is not supplied then this is defaulted to class level value :return: Response from ElastiCache delete replication group API :raises AirflowException: If replication group is not deleted """ self.log.info("Deleting replication group with ID %s", replication_group_id) response, deleted = self.wait_for_deletion( replication_group_id=replication_group_id, initial_sleep_time=initial_sleep_time, exponential_back_off_factor=exponential_back_off_factor, max_retries=max_retries, ) if not deleted: raise AirflowException(f'Replication group could not be deleted. Response "{response}"') return response
ElastiCacheReplicationGroupHook
python
viewflow__viewflow
tests/fsm/test_fsm__inheritance.py
{ "start": 1491, "end": 3607 }
class ____(TestCase): def setUp(self): self.publication = GuestPublication(text="test publication") self.assertEqual(self.publication.state, ReviewState.NEW) def test_method_transitions_list(self): transitions = { (transition.source, transition.target) for transition in self.publication.publish.get_transitions() } self.assertEqual( { (ReviewState.APPROVED, ReviewState.PUBLISHED), (ReviewState.HIDDEN, ReviewState.PUBLISHED), }, transitions, ) def test_field_transitions(self): transitions = { (transition.source, transition.target) for transitions in GuestPublication.state.get_transitions().values() for transition in transitions } self.assertEqual( { (ReviewState.NEW, ReviewState.APPROVED), (ReviewState.NEW, ReviewState.REJECTED), (ReviewState.APPROVED, ReviewState.PUBLISHED), (ReviewState.HIDDEN, ReviewState.PUBLISHED), (fsm.State.ANY, ReviewState.HIDDEN), (fsm.State.ANY, ReviewState.REMOVED), }, transitions, ) def test_redefined_transition_failed(self): self.assertRaises(fsm.TransitionNotAllowed, self.publication.publish) def test_approvement_workflow_succeed(self): self.publication.approve() self.assertEqual(self.publication.state, ReviewState.APPROVED) self.publication.publish() self.assertEqual(self.publication.state, ReviewState.PUBLISHED) self.publication.remove() self.assertEqual(self.publication.state, ReviewState.REMOVED) def test_rejection_workflow_succeed(self): self.publication.reject() self.assertEqual(self.publication.state, ReviewState.REJECTED) self.assertRaises(fsm.TransitionNotAllowed, self.publication.publish) def test_transition_permission(self): pass def test_transition_condition(self): pass
Test
python
Netflix__metaflow
metaflow/runner/deployer.py
{ "start": 2080, "end": 3307 }
class ____(type): def __new__(mcs, name, bases, dct): cls = super().__new__(mcs, name, bases, dct) from metaflow.plugins import DEPLOYER_IMPL_PROVIDERS def _injected_method(method_name, deployer_class): def f(self, **deployer_kwargs): return deployer_class( deployer_kwargs=deployer_kwargs, flow_file=self.flow_file, show_output=self.show_output, profile=self.profile, env=self.env, cwd=self.cwd, file_read_timeout=self.file_read_timeout, **self.top_level_kwargs, ) f.__doc__ = provider_class.__doc__ or "" f.__name__ = method_name return f for provider_class in DEPLOYER_IMPL_PROVIDERS: # TYPE is the name of the CLI groups i.e. # `argo-workflows` instead of `argo_workflows` # The injected method names replace '-' by '_' though. method_name = provider_class.TYPE.replace("-", "_") setattr(cls, method_name, _injected_method(method_name, provider_class)) return cls
DeployerMeta
python
doocs__leetcode
solution/2400-2499/2414.Length of the Longest Alphabetical Continuous Substring/Solution.py
{ "start": 0, "end": 287 }
class ____: def longestContinuousSubstring(self, s: str) -> int: ans = cnt = 1 for x, y in pairwise(map(ord, s)): if y - x == 1: cnt += 1 ans = max(ans, cnt) else: cnt = 1 return ans
Solution
python
keras-team__keras
keras/src/callbacks/model_checkpoint_test.py
{ "start": 504, "end": 19216 }
class ____(testing.TestCase): @pytest.mark.skipif( h5py is None, reason="`h5py` is a required dependency for `ModelCheckpoint` tests.", ) @pytest.mark.skipif( testing.jax_uses_gpu(), reason="Mysterious core dump on CI after upgrading JAX", ) @pytest.mark.requires_trainable_backend def test_model_checkpoint_options(self): def get_model(): model = Sequential( [ layers.Dense(NUM_HIDDEN, activation="relu"), layers.Dense(NUM_CLASSES, activation="softmax"), ] ) model.compile( loss="categorical_crossentropy", optimizer="sgd", metrics=[metrics.Accuracy("acc")], ) return model model = get_model() temp_dir = self.get_temp_dir() # Save model to a subdir inside the temp_dir so we can test # automatic directory creation. filepath = os.path.join(temp_dir, "subdir", "checkpoint.keras") (x_train, y_train), (x_test, y_test) = test_utils.get_test_data( random_seed=42, train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES, ) y_test = numerical_utils.to_categorical(y_test, num_classes=NUM_CLASSES) y_train = numerical_utils.to_categorical( y_train, num_classes=NUM_CLASSES ) # Case 1 monitor = "val_loss" save_best_only = False mode = "auto" cbks = [ callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode, ) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0, ) self.assertTrue(os.path.exists(filepath)) os.remove(filepath) # Case 2 mode = "min" cbks = [ callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode, ) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0, ) self.assertTrue(os.path.exists(filepath)) os.remove(filepath) # Case 3 mode = "max" monitor = "val_acc" cbks = [ callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode, ) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0, ) self.assertTrue(os.path.exists(filepath)) os.remove(filepath) # Case 4 save_best_only = True cbks = [ callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode, ) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0, ) self.assertTrue(os.path.exists(filepath)) os.remove(filepath) # Case 5: metric not available. cbks = [ callbacks.ModelCheckpoint( filepath, monitor="unknown", save_best_only=True, mode="min" ) ] with pytest.warns(UserWarning): model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0, ) self.assertTrue(os.path.exists(filepath)) # Case 6 with warnings.catch_warnings(record=True) as warning_logs: warnings.simplefilter("always") callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode="unknown", ) self.assertIn( "ModelCheckpoint mode 'unknown' is unknown", str(warning_logs[-1].message), ) # Case 8a: `ModelCheckpoint` with an integer `save_freq` temp_dir = self.get_temp_dir() filepath = os.path.join(temp_dir, "checkpoint.epoch{epoch:02d}.keras") save_best_only = False cbks = [ callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode, save_freq=15, ) ] self.assertFalse(os.path.exists(filepath.format(epoch=3))) model.fit( x_train, y_train, batch_size=6, # 5 batches / epoch, so should backup every 3 epochs validation_data=(x_test, y_test), callbacks=cbks, epochs=10, verbose=0, ) self.assertFalse(os.path.exists(filepath.format(epoch=1))) self.assertFalse(os.path.exists(filepath.format(epoch=2))) self.assertTrue(os.path.exists(filepath.format(epoch=3))) self.assertFalse(os.path.exists(filepath.format(epoch=4))) self.assertFalse(os.path.exists(filepath.format(epoch=5))) self.assertTrue(os.path.exists(filepath.format(epoch=6))) self.assertFalse(os.path.exists(filepath.format(epoch=7))) self.assertFalse(os.path.exists(filepath.format(epoch=8))) self.assertTrue(os.path.exists(filepath.format(epoch=9))) os.remove(filepath.format(epoch=3)) os.remove(filepath.format(epoch=6)) os.remove(filepath.format(epoch=9)) # Case 8b: `ModelCheckpoint` with int `save_freq` & `save_weights_only` temp_dir = self.get_temp_dir() filepath = os.path.join( temp_dir, "checkpoint.epoch{epoch:02d}.weights.h5" ) cbks = [ callbacks.ModelCheckpoint( filepath, monitor=monitor, save_freq=15, save_weights_only=True ) ] self.assertFalse(os.path.exists(filepath.format(epoch=3))) model.fit( x_train, y_train, batch_size=6, validation_data=(x_test, y_test), callbacks=cbks, epochs=10, verbose=0, ) self.assertFalse(os.path.exists(filepath.format(epoch=1))) self.assertFalse(os.path.exists(filepath.format(epoch=2))) self.assertTrue(os.path.exists(filepath.format(epoch=3))) self.assertFalse(os.path.exists(filepath.format(epoch=4))) self.assertFalse(os.path.exists(filepath.format(epoch=5))) self.assertTrue(os.path.exists(filepath.format(epoch=6))) self.assertFalse(os.path.exists(filepath.format(epoch=7))) self.assertFalse(os.path.exists(filepath.format(epoch=8))) self.assertTrue(os.path.exists(filepath.format(epoch=9))) # Case 9: `ModelCheckpoint` with valid and invalid save_freq argument. with self.assertRaisesRegex(ValueError, "Unrecognized save_freq"): callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, save_weights_only=True, mode=mode, save_freq="invalid_save_freq", ) # The following should not raise ValueError. callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, save_weights_only=True, mode=mode, save_freq="epoch", ) callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, save_weights_only=True, mode=mode, save_freq=3, ) # Case 10a: `ModelCheckpoint` save with batch in filename. temp_dir = self.get_temp_dir() filepath = os.path.join( temp_dir, "checkpoint.epoch{epoch:02d}batch{batch:02d}.keras" ) cbks = [ callbacks.ModelCheckpoint(filepath, monitor=monitor, save_freq=1) ] model.fit( x_train, y_train, batch_size=15, validation_data=(x_test, y_test), callbacks=cbks, epochs=5, verbose=1, ) self.assertTrue(os.path.exists(filepath.format(epoch=1, batch=1))) self.assertTrue(os.path.exists(filepath.format(epoch=1, batch=2))) self.assertTrue(os.path.exists(filepath.format(epoch=2, batch=1))) self.assertTrue(os.path.exists(filepath.format(epoch=2, batch=2))) self.assertTrue(os.path.exists(filepath.format(epoch=3, batch=1))) self.assertTrue(os.path.exists(filepath.format(epoch=3, batch=2))) self.assertTrue(os.path.exists(filepath.format(epoch=4, batch=1))) self.assertTrue(os.path.exists(filepath.format(epoch=4, batch=2))) self.assertTrue(os.path.exists(filepath.format(epoch=5, batch=1))) self.assertTrue(os.path.exists(filepath.format(epoch=5, batch=2))) # Case 10b: `ModelCheckpoint` save weights with batch in filename. temp_dir = self.get_temp_dir() filepath = os.path.join( temp_dir, "checkpoint.epoch{epoch:02d}batch{batch:02d}.weights.h5" ) cbks = [ callbacks.ModelCheckpoint( filepath, monitor=monitor, save_freq=1, save_weights_only=True ) ] model.fit( x_train, y_train, batch_size=15, validation_data=(x_test, y_test), callbacks=cbks, epochs=5, verbose=1, ) self.assertTrue(os.path.exists(filepath.format(epoch=1, batch=1))) self.assertTrue(os.path.exists(filepath.format(epoch=1, batch=2))) self.assertTrue(os.path.exists(filepath.format(epoch=2, batch=1))) self.assertTrue(os.path.exists(filepath.format(epoch=2, batch=2))) self.assertTrue(os.path.exists(filepath.format(epoch=3, batch=1))) self.assertTrue(os.path.exists(filepath.format(epoch=3, batch=2))) self.assertTrue(os.path.exists(filepath.format(epoch=4, batch=1))) self.assertTrue(os.path.exists(filepath.format(epoch=4, batch=2))) self.assertTrue(os.path.exists(filepath.format(epoch=5, batch=1))) self.assertTrue(os.path.exists(filepath.format(epoch=5, batch=2))) # Case 11: ModelCheckpoint saves model with initial_value_threshold # param mode = "max" monitor = "val_acc" initial_value_threshold = -0.01 save_best_only = True filepath = os.path.join(temp_dir, "checkpoint.keras") cbks = [ callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, initial_value_threshold=initial_value_threshold, mode=mode, ) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0, ) self.assertTrue(os.path.exists(filepath)) os.remove(filepath) # Case 12: ModelCheckpoint saves model with initial_value_threshold # param mode = "auto" monitor = "val_loss" initial_value_threshold = None save_best_only = True cbks = [ callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, initial_value_threshold=initial_value_threshold, mode=mode, ) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0, ) self.assertTrue(os.path.exists(filepath)) os.remove(filepath) # Case 13: ModelCheckpoint doesn't save model if loss was minimum # earlier mode = "min" monitor = "val_loss" initial_value_threshold = 0 save_best_only = True cbks = [ callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, initial_value_threshold=initial_value_threshold, mode=mode, ) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0, ) self.assertFalse(os.path.exists(filepath)) # Case 14: ModelCheckpoint doesn't save model if loss was min earlier in # auto mode mode = "auto" monitor = "val_loss" initial_value_threshold = 0 save_best_only = True cbks = [ callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, initial_value_threshold=initial_value_threshold, mode=mode, ) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0, ) self.assertFalse(os.path.exists(filepath)) # Case 15: ModelCheckpoint doesn't save model if auc was max earlier in # auto mode mode = "auto" monitor = "val_auc" initial_value_threshold = 1 save_best_only = True cbks = [ callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, initial_value_threshold=initial_value_threshold, mode=mode, ) ] model.compile( loss="categorical_crossentropy", optimizer="sgd", metrics=[metrics.AUC()], ) model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0, ) self.assertFalse(os.path.exists(filepath)) @pytest.mark.skipif( h5py is None, reason="`h5py` is a required dependency for `ModelCheckpoint` tests.", ) @pytest.mark.requires_trainable_backend def test_model_checkpoint_loading(self): def get_model(): inputs = layers.Input(shape=(INPUT_DIM,), batch_size=5) x = layers.Dense(NUM_HIDDEN, activation="relu")(inputs) outputs = layers.Dense(NUM_CLASSES, activation="softmax")(x) functional_model = models.Model(inputs, outputs) functional_model.compile( loss="categorical_crossentropy", optimizer="sgd", metrics=[metrics.Accuracy("acc")], ) return functional_model (x_train, y_train), (x_test, y_test) = test_utils.get_test_data( random_seed=42, train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES, ) y_test = numerical_utils.to_categorical(y_test, num_classes=NUM_CLASSES) y_train = numerical_utils.to_categorical( y_train, num_classes=NUM_CLASSES ) # Model Checkpoint load model (default) model = get_model() temp_dir = self.get_temp_dir() filepath = os.path.join(temp_dir, "checkpoint.model.keras") mode = "auto" monitor = "val_loss" save_best_only = True cbks = [ callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode, ) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0, ) ref_weights = model.get_weights() self.assertTrue(os.path.exists(filepath)) new_model = saving.load_model(filepath) new_weights = new_model.get_weights() self.assertEqual(len(ref_weights), len(new_weights)) for ref_w, w in zip(ref_weights, new_weights): self.assertAllClose(ref_w, w) # Model Checkpoint load model weights model = get_model() temp_dir = self.get_temp_dir() filepath = os.path.join(temp_dir, "checkpoint.weights.h5") mode = "auto" monitor = "val_loss" save_best_only = True cbks = [ callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, save_weights_only=True, mode=mode, ) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0, ) ref_weights = model.get_weights() self.assertTrue(os.path.exists(filepath)) new_model = get_model() new_model.load_weights(filepath) new_weights = new_model.get_weights() self.assertEqual(len(ref_weights), len(new_weights)) for ref_w, w in zip(ref_weights, new_weights): self.assertAllClose(ref_w, w)
ModelCheckpointTest
python
realpython__materials
contact-book-python-textual/source_code_step_2/rpcontacts/tui.py
{ "start": 199, "end": 1598 }
class ____(App): CSS_PATH = "rpcontacts.tcss" BINDINGS = [ ("m", "toggle_dark", "Toggle dark mode"), ("a", "add", "Add"), ("d", "delete", "Delete"), ("c", "clear_all", "Clear All"), ("q", "request_quit", "Quit"), ] def compose(self): yield Header() contacts_list = DataTable(classes="contacts-list") contacts_list.focus() contacts_list.add_columns("Name", "Phone", "Email") contacts_list.cursor_type = "row" contacts_list.zebra_stripes = True add_button = Button("Add", variant="success", id="add") add_button.focus() buttons_panel = Vertical( add_button, Button("Delete", variant="warning", id="delete"), Static(classes="separator"), Button("Clear All", variant="error", id="clear"), classes="buttons-panel", ) yield Horizontal(contacts_list, buttons_panel) yield Footer() def on_mount(self): self.title = "RP Contacts" self.sub_title = "A Contacts Book App With Textual & Python" def action_toggle_dark(self): self.dark = not self.dark def action_request_quit(self): def check_answer(accepted): if accepted: self.exit() self.push_screen(QuestionDialog("Do you want to quit?"), check_answer)
ContactsApp
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/freshness.py
{ "start": 10636, "end": 11009 }
class ____: """Store serialized metadata about the freshness state for an entity. Left blank for now, a few examples of what we might want to store here: - Source timestamp for external assets / freshness checks - Snapshot of the freshness policy at the time of record creation """ metadata: Optional[dict[str, Any]] @record
FreshnessStateRecordBody
python
getsentry__sentry
src/sentry/discover/models.py
{ "start": 5047, "end": 7240 }
class ____(BaseManager["TeamKeyTransaction"]): @staticmethod def __schedule_invalidate_project_config_transaction_commit(instance, trigger): try: project = getattr(instance.project_team, "project", None) except ProjectTeam.DoesNotExist: # During org deletions TeamKeyTransactions are cleaned up as a cascade # of ProjectTeam being deleted so this read can fail. return if project is None: return if features.has("organizations:dynamic-sampling", project.organization): from sentry.dynamic_sampling import RuleType, get_enabled_user_biases # check if option is enabled enabled_biases = get_enabled_user_biases( project.get_option("sentry:dynamic_sampling_biases", None) ) # invalidate project config only when the rule is enabled if RuleType.BOOST_KEY_TRANSACTIONS_RULE.value in enabled_biases: schedule_invalidate_project_config(project_id=project.id, trigger=trigger) def post_save(self, *, instance: TeamKeyTransaction, created: bool, **kwargs: object) -> None: # this hook may be called from model hooks during an # open transaction. In that case, wait until the current transaction has # been committed or rolled back to ensure we don't read stale data in the # task. # # If there is no transaction open, on_commit should run immediately. self.__schedule_invalidate_project_config_transaction_commit( instance, "teamkeytransaction.post_save" ) def post_delete(self, instance, **kwargs): # this hook may be called from model hooks during an # open transaction. In that case, wait until the current transaction has # been committed or rolled back to ensure we don't read stale data in the # task. # # If there is no transaction open, on_commit should run immediately. self.__schedule_invalidate_project_config_transaction_commit( instance, "teamkeytransaction.post_delete" ) @region_silo_model
TeamKeyTransactionModelManager
python
modin-project__modin
modin/pandas/series_utils.py
{ "start": 2197, "end": 3135 }
class ____(ClassLogger): _series: Series _query_compiler: BaseQueryCompiler def __init__(self, data: Series = None): self._series = data self._query_compiler = data._query_compiler @cached_property def _Series(self) -> Series: # noqa: GL08 # to avoid cyclic import from modin.pandas.series import Series return Series @property def dtypes(self): return self._Series(query_compiler=self._query_compiler.struct_dtypes()) def field(self, name_or_index): return self._Series( query_compiler=self._query_compiler.struct_field( name_or_index=name_or_index ) ) def explode(self): from modin.pandas.dataframe import DataFrame return DataFrame(query_compiler=self._query_compiler.struct_explode()) @_inherit_docstrings(pandas.core.arrays.categorical.CategoricalAccessor)
StructAccessor
python
spack__spack
lib/spack/spack/vendor/jinja2/loaders.py
{ "start": 1052, "end": 5545 }
class ____: """Baseclass for all loaders. Subclass this and override `get_source` to implement a custom loading mechanism. The environment provides a `get_template` method that calls the loader's `load` method to get the :class:`Template` object. A very basic example for a loader that looks up templates on the file system could look like this:: from spack.vendor.jinja2 import BaseLoader, TemplateNotFound from os.path import join, exists, getmtime class MyLoader(BaseLoader): def __init__(self, path): self.path = path def get_source(self, environment, template): path = join(self.path, template) if not exists(path): raise TemplateNotFound(template) mtime = getmtime(path) with open(path) as f: source = f.read() return source, path, lambda: mtime == getmtime(path) """ #: if set to `False` it indicates that the loader cannot provide access #: to the source of templates. #: #: .. versionadded:: 2.4 has_source_access = True def get_source( self, environment: "Environment", template: str ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]: """Get the template source, filename and reload helper for a template. It's passed the environment and template name and has to return a tuple in the form ``(source, filename, uptodate)`` or raise a `TemplateNotFound` error if it can't locate the template. The source part of the returned tuple must be the source of the template as a string. The filename should be the name of the file on the filesystem if it was loaded from there, otherwise ``None``. The filename is used by Python for the tracebacks if no loader extension is used. The last item in the tuple is the `uptodate` function. If auto reloading is enabled it's always called to check if the template changed. No arguments are passed so the function must store the old state somewhere (for example in a closure). If it returns `False` the template will be reloaded. """ if not self.has_source_access: raise RuntimeError( f"{type(self).__name__} cannot provide access to the source" ) raise TemplateNotFound(template) def list_templates(self) -> t.List[str]: """Iterates over all templates. If the loader does not support that it should raise a :exc:`TypeError` which is the default behavior. """ raise TypeError("this loader cannot iterate over all templates") @internalcode def load( self, environment: "Environment", name: str, globals: t.Optional[t.MutableMapping[str, t.Any]] = None, ) -> "Template": """Loads a template. This method looks up the template in the cache or loads one by calling :meth:`get_source`. Subclasses should not override this method as loaders working on collections of other loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`) will not call this method but `get_source` directly. """ code = None if globals is None: globals = {} # first we try to get the source for this template together # with the filename and the uptodate function. source, filename, uptodate = self.get_source(environment, name) # try to load the code from the bytecode cache if there is a # bytecode cache configured. bcc = environment.bytecode_cache if bcc is not None: bucket = bcc.get_bucket(environment, name, filename, source) code = bucket.code # if we don't have code so far (not cached, no longer up to # date) etc. we compile the template if code is None: code = environment.compile(source, name, filename) # if the bytecode cache is available and the bucket doesn't # have a code so far, we give the bucket the new code and put # it back to the bytecode cache. if bcc is not None and bucket.code is None: bucket.code = code bcc.set_bucket(bucket) return environment.template_class.from_code( environment, code, globals, uptodate )
BaseLoader
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 224890, "end": 225216 }
class ____(ConditionalMarkPropFieldOrDatumDef): """ConditionalPredicateMarkPropFieldOrDatumDef schema wrapper.""" _schema = {"$ref": "#/definitions/ConditionalPredicate<MarkPropFieldOrDatumDef>"} def __init__(self, *args, **kwds): super().__init__(*args, **kwds)
ConditionalPredicateMarkPropFieldOrDatumDef
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pie/PIE807.py
{ "start": 448, "end": 564 }
class ____: foo: List[str] = field(default_factory=list) bar: Dict[str, int] = field(default_factory=dict)
Foo
python
conda__conda
conda/plugins/reporter_backends/console.py
{ "start": 1165, "end": 2667 }
class ____(ProgressBarBase): """ Progress bar class used for tqdm progress bars """ def __init__( self, description: str, position=None, leave=True, **kwargs, ) -> None: super().__init__(description) self.enabled = True bar_format = "{desc}{bar} | {percentage:3.0f}% " try: self.pbar = self._tqdm( desc=description, bar_format=bar_format, ascii=True, total=1, file=sys.stdout, position=position, leave=leave, ) except OSError as e: if e.errno in (EPIPE, ESHUTDOWN): self.enabled = False else: raise def update_to(self, fraction) -> None: try: if self.enabled: self.pbar.update(fraction - self.pbar.n) except OSError as e: if e.errno in (EPIPE, ESHUTDOWN): self.enabled = False else: raise @swallow_broken_pipe def close(self) -> None: if self.enabled: self.pbar.close() def refresh(self) -> None: if self.enabled: self.pbar.refresh() @staticmethod def _tqdm(*args, **kwargs): """Deferred import so it doesn't hit the `conda activate` paths.""" from tqdm.auto import tqdm return tqdm(*args, **kwargs)
TQDMProgressBar
python
django__django
django/forms/models.py
{ "start": 58197, "end": 62010 }
class ____(ModelChoiceField): """A MultipleChoiceField whose choices are a model QuerySet.""" widget = SelectMultiple hidden_widget = MultipleHiddenInput default_error_messages = { "invalid_list": _("Enter a list of values."), "invalid_choice": _( "Select a valid choice. %(value)s is not one of the available choices." ), "invalid_pk_value": _("“%(pk)s” is not a valid value."), } def __init__(self, queryset, **kwargs): super().__init__(queryset, empty_label=None, **kwargs) def to_python(self, value): if not value: return [] return list(self._check_values(value)) def clean(self, value): value = self.prepare_value(value) if self.required and not value: raise ValidationError(self.error_messages["required"], code="required") elif not self.required and not value: return self.queryset.none() if not isinstance(value, (list, tuple)): raise ValidationError( self.error_messages["invalid_list"], code="invalid_list", ) qs = self._check_values(value) # Since this overrides the inherited ModelChoiceField.clean # we run custom validators here self.run_validators(value) return qs def _check_values(self, value): """ Given a list of possible PK values, return a QuerySet of the corresponding objects. Raise a ValidationError if a given value is invalid (not a valid PK, not in the queryset, etc.) """ key = self.to_field_name or "pk" # deduplicate given values to avoid creating many querysets or # requiring the database backend deduplicate efficiently. try: value = frozenset(value) except TypeError: # list of lists isn't hashable, for example raise ValidationError( self.error_messages["invalid_list"], code="invalid_list", ) for pk in value: self.validate_no_null_characters(pk) try: self.queryset.filter(**{key: pk}) except (ValueError, TypeError, ValidationError): raise ValidationError( self.error_messages["invalid_pk_value"], code="invalid_pk_value", params={"pk": pk}, ) qs = self.queryset.filter(**{"%s__in" % key: value}) pks = {str(getattr(o, key)) for o in qs} for val in value: if str(val) not in pks: raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": val}, ) return qs def prepare_value(self, value): if ( hasattr(value, "__iter__") and not isinstance(value, str) and not hasattr(value, "_meta") ): prepare_value = super().prepare_value return [prepare_value(v) for v in value] return super().prepare_value(value) def has_changed(self, initial, data): if self.disabled: return False if initial is None: initial = [] if data is None: data = [] if len(initial) != len(data): return True initial_set = {str(value) for value in self.prepare_value(initial)} data_set = {str(value) for value in data} return data_set != initial_set def modelform_defines_fields(form_class): return hasattr(form_class, "_meta") and ( form_class._meta.fields is not None or form_class._meta.exclude is not None )
ModelMultipleChoiceField
python
mlflow__mlflow
tests/langchain/sample_code/workflow.py
{ "start": 681, "end": 3403 }
class ____(ChatOpenAI, extra="allow"): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._responses = iter( [ AIMessage( content="", tool_calls=[ToolCall(name="uc_tool_format", args={}, id="123")], ), AIMessage( content="", tool_calls=[ToolCall(name="lc_tool_format", args={}, id="456")], ), AIMessage(content="Successfully generated", id="789"), ] ) def _generate(self, *args, **kwargs): return ChatResult(generations=[ChatGeneration(message=next(self._responses))]) @tool def uc_tool_format() -> str: """Returns uc tool format""" return json.dumps( { "format": "SCALAR", "value": '{"content":"hi","attachments":{"a":"b"},"custom_outputs":{"c":"d"}}', "truncated": False, } ) @tool def lc_tool_format() -> dict[str, Any]: """Returns lc tool format""" nums = [1, 2] return { "content": f"Successfully generated array of 2 random ints: {nums}.", "attachments": {"key1": "attach1", "key2": "attach2"}, "custom_outputs": {"random_nums": nums}, } tools = [uc_tool_format, lc_tool_format] def create_tool_calling_agent( model: LanguageModelLike, tools: ToolNode | Sequence[BaseTool], agent_prompt: str | None = None, ) -> CompiledStateGraph: model = model.bind_tools(tools) def should_continue(state: ChatAgentState): messages = state["messages"] last_message = messages[-1] # If there are function calls, continue. else, end if last_message.get("tool_calls"): return "continue" else: return "end" preprocessor = RunnableLambda(lambda state: state["messages"]) model_runnable = preprocessor | model @mlflow.trace def call_model( state: ChatAgentState, config: RunnableConfig, ): response = model_runnable.invoke(state, config) return {"messages": [response]} workflow = StateGraph(ChatAgentState) workflow.add_node("agent", RunnableLambda(call_model)) workflow.add_node("tools", ChatAgentToolNode(tools)) workflow.set_entry_point("agent") workflow.add_conditional_edges( "agent", should_continue, { "continue": "tools", "end": END, }, ) workflow.add_edge("tools", "agent") return workflow.compile() mlflow.langchain.autolog() llm = FakeOpenAI() graph = create_tool_calling_agent(llm, tools) mlflow.models.set_model(graph)
FakeOpenAI
python
python-openxml__python-docx
tests/opc/test_oxml.py
{ "start": 809, "end": 1250 }
class ____: def it_provides_read_access_to_xml_values(self): override = an_Override().element assert override.partname == "/part/name.xml" assert override.content_type == "app/vnd.type" def it_can_construct_a_new_override_element(self): override = CT_Override.new("/part/name.xml", "app/vnd.type") expected_xml = an_Override().xml assert override.xml == expected_xml
DescribeCT_Override
python
pennersr__django-allauth
allauth/socialaccount/providers/weixin/client.py
{ "start": 246, "end": 1931 }
class ____(OAuth2Client): def get_redirect_url(self, authorization_url, scope, extra_params): scope = self.scope_delimiter.join(set(scope)) params = { "appid": self.consumer_key, "redirect_uri": self.callback_url, "scope": scope, "response_type": "code", } if self.state: params["state"] = self.state params.update(extra_params) sorted_params = OrderedDict() for param in sorted(params): sorted_params[param] = params[param] return "%s?%s" % (authorization_url, urlencode(sorted_params)) def get_access_token(self, code, pkce_code_verifier=None): data = { "appid": self.consumer_key, "grant_type": "authorization_code", "secret": self.consumer_secret, "code": code, } params = None self._strip_empty_keys(data) url = self.access_token_url if self.access_token_method == "GET": # nosec params = data data = None if data and pkce_code_verifier: data["code_verifier"] = pkce_code_verifier # TODO: Proper exception handling resp = ( get_adapter() .get_requests_session() .request(self.access_token_method, url, params=params, data=data) ) access_token = None if resp.status_code == HTTPStatus.OK: access_token = resp.json() if not access_token or "access_token" not in access_token: raise OAuth2Error("Error retrieving access token: %s" % resp.content) return access_token
WeixinOAuth2Client
python
django__django
django/core/validators.py
{ "start": 13747, "end": 13959 }
class ____(BaseValidator): message = _("Ensure this value is less than or equal to %(limit_value)s.") code = "max_value" def compare(self, a, b): return a > b @deconstructible
MaxValueValidator
python
openai__openai-python
src/openai/types/responses/response_error.py
{ "start": 190, "end": 915 }
class ____(BaseModel): code: Literal[ "server_error", "rate_limit_exceeded", "invalid_prompt", "vector_store_timeout", "invalid_image", "invalid_image_format", "invalid_base64_image", "invalid_image_url", "image_too_large", "image_too_small", "image_parse_error", "image_content_policy_violation", "invalid_image_mode", "image_file_too_large", "unsupported_image_media_type", "empty_image_file", "failed_to_download_image", "image_file_not_found", ] """The error code for the response.""" message: str """A human-readable description of the error."""
ResponseError
python
django__django
django/templatetags/i18n.py
{ "start": 1868, "end": 2092 }
class ____(Node): def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = translation.get_language_bidi() return ""
GetCurrentLanguageBidiNode
python
keras-team__keras
keras/src/backend/common/stateless_scope_test.py
{ "start": 176, "end": 1985 }
class ____(testing.TestCase): def test_basic_flow(self): var1 = backend.Variable(np.zeros((2,))) var2 = backend.Variable(np.zeros((2,))) var_out = backend.Variable(np.zeros((2,))) value1 = ops.ones(shape=(2,)) value2 = ops.ones(shape=(2,)) with StatelessScope( state_mapping=[(var1, value1), (var2, value2)] ) as scope: out = var1 + var2 var_out.assign(out) var_out_value = var_out + 0.0 # Inside scope: new value is used. self.assertAllClose(var_out_value, 2 * np.ones((2,))) # Out of scope: old value is used. var_out_value = var_out + 0.0 self.assertAllClose(var_out_value, np.zeros((2,))) # Updates are tracked. var_out_value = scope.get_current_value(var_out) self.assertAllClose(var_out_value, 2 * np.ones((2,))) # Updates can be reapplied. var_out.assign(scope.get_current_value(var_out)) self.assertAllClose(var_out_value, 2 * np.ones((2,))) def test_invalid_key_in_state_mapping(self): # var1 = backend.Variable(np.zeros((2,))) invalid_key = "not_a_keras_variable" value1 = ops.ones(shape=(2,)) with self.assertRaisesRegex( ValueError, "all keys in argument `mapping` must be Variable" ): StatelessScope(state_mapping=[(invalid_key, value1)]) def test_invalid_value_shape_in_state_mapping(self): var1 = backend.Variable(np.zeros((2,))) invalid_value = ops.ones(shape=(3,)) # Incorrect shape with self.assertRaisesRegex( ValueError, "all values in argument `mapping` must be tensors with" ): StatelessScope(state_mapping=[(var1, invalid_value)])
TestStatelessScope
python
tiangolo__fastapi
docs_src/schema_extra_example/tutorial002_py310.py
{ "start": 85, "end": 479 }
class ____(BaseModel): name: str = Field(examples=["Foo"]) description: str | None = Field(default=None, examples=["A very nice Item"]) price: float = Field(examples=[35.4]) tax: float | None = Field(default=None, examples=[3.2]) @app.put("/items/{item_id}") async def update_item(item_id: int, item: Item): results = {"item_id": item_id, "item": item} return results
Item
python
openai__openai-python
src/openai/types/chat/chat_completion_allowed_tool_choice_param.py
{ "start": 318, "end": 636 }
class ____(TypedDict, total=False): allowed_tools: Required[ChatCompletionAllowedToolsParam] """Constrains the tools available to the model to a pre-defined set.""" type: Required[Literal["allowed_tools"]] """Allowed tool configuration type. Always `allowed_tools`."""
ChatCompletionAllowedToolChoiceParam
python
kamyu104__LeetCode-Solutions
Python/keyboard-row.py
{ "start": 29, "end": 745 }
class ____(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ rows = [set(['q', 'w', 'e', 'r', 't', 'y','u', 'i', 'o', 'p']), set(['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']), set(['z', 'x', 'c', 'v', 'b' ,'n', 'm'])] result = [] for word in words: k = 0 for i in xrange(len(rows)): if word[0].lower() in rows[i]: k = i break for c in word: if c.lower() not in rows[k]: break else: result.append(word) return result
Solution
python
dateutil__dateutil
tests/test_tz.py
{ "start": 6785, "end": 6969 }
class ____(object): def __init__(*args, **kwargs): pass def __enter__(*args, **kwargs): pass def __exit__(*args, **kwargs): pass
context_passthrough
python
doocs__leetcode
solution/1000-1099/1049.Last Stone Weight II/Solution.py
{ "start": 0, "end": 504 }
class ____: def lastStoneWeightII(self, stones: List[int]) -> int: s = sum(stones) m, n = len(stones), s >> 1 dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(n + 1): dp[i][j] = dp[i - 1][j] if stones[i - 1] <= j: dp[i][j] = max( dp[i][j], dp[i - 1][j - stones[i - 1]] + stones[i - 1] ) return s - 2 * dp[-1][-1]
Solution
python
huggingface__transformers
tests/models/ibert/test_modeling_ibert.py
{ "start": 1520, "end": 8753 }
class ____: def __init__( self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=16, type_sequence_label_size=2, initializer_range=0.02, num_labels=3, num_choices=4, scope=None, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.use_input_mask = use_input_mask self.use_token_type_ids = use_token_type_ids self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.num_labels = num_labels self.num_choices = num_choices self.scope = scope def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) input_mask = None if self.use_input_mask: input_mask = random_attention_mask([self.batch_size, self.seq_length]) token_type_ids = None if self.use_token_type_ids: token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) sequence_labels = None token_labels = None choice_labels = None if self.use_labels: sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) choice_labels = ids_tensor([self.batch_size], self.num_choices) config = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def get_config(self): return IBertConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, initializer_range=self.initializer_range, quant_mode=True, ) def get_pipeline_config(self): config = self.get_config() config.vocab_size = 300 return config def create_and_check_model( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = IBertModel(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) result = model(input_ids, token_type_ids=token_type_ids) result = model(input_ids) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) def create_and_check_for_masked_lm( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = IBertForMaskedLM(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def create_and_check_for_token_classification( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): config.num_labels = self.num_labels model = IBertForTokenClassification(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) def create_and_check_for_multiple_choice( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): config.num_choices = self.num_choices model = IBertForMultipleChoice(config=config) model.to(torch_device) model.eval() multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() result = model( multiple_choice_inputs_ids, attention_mask=multiple_choice_input_mask, token_type_ids=multiple_choice_token_type_ids, labels=choice_labels, ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) def create_and_check_for_question_answering( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = IBertForQuestionAnswering(config=config) model.to(torch_device) model.eval() result = model( input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, start_positions=sequence_labels, end_positions=sequence_labels, ) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) = config_and_inputs inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch
IBertModelTester
python
celery__celery
t/unit/utils/test_serialization.py
{ "start": 2629, "end": 3256 }
class ____: @pytest.mark.parametrize('s,b', STRTOBOOL_DEFAULT_TABLE.items()) def test_default_table(self, s, b): assert strtobool(s) == b def test_unknown_value(self): with pytest.raises(TypeError, match="Cannot coerce 'foo' to type bool"): strtobool('foo') def test_no_op(self): assert strtobool(1) == 1 def test_custom_table(self): custom_table = { 'foo': True, 'bar': False } assert strtobool("foo", table=custom_table) assert not strtobool("bar", table=custom_table)
test_strtobool
python
huggingface__transformers
src/transformers/models/yoso/modeling_yoso.py
{ "start": 11114, "end": 16919 }
class ____(nn.Module): def __init__(self, config): super().__init__() if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention " f"heads ({config.num_attention_heads})" ) kernel_loaded = lsh_cumulation is not None if is_torch_cuda_available() and is_ninja_available() and not kernel_loaded: try: load_cuda_kernels() except Exception as e: logger.warning(f"Could not load the custom kernel for multi-scale deformable attention: {e}") self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) self.use_expectation = config.use_expectation self.hash_code_len = config.hash_code_len self.use_conv = config.conv_window is not None self.use_fast_hash = config.use_fast_hash self.num_hash = config.num_hash self.lsh_backward = config.lsh_backward self.lsh_config = { "hash_code_len": self.hash_code_len, "use_fast_hash": self.use_fast_hash, "num_hash": self.num_hash, "lsh_backward": self.lsh_backward, } if config.conv_window is not None: self.conv = nn.Conv2d( in_channels=config.num_attention_heads, out_channels=config.num_attention_heads, kernel_size=(config.conv_window, 1), padding=(config.conv_window // 2, 0), bias=False, groups=config.num_attention_heads, ) def forward(self, hidden_states, attention_mask=None, output_attentions=False): batch_size, seq_length, _ = hidden_states.shape query_layer = ( self.query(hidden_states) .view(batch_size, -1, self.num_attention_heads, self.attention_head_size) .transpose(1, 2) ) key_layer = ( self.key(hidden_states) .view(batch_size, -1, self.num_attention_heads, self.attention_head_size) .transpose(1, 2) ) value_layer = ( self.value(hidden_states) .view(batch_size, -1, self.num_attention_heads, self.attention_head_size) .transpose(1, 2) ) if self.use_conv: conv_value_layer = self.conv(value_layer * attention_mask[:, None, :, None]) batch_size, num_heads, seq_len, head_dim = query_layer.size() query_layer = query_layer.reshape(batch_size * num_heads, seq_len, head_dim) key_layer = key_layer.reshape(batch_size * num_heads, seq_len, head_dim) value_layer = value_layer.reshape(batch_size * num_heads, seq_len, head_dim) attention_mask = 1.0 + attention_mask / 10000.0 attention_mask = ( attention_mask.unsqueeze(1) .repeat_interleave(num_heads, dim=1) .reshape(batch_size * num_heads, seq_len) .int() ) # The CUDA kernels are most efficient with inputs whose size is a multiple of a GPU's warp size (32). Inputs # smaller than this are padded with zeros. gpu_warp_size = 32 if (not self.use_expectation) and head_dim < gpu_warp_size: pad_size = batch_size * num_heads, seq_len, gpu_warp_size - head_dim query_layer = torch.cat( [ query_layer, torch.zeros(pad_size, device=query_layer.device), ], dim=-1, ) key_layer = torch.cat( [ key_layer, torch.zeros(pad_size, device=key_layer.device), ], dim=-1, ) value_layer = torch.cat( [ value_layer, torch.zeros(pad_size, device=value_layer.device), ], dim=-1, ) if self.use_expectation or self.training: query_layer, key_layer = normalize([query_layer, key_layer]) if self.use_expectation: context_layer = YosoCumulation.apply( attention_mask, attention_mask, query_layer, key_layer, value_layer, self.lsh_config ) else: context_layer = YosoLSHCumulation.apply( attention_mask, attention_mask, query_layer, key_layer, value_layer, self.lsh_config ) if (not self.use_expectation) and head_dim < gpu_warp_size: context_layer = context_layer[:, :, :head_dim] context_layer = normalize(context_layer) context_layer = context_layer.reshape(batch_size, num_heads, seq_len, head_dim) if self.use_conv: context_layer += conv_value_layer context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) context_layer = context_layer.view(*new_context_layer_shape) outputs = (context_layer, context_layer) if output_attentions else (context_layer,) return outputs # Copied from transformers.models.bert.modeling_bert.BertSelfOutput
YosoSelfAttention
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1408307, "end": 1408583 }
class ____(sgqlc.types.Type, Node, AuditEntry, OrganizationAuditEntryData, RepositoryAuditEntryData): """Audit log entry for a repo.config.lock_anonymous_git_access event.""" __schema__ = github_schema __field_names__ = ()
RepoConfigLockAnonymousGitAccessAuditEntry
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/test_bigquery.py
{ "start": 63895, "end": 77868 }
class ____: def setup_method(self) -> None: class MockedBigQueryAsyncHook(BigQueryAsyncHook): def get_credentials_and_project_id(self): return CREDENTIALS, PROJECT_ID self.hook = MockedBigQueryAsyncHook() @pytest.mark.db_test @pytest.mark.asyncio @mock.patch("google.auth.default") @mock.patch("airflow.providers.google.cloud.hooks.bigquery.ClientSession") async def test_get_job_instance(self, mock_session, mock_auth_default): mock_credentials = mock.MagicMock(spec=google.auth.compute_engine.Credentials) mock_credentials.token = "ACCESS_TOKEN" mock_auth_default.return_value = (mock_credentials, PROJECT_ID) hook = BigQueryAsyncHook() result = await hook.get_job_instance(project_id=PROJECT_ID, job_id=JOB_ID, session=mock_session) assert isinstance(result, Job) @pytest.mark.parametrize( ("job_state", "error_result", "expected"), [ ("DONE", None, {"status": "success", "message": "Job completed"}), ("DONE", {"message": "Timeout"}, {"status": "error", "message": "Timeout"}), ("RUNNING", None, {"status": "running", "message": "Job running"}), ], ) @pytest.mark.asyncio @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryAsyncHook._get_job") async def test_get_job_status(self, mock_get_job, job_state, error_result, expected): hook = BigQueryAsyncHook() mock_get_job.return_value = mock.MagicMock(state=job_state, error_result=error_result) resp = await hook.get_job_status(job_id=JOB_ID, project_id=PROJECT_ID) assert resp == expected @pytest.mark.asyncio @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryAsyncHook.get_job_instance") async def test_get_job_output_assert_once_with(self, mock_job_instance): hook = BigQueryAsyncHook() mock_job_client = AsyncMock(Job) mock_job_instance.return_value = mock_job_client response = "success" mock_job_instance.return_value.get_query_results.return_value = response resp = await hook.get_job_output(job_id=JOB_ID, project_id=PROJECT_ID) assert resp == response @pytest.mark.asyncio @pytest.mark.db_test @mock.patch("google.auth.default") @mock.patch("airflow.providers.google.cloud.hooks.bigquery.Job") async def test_cancel_job_success(self, mock_job, mock_auth_default): mock_credentials = mock.MagicMock(spec=google.auth.compute_engine.Credentials) mock_credentials.token = "ACCESS_TOKEN" mock_auth_default.return_value = (mock_credentials, PROJECT_ID) job_id = "test_job_id" project_id = "test_project" location = "US" mock_job_instance = AsyncMock() mock_job_instance.cancel.return_value = None mock_job.return_value = mock_job_instance await self.hook.cancel_job(job_id=job_id, project_id=project_id, location=location) mock_job_instance.cancel.assert_called_once() @pytest.mark.asyncio @pytest.mark.db_test @mock.patch("google.auth.default") @mock.patch("airflow.providers.google.cloud.hooks.bigquery.Job") async def test_cancel_job_failure(self, mock_job, mock_auth_default): """ Test that BigQueryAsyncHook handles exceptions during job cancellation correctly. """ mock_credentials = mock.MagicMock(spec=google.auth.compute_engine.Credentials) mock_credentials.token = "ACCESS_TOKEN" mock_auth_default.return_value = (mock_credentials, PROJECT_ID) mock_job_instance = AsyncMock() mock_job_instance.cancel.side_effect = Exception("Cancellation failed") mock_job.return_value = mock_job_instance hook = BigQueryAsyncHook() job_id = "test_job_id" project_id = "test_project" location = "US" with pytest.raises(Exception, match="Cancellation failed"): await hook.cancel_job(job_id=job_id, project_id=project_id, location=location) mock_job_instance.cancel.assert_called_once() @pytest.mark.asyncio @mock.patch("airflow.providers.google.cloud.hooks.bigquery.ClientSession") @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryAsyncHook.get_job_instance") async def test_create_job_for_partition_get_with_table(self, mock_job_instance, mock_client_session): hook = BigQueryAsyncHook() mock_job_client = AsyncMock(Job) mock_job_instance.return_value = mock_job_client mock_session = AsyncMock() mock_client_session.return_value.__aenter__.return_value = mock_session expected_query_request = { "query": "SELECT partition_id " f"FROM `{PROJECT_ID}.{DATASET_ID}.INFORMATION_SCHEMA.PARTITIONS`" f" WHERE table_name='{TABLE_ID}'", "useLegacySql": False, } await hook.create_job_for_partition_get( dataset_id=DATASET_ID, table_id=TABLE_ID, project_id=PROJECT_ID ) mock_job_client.query.assert_called_once_with(expected_query_request, mock_session) @pytest.mark.asyncio @mock.patch("airflow.providers.google.cloud.hooks.bigquery.ClientSession") @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryAsyncHook.get_job_instance") async def test_create_job_for_partition_get(self, mock_job_instance, mock_client_session): hook = BigQueryAsyncHook() mock_job_client = AsyncMock(Job) mock_job_instance.return_value = mock_job_client mock_session = AsyncMock() mock_client_session.return_value.__aenter__.return_value = mock_session expected_query_request = { "query": f"SELECT partition_id FROM `{PROJECT_ID}.{DATASET_ID}.INFORMATION_SCHEMA.PARTITIONS`", "useLegacySql": False, } await hook.create_job_for_partition_get(dataset_id=DATASET_ID, project_id=PROJECT_ID) mock_job_client.query.assert_called_once_with(expected_query_request, mock_session) def test_interval_check_for_airflow_exception(self): """ Assert that check return AirflowException """ hook = BigQueryAsyncHook() row1, row2, metrics_thresholds, ignore_zero, ratio_formula = ( None, "0", {"COUNT(*)": 1.5}, True, "max_over_min", ) with pytest.raises(AirflowException): hook.interval_check(row1, row2, metrics_thresholds, ignore_zero, ratio_formula) row1, row2, metrics_thresholds, ignore_zero, ratio_formula = ( "0", None, {"COUNT(*)": 1.5}, True, "max_over_min", ) with pytest.raises(AirflowException): hook.interval_check(row1, row2, metrics_thresholds, ignore_zero, ratio_formula) row1, row2, metrics_thresholds, ignore_zero, ratio_formula = ( "1", "1", {"COUNT(*)": 0}, True, "max_over_min", ) with pytest.raises(AirflowException): hook.interval_check(row1, row2, metrics_thresholds, ignore_zero, ratio_formula) def test_interval_check_for_success(self): """ Assert that check return None """ hook = BigQueryAsyncHook() row1, row2, metrics_thresholds, ignore_zero, ratio_formula = ( "0", "0", {"COUNT(*)": 1.5}, True, "max_over_min", ) response = hook.interval_check(row1, row2, metrics_thresholds, ignore_zero, ratio_formula) assert response is None @pytest.mark.asyncio @mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryAsyncHook.get_job_instance") async def test_get_job_output(self, mock_job_instance): """ Tests to check if a particular object in Google Cloud Storage is found or not """ response = { "kind": "bigquery#tableDataList", "etag": "test_etag", "schema": {"fields": [{"name": "f0_", "type": "INTEGER", "mode": "NULLABLE"}]}, "jobReference": { "projectId": "test_astronomer-airflow-providers", "jobId": "test_jobid", "location": "US", }, "totalRows": "10", "rows": [{"f": [{"v": "42"}, {"v": "monthy python"}]}, {"f": [{"v": "42"}, {"v": "fishy fish"}]}], "totalBytesProcessed": "0", "jobComplete": True, "cacheHit": False, } hook = BigQueryAsyncHook() mock_job_client = AsyncMock(Job) mock_job_instance.return_value = mock_job_client mock_job_client.get_query_results.return_value = response resp = await hook.get_job_output(job_id=JOB_ID, project_id=PROJECT_ID) assert resp == response @pytest.mark.parametrize( ("records", "pass_value", "tolerance"), [(["str"], "str", None), ([2], 2, None), ([0], 2, 1), ([4], 2, 1)], ) def test_value_check_success(self, records, pass_value, tolerance): """ Assert that value_check method execution succeed """ hook = BigQueryAsyncHook() query = "SELECT COUNT(*) from Any" response = hook.value_check(query, pass_value, records, tolerance) assert response is None @pytest.mark.parametrize( ("records", "pass_value", "tolerance"), [([], "", None), (["str"], "str1", None), ([2], 21, None), ([5], 2, 1), (["str"], 2, None)], ) def test_value_check_fail(self, records, pass_value, tolerance): """Assert that check raise AirflowException""" hook = BigQueryAsyncHook() query = "SELECT COUNT(*) from Any" with pytest.raises(AirflowException) as ex: hook.value_check(query, pass_value, records, tolerance) assert isinstance(ex.value, AirflowException) @pytest.mark.parametrize( ("records", "pass_value", "tolerance", "expected"), [ ([2.0], 2.0, None, [True]), ([2.0], 2.1, None, [False]), ([2.0], 2.0, 0.5, [True]), ([1.0], 2.0, 0.5, [True]), ([3.0], 2.0, 0.5, [True]), ([0.9], 2.0, 0.5, [False]), ([3.1], 2.0, 0.5, [False]), ], ) def test_get_numeric_matches(self, records, pass_value, tolerance, expected): """Assert the if response list have all element match with pass_value with tolerance""" assert BigQueryAsyncHook._get_numeric_matches(records, pass_value, tolerance) == expected @pytest.mark.parametrize(("test_input", "expected"), [(5.0, 5.0), (5, 5.0), ("5", 5), ("str", "str")]) def test_convert_to_float_if_possible(self, test_input, expected): """ Assert that type casting succeed for the possible value Otherwise return the same value """ assert BigQueryAsyncHook._convert_to_float_if_possible(test_input) == expected @pytest.mark.db_test @pytest.mark.asyncio @mock.patch("google.auth.default") @mock.patch("aiohttp.client.ClientSession") async def test_get_table_client(self, mock_session, mock_auth_default): """Test get_table_client async function and check whether the return value is a Table instance object""" mock_credentials = mock.MagicMock(spec=google.auth.compute_engine.Credentials) mock_auth_default.return_value = (mock_credentials, PROJECT_ID) hook = BigQueryTableAsyncHook() result = await hook.get_table_client( dataset=DATASET_ID, project_id=PROJECT_ID, table_id=TABLE_ID, session=mock_session ) assert isinstance(result, Table_async) def test_get_records_return_type(self): query_result = { "kind": "bigquery#getQueryResultsResponse", "etag": "test_etag", "schema": { "fields": [ {"name": "f0_", "type": "INTEGER", "mode": "NULLABLE"}, {"name": "f1_", "type": "FLOAT", "mode": "NULLABLE"}, {"name": "f2_", "type": "STRING", "mode": "NULLABLE"}, ] }, "jobReference": { "projectId": "test_airflow-providers", "jobId": "test_jobid", "location": "US", }, "totalRows": "1", "rows": [{"f": [{"v": "22"}, {"v": "3.14"}, {"v": "PI"}]}], "totalBytesProcessed": "0", "jobComplete": True, "cacheHit": False, } hook = BigQueryAsyncHook() result = hook.get_records(query_result) assert isinstance(result[0][0], int) assert isinstance(result[0][1], float) assert isinstance(result[0][2], str) def test_get_records_as_dict(self): query_result = { "kind": "bigquery#getQueryResultsResponse", "etag": "test_etag", "schema": { "fields": [ {"name": "f0_", "type": "INTEGER", "mode": "NULLABLE"}, {"name": "f1_", "type": "FLOAT", "mode": "NULLABLE"}, {"name": "f2_", "type": "STRING", "mode": "NULLABLE"}, ] }, "jobReference": { "projectId": "test_airflow-providers", "jobId": "test_jobid", "location": "US", }, "totalRows": "1", "rows": [{"f": [{"v": "22"}, {"v": "3.14"}, {"v": "PI"}]}], "totalBytesProcessed": "0", "jobComplete": True, "cacheHit": False, } hook = BigQueryAsyncHook() result = hook.get_records(query_result, as_dict=True) assert result == [{"f0_": 22, "f1_": 3.14, "f2_": "PI"}] @pytest.mark.db_test
TestBigQueryAsyncHookMethods
python
celery__celery
t/unit/tasks/test_trace.py
{ "start": 21585, "end": 23214 }
class ____: def test_stackprotection(self): setup_worker_optimizations(self.app) try: @self.app.task(shared=False, bind=True) def foo(self, i): if i: return foo(0) return self.request assert foo(1).called_directly finally: reset_worker_optimizations(self.app) def test_stackprotection_headers_passed_on_new_request_stack(self): setup_worker_optimizations(self.app) try: @self.app.task(shared=False, bind=True) def foo(self, i): if i: return foo.apply(args=(i-1,), headers=456) return self.request task = foo.apply(args=(2,), headers=123, loglevel=5) assert task.result.result.result.args == (0,) assert task.result.result.result.headers == 456 assert task.result.result.result.loglevel == 0 finally: reset_worker_optimizations(self.app) def test_stackprotection_headers_persisted_calling_task_directly(self): setup_worker_optimizations(self.app) try: @self.app.task(shared=False, bind=True) def foo(self, i): if i: return foo(i-1) return self.request task = foo.apply(args=(2,), headers=123, loglevel=5) assert task.result.args == (0,) assert task.result.headers == 123 assert task.result.loglevel == 5 finally: reset_worker_optimizations(self.app)
test_stackprotection
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_table_via_select.py
{ "start": 808, "end": 21706 }
class ____(fixtures.TablesTest): __sparse_driver_backend__ = True @classmethod def temp_table_name(cls): return get_temp_table_name( config, config.db, f"user_tmp_{config.ident}" ) @classmethod def temp_view_name(cls): return get_temp_table_name( config, config.db, f"user_tmp_view_{config.ident}" ) @classmethod def define_tables(cls, metadata): Table( "source_table", metadata, Column("id", Integer, primary_key=True, autoincrement=False), Column("name", String(50)), Column("value", Integer), ) Table("a", metadata, Column("id", Integer)) Table("b", metadata, Column("id", Integer)) if testing.requires.schemas.enabled: Table( "source_table_s", metadata, Column("id", Integer, primary_key=True, autoincrement=False), Column("name", String(50)), Column("value", Integer), schema=config.test_schema, ) @classmethod def insert_data(cls, connection): table = cls.tables.source_table connection.execute( table.insert(), [ {"id": 1, "name": "alice", "value": 100}, {"id": 2, "name": "bob", "value": 200}, {"id": 3, "name": "charlie", "value": 300}, ], ) a = cls.tables.a b = cls.tables.b connection.execute(a.insert(), [{"id": v} for v in [1, 3]]) connection.execute(b.insert(), [{"id": v} for v in [2, 4]]) if testing.requires.schemas.enabled: table = cls.tables[f"{config.test_schema}.source_table_s"] connection.execute( table.insert(), [ {"id": 1, "name": "alice", "value": 100}, {"id": 2, "name": "bob", "value": 200}, {"id": 3, "name": "charlie", "value": 300}, ], ) @testing.fixture(scope="function", autouse=True) def drop_dest_table(self, connection): for schema in None, config.test_schema: for name in ("dest_table", self.temp_table_name()): if inspect(connection).has_table(name, schema=schema): connection.execute( DropTable(Table(name, MetaData(), schema=schema)) ) for name in ("dest_view", self.temp_view_name()): if inspect(connection).has_table(name, schema=schema): connection.execute( DropView(Table(name, MetaData(), schema=schema)) ) connection.commit() @testing.combinations( ("plain", False, False, False), ( "use_temp", False, True, False, testing.requires.create_temp_table_as, ), ("use_schema", True, False, False, testing.requires.schemas), ("plain", False, False, False), ("use_temp", False, True, True, testing.requires.temporary_views), ("use_schema", True, False, True, testing.requires.schemas), argnames="use_schemas,use_temp,use_view", id_="iaaa", ) def test_without_metadata( self, connection, use_temp, use_schemas, use_view ): source_table = self.tables.source_table if not use_view: tablename = self.temp_table_name() if use_temp else "dest_table" stmt = CreateTableAs( select(source_table.c.id, source_table.c.name).where( source_table.c.value > 100 ), tablename, temporary=bool(use_temp), schema=config.test_schema if use_schemas else None, ) else: if use_schemas: source_table = self.tables[ f"{config.test_schema}.source_table_s" ] tablename = self.temp_view_name() if use_temp else "dest_view" stmt = CreateView( select(source_table.c.id, source_table.c.name).where( source_table.c.value > 100 ), tablename, temporary=bool(use_temp), schema=config.test_schema if use_schemas else None, ) connection.execute(stmt) # Verify we can SELECT from the generated table dest = stmt.table result = connection.execute( select(dest.c.id, dest.c.name).order_by(dest.c.id) ).fetchall() eq_(result, [(2, "bob"), (3, "charlie")]) # Verify reflection works insp = inspect(connection) cols = insp.get_columns( tablename, schema=config.test_schema if use_schemas else None, ) eq_(len(cols), 2) eq_(cols[0]["name"], "id") eq_(cols[1]["name"], "name") # Verify type affinity eq_(cols[0]["type"]._type_affinity, Integer) eq_(cols[1]["type"]._type_affinity, String) @testing.variation( "table_type", [ ("create_table_as", testing.requires.create_table_as), ("select_into", testing.requires.create_table_as), ("create_view", testing.requires.views), ], ) @testing.variation( "use_temp", [ False, ( True, testing.requires.create_temp_table_as + testing.requires.temporary_views, ), ], ) @testing.variation("use_drop_all", [True, False]) def test_with_metadata( self, connection, metadata, use_temp, table_type, use_drop_all, ): source_table = self.tables.source_table select_stmt = select( source_table.c.id, source_table.c.name, source_table.c.value, ).where(source_table.c.value > 100) match table_type: case "create_table_as": tablename = ( self.temp_table_name() if use_temp else "dest_table" ) stmt = CreateTableAs( select_stmt, tablename, metadata=metadata, temporary=bool(use_temp), ) case "select_into": tablename = ( self.temp_table_name() if use_temp else "dest_table" ) stmt = select_stmt.into( tablename, temporary=use_temp, metadata=metadata, ) case "create_view": tablename = self.temp_view_name() if use_temp else "dest_view" stmt = CreateView( select_stmt, tablename, metadata=metadata, temporary=bool(use_temp), ) case _: table_type.fail() # these are metadata attached, create all metadata.create_all(connection) # Verify the generated table is a proper Table object dest = stmt.table assert isinstance(dest, Table) assert dest.metadata is metadata eq_(dest.name, tablename) # SELECT from the generated table - should only have rows with # value > 100 (bob and charlie) result = connection.execute( select(dest.c.id, dest.c.name).order_by(dest.c.id) ).fetchall() eq_(result, [(2, "bob"), (3, "charlie")]) # Drop the table using either metadata.drop_all() or dest.drop() if use_drop_all: metadata.drop_all(connection) else: dest.drop(connection) # Verify it's gone if use_temp: if testing.requires.temp_table_names.enabled: insp = inspect(connection) assert tablename not in insp.get_temp_table_names() else: insp = inspect(connection) if table_type.create_view: assert tablename not in insp.get_view_names() else: assert tablename not in insp.get_table_names() @testing.variation( "table_type", [ ("create_table_as", testing.requires.create_table_as), ("create_view", testing.requires.views), ], ) def test_with_labels(self, connection, table_type): source_table = self.tables.source_table match table_type: case "create_table_as": tablename = "dest_table" stmt = CreateTableAs( select( source_table.c.id.label("user_id"), source_table.c.name.label("user_name"), ), tablename, ) case "create_view": tablename = "dest_view" stmt = CreateView( select( source_table.c.id.label("user_id"), source_table.c.name.label("user_name"), ), tablename, ) case _: table_type.fail() connection.execute(stmt) # Verify column names from labels insp = inspect(connection) cols = insp.get_columns(tablename) eq_(len(cols), 2) eq_(cols[0]["name"], "user_id") eq_(cols[1]["name"], "user_name") # Verify we can query using the labels dest = stmt.table result = connection.execute( select(dest.c.user_id, dest.c.user_name).where(dest.c.user_id == 1) ).fetchall() eq_(result, [(1, "alice")]) @testing.requires.table_ddl_if_exists @testing.requires.create_table_as def test_create_table_as_if_not_exists(self, connection): source_table = self.tables.source_table tablename = "dest_table" stmt = CreateTableAs( select(source_table.c.id).select_from(source_table), tablename, if_not_exists=True, ) insp = inspect(connection) assert tablename not in insp.get_table_names() connection.execute(stmt) insp = inspect(connection) assert tablename in insp.get_table_names() # succeeds even though table exists connection.execute(stmt) @testing.requires.create_or_replace_view def test_create_or_replace_view(self, connection): source_table = self.tables.source_table viewname = "dest_view" # Create initial view that selects all rows stmt = CreateView( select(source_table.c.id).select_from(source_table), viewname, or_replace=True, ) insp = inspect(connection) assert viewname not in insp.get_view_names() connection.execute(stmt) insp = inspect(connection) assert viewname in insp.get_view_names() # Verify initial view returns all 3 rows result = connection.execute(select(stmt.table)).fetchall() eq_(len(result), 3) # Replace view with filtered query (only id > 1) stmt = CreateView( select(source_table.c.id) .select_from(source_table) .where(source_table.c.id > 1), viewname, or_replace=True, ) connection.execute(stmt) # Verify view was replaced - should now return only 2 rows insp = inspect(connection) assert viewname in insp.get_view_names() result = connection.execute(select(stmt.table)).fetchall() eq_(len(result), 2) @testing.requires.materialized_views @testing.variation("use_metadata", [True, False]) def test_create_drop_materialized_view(self, connection, use_metadata): source_table = self.tables.source_table viewname = "dest_mat_view" if use_metadata: # Create with metadata metadata = MetaData() stmt = CreateView( select(source_table.c.id, source_table.c.name).select_from( source_table ), viewname, materialized=True, metadata=metadata, ) else: # Create without metadata stmt = CreateView( select(source_table.c.id, source_table.c.name).select_from( source_table ), viewname, materialized=True, ) insp = inspect(connection) assert viewname not in insp.get_materialized_view_names() if use_metadata: metadata.create_all(connection) else: connection.execute(stmt) insp = inspect(connection) assert viewname in insp.get_materialized_view_names() # Verify materialized view returns data dst_view = stmt.table result = connection.execute(select(dst_view)).fetchall() eq_(len(result), 3) eq_(set(r[0] for r in result), {1, 2, 3}) # Drop materialized view if use_metadata: metadata.drop_all(connection) else: drop_stmt = DropView(dst_view, materialized=True) connection.execute(drop_stmt) insp = inspect(connection) assert viewname not in insp.get_materialized_view_names() @testing.variation( "table_type", [ ("create_table_as", testing.requires.create_table_as), ("create_view", testing.requires.views), ], ) def test_literal_inlining_inside_select(self, connection, table_type): src = self.tables.source_table sel = select( (src.c.id + 1).label("id2"), literal("x").label("tag"), ).select_from(src) match table_type: case "create_table_as": tablename = "dest_table" stmt = CreateTableAs(sel, tablename) case "create_view": tablename = "dest_view" stmt = CreateView(sel, tablename) case _: table_type.fail() connection.execute(stmt) tbl = stmt.table row = connection.execute( select(func.count(), func.min(tbl.c.tag), func.max(tbl.c.tag)) ).first() eq_(row, (3, "x", "x")) @testing.variation( "table_type", [ ("create_table_as", testing.requires.create_table_as), ("create_view", testing.requires.views), ], ) def test_with_bind_param_executes(self, connection, table_type): src = self.tables.source_table sel = ( select(src.c.id, src.c.name) .select_from(src) .where(src.c.name == bindparam("p", value="alice")) ) match table_type: case "create_table_as": tablename = "dest_table" stmt = CreateTableAs(sel, tablename) case "create_view": tablename = "dest_view" stmt = CreateView(sel, tablename) case _: table_type.fail() connection.execute(stmt) tbl = stmt.table row = connection.execute( select(func.count(), func.min(tbl.c.name), func.max(tbl.c.name)) ).first() eq_(row, (1, "alice", "alice")) @testing.variation( "table_type", [ ("create_table_as", testing.requires.create_table_as), ("create_view", testing.requires.views), ], ) def test_compound_select_smoke(self, connection, table_type): a, b = self.tables("a", "b") sel = select(a.c.id).union_all(select(b.c.id)) match table_type: case "create_table_as": tablename = "dest_table" stmt = CreateTableAs(sel, tablename) case "create_view": tablename = "dest_view" stmt = CreateView(sel, tablename) case _: table_type.fail() connection.execute(stmt) vals = ( connection.execute( select(stmt.table.c.id).order_by(stmt.table.c.id) ) .scalars() .all() ) eq_(vals, [1, 2, 3, 4]) @testing.requires.views def test_view_dependencies_with_metadata(self, connection, metadata): """Test that views with dependencies are created/dropped in correct order. This validates that when views are attached to metadata: - create_all() creates base tables first, then dependent views in order - drop_all() drops dependent views first, then base tables in reverse order """ # Create three base tables table1 = Table( "base_table1", metadata, Column("id", Integer, primary_key=True, autoincrement=False), Column("value", Integer), ) table2 = Table( "base_table2", metadata, Column("id", Integer, primary_key=True, autoincrement=False), Column("amount", Integer), ) table3 = Table( "base_table3", metadata, Column("id", Integer, primary_key=True, autoincrement=False), Column("total", Integer), ) # First view depends on table1 and table2 view1_stmt = CreateView( select( table1.c.id, table1.c.value, table2.c.amount, ) .select_from(table1.join(table2, table1.c.id == table2.c.id)) .where(table1.c.value > 0), "view1", metadata=metadata, ) # Second view depends on table3 and view1 view2_stmt = CreateView( select( view1_stmt.table.c.id, view1_stmt.table.c.value, table3.c.total, ) .select_from( view1_stmt.table.join( table3, view1_stmt.table.c.id == table3.c.id ) ) .where(table3.c.total > 100), "view2", metadata=metadata, ) # Verify metadata knows about all objects eq_( {"base_table1", "base_table2", "base_table3", "view1", "view2"}, set(metadata.tables), ) # Create all in correct dependency order metadata.create_all(connection) # Verify all tables and views were created insp = inspect(connection) assert {"base_table1", "base_table2", "base_table3"}.issubset( insp.get_table_names() ) assert {"view1", "view2"}.issubset(insp.get_view_names()) # Insert test data connection.execute( table1.insert(), [ {"id": 1, "value": 10}, {"id": 2, "value": 20}, {"id": 3, "value": 30}, ], ) connection.execute( table2.insert(), [ {"id": 1, "amount": 100}, {"id": 2, "amount": 200}, {"id": 3, "amount": 300}, ], ) connection.execute( table3.insert(), [ {"id": 1, "total": 50}, {"id": 2, "total": 150}, {"id": 3, "total": 250}, ], ) # Query view1 to verify it works view1_results = connection.execute( select(view1_stmt.table).order_by(view1_stmt.table.c.id) ).fetchall() eq_( view1_results, [ (1, 10, 100), (2, 20, 200), (3, 30, 300), ], ) # Query view2 to verify it works (should filter total > 100) view2_results = connection.execute( select(view2_stmt.table).order_by(view2_stmt.table.c.id) ).fetchall() eq_( view2_results, [ (2, 20, 150), (3, 30, 250), ], ) # Drop all in correct reverse dependency order metadata.drop_all(connection) # Verify all tables and views were dropped insp = inspect(connection) assert {"base_table1", "base_table2", "base_table3"}.isdisjoint( insp.get_table_names() ) assert {"view1", "view2"}.isdisjoint(insp.get_view_names())
TableViaSelectTest
python
hynek__structlog
tests/test_stdlib.py
{ "start": 1788, "end": 4860 }
class ____: def setup_method(self, method): """ The stdlib logger factory modifies global state to fix caller identification. """ self.original_logger = logging.getLoggerClass() def teardown_method(self, method): logging.setLoggerClass(self.original_logger) def test_deduces_correct_name(self): """ The factory isn't called directly but from structlog._config so deducing has to be slightly smarter. """ assert "tests.additional_frame" == ( additional_frame(LoggerFactory()).name ) assert "tests.test_stdlib" == LoggerFactory()().name def test_ignores_frames(self): """ The name guesser walks up the frames until it reaches a frame whose name is not from structlog or one of the configurable other names. """ # Compute the names to __main__ so it doesn't get thrown off if people # install plugins that alter the frames. E.g. #370 names = set() f = sys._getframe() while f.f_globals["__name__"] != "__main__": names.add(f.f_globals["__name__"].split(".", 1)[0]) f = f.f_back assert ( "__main__" == additional_frame( LoggerFactory(ignore_frame_names=list(names)) ).name ) def test_deduces_correct_caller(self): """ It will find the correct caller. """ logger = _FixedFindCallerLogger("test") file_name, _line_number, func_name = logger.findCaller()[:3] assert file_name == os.path.realpath(__file__) assert func_name == "test_deduces_correct_caller" def test_stack_info(self): """ If we ask for stack_info, it will returned. """ logger = _FixedFindCallerLogger("test") testing, is_, fun, stack_info = logger.findCaller(stack_info=True) # noqa: RUF059 assert "testing, is_, fun" in stack_info def test_no_stack_info_by_default(self): """ If we don't ask for stack_info, it won't be returned. """ logger = _FixedFindCallerLogger("test") testing, is_, fun, stack_info = logger.findCaller() # noqa: RUF059 assert None is stack_info def test_find_caller(self, caplog): """ The caller is found. """ logger = LoggerFactory()() logger.error("Test") assert caplog.text.startswith( "ERROR tests.test_stdlib:test_stdlib.py" ) def test_sets_correct_logger(self): """ Calling LoggerFactory ensures that Logger.findCaller gets patched. """ LoggerFactory() assert logging.getLoggerClass() is _FixedFindCallerLogger def test_positional_argument_avoids_guessing(self): """ If a positional argument is passed to the factory, it's used as the name instead of guessing. """ lf = LoggerFactory()("foo") assert "foo" == lf.name
TestLoggerFactory
python
getsentry__sentry
src/sentry/grouping/enhancer/matchers.py
{ "start": 10920, "end": 10973 }
class ____(PathLikeMatch): field = "path"
PathMatch
python
sphinx-doc__sphinx
tests/roots/test-ext-imgmockconverter/mocksvgconverter.py
{ "start": 343, "end": 939 }
class ____(ImageConverter): conversion_rules = [ ('image/svg+xml', 'application/pdf'), ] def is_available(self) -> bool: return True def convert( self, _from: str | os.PathLike[str], _to: str | os.PathLike[str] ) -> bool: """Mock converts the image from SVG to PDF.""" shutil.copyfile(_from, _to) return True def setup(app: Sphinx) -> ExtensionMetadata: app.add_post_transform(MyConverter) return { 'version': 'builtin', 'parallel_read_safe': True, 'parallel_write_safe': True, }
MyConverter
python
PyCQA__pylint
tests/functional/a/arguments.py
{ "start": 354, "end": 2500 }
class ____: """Test class for method invocations.""" @staticmethod def static_method(arg): """static method.""" return arg + arg @classmethod def class_method(cls, arg): """class method""" return arg + arg def method(self, arg): """method.""" return (self, arg) @decorator def decorated_method(self, arg): """decorated method.""" return (self, arg) def function_1_arg(first_argument): """one argument function""" return first_argument def function_3_args(first_argument, second_argument, third_argument): """three arguments function""" return first_argument, second_argument, third_argument def function_default_arg(one=1, two=2): """function with default value""" return two, one function_1_arg(420) function_1_arg() # [no-value-for-parameter] function_1_arg(1337, 347) # [too-many-function-args] function_3_args(420, 789) # [no-value-for-parameter] # +1:[no-value-for-parameter,no-value-for-parameter,no-value-for-parameter] function_3_args() function_3_args(1337, 347, 456) function_3_args('bab', 'bebe', None, 5.6) # [too-many-function-args] function_default_arg(1, two=5) function_default_arg(two=5) function_1_arg(bob=4) # [unexpected-keyword-arg,no-value-for-parameter] function_default_arg(1, 4, coin="hello") # [unexpected-keyword-arg] function_default_arg(1, one=5) # [redundant-keyword-arg] # Remaining tests are for coverage of correct names in messages. my_lambda = lambda arg: 1 my_lambda() # [no-value-for-parameter] def method_tests(): """Method invocations.""" demo = DemoClass() demo.static_method() # [no-value-for-parameter] DemoClass.static_method() # [no-value-for-parameter] demo.class_method() # [no-value-for-parameter] DemoClass.class_method() # [no-value-for-parameter] demo.method() # [no-value-for-parameter] DemoClass.method(demo) # [no-value-for-parameter] demo.decorated_method() # [no-value-for-parameter] DemoClass.decorated_method(demo) # [no-value-for-parameter] # Test a regression (issue #234) import sys
DemoClass
python
celery__celery
celery/utils/graph.py
{ "start": 650, "end": 6391 }
class ____: """A directed acyclic graph of objects and their dependencies. Supports a robust topological sort to detect the order in which they must be handled. Takes an optional iterator of ``(obj, dependencies)`` tuples to build the graph from. Warning: Does not support cycle detection. """ def __init__(self, it=None, formatter=None): self.formatter = formatter or GraphFormatter() self.adjacent = {} if it is not None: self.update(it) def add_arc(self, obj): """Add an object to the graph.""" self.adjacent.setdefault(obj, []) def add_edge(self, A, B): """Add an edge from object ``A`` to object ``B``. I.e. ``A`` depends on ``B``. """ self[A].append(B) def connect(self, graph): """Add nodes from another graph.""" self.adjacent.update(graph.adjacent) def topsort(self): """Sort the graph topologically. Returns: List: of objects in the order in which they must be handled. """ graph = DependencyGraph() components = self._tarjan72() NC = { node: component for component in components for node in component } for component in components: graph.add_arc(component) for node in self: node_c = NC[node] for successor in self[node]: successor_c = NC[successor] if node_c != successor_c: graph.add_edge(node_c, successor_c) return [t[0] for t in graph._khan62()] def valency_of(self, obj): """Return the valency (degree) of a vertex in the graph.""" try: l = [len(self[obj])] except KeyError: return 0 for node in self[obj]: l.append(self.valency_of(node)) return sum(l) def update(self, it): """Update graph with data from a list of ``(obj, deps)`` tuples.""" tups = list(it) for obj, _ in tups: self.add_arc(obj) for obj, deps in tups: for dep in deps: self.add_edge(obj, dep) def edges(self): """Return generator that yields for all edges in the graph.""" return (obj for obj, adj in self.items() if adj) def _khan62(self): """Perform Khan's simple topological sort algorithm from '62. See https://en.wikipedia.org/wiki/Topological_sorting """ count = Counter() result = [] for node in self: for successor in self[node]: count[successor] += 1 ready = [node for node in self if not count[node]] while ready: node = ready.pop() result.append(node) for successor in self[node]: count[successor] -= 1 if count[successor] == 0: ready.append(successor) result.reverse() return result def _tarjan72(self): """Perform Tarjan's algorithm to find strongly connected components. See Also: :wikipedia:`Tarjan%27s_strongly_connected_components_algorithm` """ result, stack, low = [], [], {} def visit(node): if node in low: return num = len(low) low[node] = num stack_pos = len(stack) stack.append(node) for successor in self[node]: visit(successor) low[node] = min(low[node], low[successor]) if num == low[node]: component = tuple(stack[stack_pos:]) stack[stack_pos:] = [] result.append(component) for item in component: low[item] = len(self) for node in self: visit(node) return result def to_dot(self, fh, formatter=None): """Convert the graph to DOT format. Arguments: fh (IO): A file, or a file-like object to write the graph to. formatter (celery.utils.graph.GraphFormatter): Custom graph formatter to use. """ seen = set() draw = formatter or self.formatter def P(s): print(bytes_to_str(s), file=fh) def if_not_seen(fun, obj): if draw.label(obj) not in seen: P(fun(obj)) seen.add(draw.label(obj)) P(draw.head()) for obj, adjacent in self.items(): if not adjacent: if_not_seen(draw.terminal_node, obj) for req in adjacent: if_not_seen(draw.node, obj) P(draw.edge(obj, req)) P(draw.tail()) def format(self, obj): return self.formatter(obj) if self.formatter else obj def __iter__(self): return iter(self.adjacent) def __getitem__(self, node): return self.adjacent[node] def __len__(self): return len(self.adjacent) def __contains__(self, obj): return obj in self.adjacent def _iterate_items(self): return self.adjacent.items() items = iteritems = _iterate_items def __repr__(self): return '\n'.join(self.repr_node(N) for N in self) def repr_node(self, obj, level=1, fmt='{0}({1})'): output = [fmt.format(obj, self.valency_of(obj))] if obj in self: for other in self[obj]: d = fmt.format(other, self.valency_of(other)) output.append(' ' * level + d) output.extend(self.repr_node(other, level + 1).split('\n')[1:]) return '\n'.join(output)
DependencyGraph
python
pyca__cryptography
src/cryptography/hazmat/primitives/hashes.py
{ "start": 2975, "end": 3087 }
class ____(HashAlgorithm): # noqa: N801 name = "sha3-256" digest_size = 32 block_size = None
SHA3_256