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
kamyu104__LeetCode-Solutions
Python/minimum-sum-of-mountain-triplets-i.py
{ "start": 657, "end": 1342 }
class ____(object): def minimumSum(self, nums): """ :type nums: List[int] :rtype: int """ INF = float("inf") left = [INF]*len(nums) curr = INF for i in xrange(len(nums)): left[i] = curr curr = min(curr, nums[i]) right = [INF]*len(nums) curr = INF for i in reversed(xrange(len(nums))): right[i] = curr curr = min(curr, nums[i]) result = INF for i in xrange(len(nums)): if left[i] < nums[i] > right[i]: result = min(result, left[i]+nums[i]+right[i]) return result if result != INF else -1
Solution2
python
huggingface__transformers
src/transformers/modeling_gguf_pytorch_utils.py
{ "start": 7840, "end": 8486 }
class ____(TensorProcessor): def __init__(self, config=None): super().__init__(config=config) def process(self, weights, name, **kwargs): if "ssm_conv1d.weight" in name: # for compatibility tensor ssm_conv1d must be (5120, 1, 4]) dim, # quantized one is (5120, 4) weights = np.expand_dims(weights, axis=1) if "ssm_a" in name: # Original exponential implementation # https://github.com/ggerganov/llama.cpp/blob/master/convert_hf_to_gguf.py#L2975-L2977 weights = np.log(-weights) return GGUFTensor(weights, name, {})
MambaTensorProcessor
python
openai__openai-python
src/openai/types/chat/chat_completion_chunk.py
{ "start": 2658, "end": 3503 }
class ____(BaseModel): delta: ChoiceDelta """A chat completion delta generated by streamed model responses.""" finish_reason: Optional[Literal["stop", "length", "tool_calls", "content_filter", "function_call"]] = None """The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, `length` if the maximum number of tokens specified in the request was reached, `content_filter` if content was omitted due to a flag from our content filters, `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function. """ index: int """The index of the choice in the list of choices.""" logprobs: Optional[ChoiceLogprobs] = None """Log probability information for the choice."""
Choice
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_default_row06.py
{ "start": 315, "end": 916 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("default_row06.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.set_default_row(24) worksheet.set_row(4, 15) worksheet.write("A1", "Foo") worksheet.write("A10", "Bar") workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
aio-libs__aiohttp
aiohttp/tracing.py
{ "start": 9473, "end": 9609 }
class ____: """Parameters sent by the `on_dns_cache_miss` signal""" host: str @frozen_dataclass_decorator
TraceDnsCacheMissParams
python
ray-project__ray
python/ray/serve/_private/benchmarks/streaming/streaming_http_throughput.py
{ "start": 332, "end": 756 }
class ____: def __init__(self, tokens_per_request: int): logging.getLogger("ray.serve").setLevel(logging.WARNING) self._tokens_per_request = tokens_per_request async def stream(self): for i in range(self._tokens_per_request): yield "hi" def __call__(self, *args): return StreamingResponse(self.stream()) @serve.deployment(ray_actor_options={"num_cpus": 0})
Downstream
python
numpy__numpy
numpy/linalg/lapack_lite/make_lite.py
{ "start": 1698, "end": 2361 }
class ____: """Wrapper for a Fortran routine in a file. """ type = 'generic' def __init__(self, name=None, filename=None): self.filename = filename if name is None: root, ext = os.path.splitext(filename) name = root self.name = name self._dependencies = None def dependencies(self): if self._dependencies is None: deps = fortran.getDependencies(self.filename) self._dependencies = [d.lower() for d in deps] return self._dependencies def __repr__(self): return f"FortranRoutine({self.name!r}, filename={self.filename!r})"
FortranRoutine
python
airbytehq__airbyte
airbyte-ci/connectors/metadata_service/lib/metadata_service/models/generated/ConnectorBuildOptions.py
{ "start": 182, "end": 306 }
class ____(BaseModel): class Config: extra = Extra.forbid baseImage: Optional[str] = None
ConnectorBuildOptions
python
donnemartin__interactive-coding-challenges
recursion_dynamic/magic_index/test_find_magic_index.py
{ "start": 18, "end": 753 }
class ____(unittest.TestCase): def test_find_magic_index(self): magic_index = MagicIndex() self.assertEqual(magic_index.find_magic_index(None), -1) self.assertEqual(magic_index.find_magic_index([]), -1) array = [-4, -2, 2, 6, 6, 6, 6, 10] self.assertEqual(magic_index.find_magic_index(array), 2) array = [-4, -2, 1, 6, 6, 6, 6, 10] self.assertEqual(magic_index.find_magic_index(array), 6) array = [-4, -2, 1, 6, 6, 6, 7, 10] self.assertEqual(magic_index.find_magic_index(array), -1) print('Success: test_find_magic') def main(): test = TestFindMagicIndex() test.test_find_magic_index() if __name__ == '__main__': main()
TestFindMagicIndex
python
astropy__astropy
astropy/io/fits/diff.py
{ "start": 6057, "end": 15791 }
class ____(_BaseDiff): """Diff two FITS files by filename, or two `HDUList` objects. `FITSDiff` objects have the following diff attributes: - ``diff_hdu_count``: If the FITS files being compared have different numbers of HDUs, this contains a 2-tuple of the number of HDUs in each file. - ``diff_hdus``: If any HDUs with the same index are different, this contains a list of 2-tuples of the HDU index and the `HDUDiff` object representing the differences between the two HDUs. """ def __init__( self, a, b, ignore_hdus=[], ignore_keywords=[], ignore_comments=[], ignore_fields=[], numdiffs=10, rtol=0.0, atol=0.0, ignore_blanks=True, ignore_blank_cards=True, ): """ Parameters ---------- a : str or `HDUList` The filename of a FITS file on disk, or an `HDUList` object. b : str or `HDUList` The filename of a FITS file on disk, or an `HDUList` object to compare to the first file. ignore_hdus : sequence, optional HDU names to ignore when comparing two FITS files or HDU lists; the presence of these HDUs and their contents are ignored. Wildcard strings may also be included in the list. ignore_keywords : sequence, optional Header keywords to ignore when comparing two headers; the presence of these keywords and their values are ignored. Wildcard strings may also be included in the list. ignore_comments : sequence, optional A list of header keywords whose comments should be ignored in the comparison. May contain wildcard strings as with ignore_keywords. ignore_fields : sequence, optional The (case-insensitive) names of any table columns to ignore if any table data is to be compared. numdiffs : int, optional The number of pixel/table values to output when reporting HDU data differences. Though the count of differences is the same either way, this allows controlling the number of different values that are kept in memory or output. If a negative value is given, then numdiffs is treated as unlimited (default: 10). rtol : float, optional The relative difference to allow when comparing two float values either in header values, image arrays, or table columns (default: 0.0). Values which satisfy the expression .. math:: \\left| a - b \\right| > \\text{atol} + \\text{rtol} \\cdot \\left| b \\right| are considered to be different. The underlying function used for comparison is `numpy.allclose`. .. versionadded:: 2.0 atol : float, optional The allowed absolute difference. See also ``rtol`` parameter. .. versionadded:: 2.0 ignore_blanks : bool, optional Ignore extra whitespace at the end of string values either in headers or data. Extra leading whitespace is not ignored (default: True). ignore_blank_cards : bool, optional Ignore all cards that are blank, i.e. they only contain whitespace (default: True). """ if isinstance(a, (str, os.PathLike)): try: a = fitsopen(a) except Exception as exc: raise OSError(f"error opening file a ({a})") from exc close_a = True else: close_a = False if isinstance(b, (str, os.PathLike)): try: b = fitsopen(b) except Exception as exc: raise OSError(f"error opening file b ({b})") from exc close_b = True else: close_b = False # Normalize keywords/fields to ignore to upper case self.ignore_hdus = {k.upper() for k in ignore_hdus} self.ignore_keywords = {k.upper() for k in ignore_keywords} self.ignore_comments = {k.upper() for k in ignore_comments} self.ignore_fields = {k.upper() for k in ignore_fields} self.numdiffs = numdiffs self.rtol = rtol self.atol = atol self.ignore_blanks = ignore_blanks self.ignore_blank_cards = ignore_blank_cards # Some hdu names may be pattern wildcards. Find them. self.ignore_hdu_patterns = set() for name in list(self.ignore_hdus): if name != "*" and glob.has_magic(name): self.ignore_hdus.remove(name) self.ignore_hdu_patterns.add(name) self.diff_hdu_count = () self.diff_hdus = [] try: super().__init__(a, b) finally: if close_a: a.close() if close_b: b.close() def _diff(self): if len(self.a) != len(self.b): self.diff_hdu_count = (len(self.a), len(self.b)) # Record filenames for use later in _report self.filenamea = self.a.filename() if not self.filenamea: self.filenamea = f"<{self.a.__class__.__name__} object at {id(self.a):#x}>" self.filenameb = self.b.filename() if not self.filenameb: self.filenameb = f"<{self.b.__class__.__name__} object at {id(self.b):#x}>" if self.ignore_hdus: self.a = HDUList([h for h in self.a if h.name not in self.ignore_hdus]) self.b = HDUList([h for h in self.b if h.name not in self.ignore_hdus]) if self.ignore_hdu_patterns: a_names = [hdu.name for hdu in self.a] b_names = [hdu.name for hdu in self.b] for pattern in self.ignore_hdu_patterns: a_ignored = fnmatch.filter(a_names, pattern) self.a = HDUList([h for h in self.a if h.name not in a_ignored]) b_ignored = fnmatch.filter(b_names, pattern) self.b = HDUList([h for h in self.b if h.name not in b_ignored]) # For now, just compare the extensions one by one in order. # Might allow some more sophisticated types of diffing later. # TODO: Somehow or another simplify the passing around of diff # options--this will become important as the number of options grows for idx in range(min(len(self.a), len(self.b))): hdu_diff = HDUDiff.fromdiff(self, self.a[idx], self.b[idx]) if not hdu_diff.identical: if ( self.a[idx].name == self.b[idx].name and self.a[idx].ver == self.b[idx].ver ): self.diff_hdus.append( (idx, hdu_diff, self.a[idx].name, self.a[idx].ver) ) else: self.diff_hdus.append((idx, hdu_diff, "", self.a[idx].ver)) def _report(self): wrapper = textwrap.TextWrapper(initial_indent=" ", subsequent_indent=" ") self._fileobj.write("\n") self._writeln(f" fitsdiff: {__version__}") self._writeln(f" a: {self.filenamea}\n b: {self.filenameb}") if self.ignore_hdus: ignore_hdus = " ".join(sorted(self.ignore_hdus)) self._writeln(" HDU(s) not to be compared:\n" + wrapper.fill(ignore_hdus)) if self.ignore_hdu_patterns: ignore_hdu_patterns = " ".join(sorted(self.ignore_hdu_patterns)) self._writeln( " HDU(s) not to be compared:\n" + wrapper.fill(ignore_hdu_patterns) ) if self.ignore_keywords: ignore_keywords = " ".join(sorted(self.ignore_keywords)) self._writeln( " Keyword(s) not to be compared:\n" + wrapper.fill(ignore_keywords) ) if self.ignore_comments: ignore_comments = " ".join(sorted(self.ignore_comments)) self._writeln( " Keyword(s) whose comments are not to be compared:\n" + wrapper.fill(ignore_comments) ) if self.ignore_fields: ignore_fields = " ".join(sorted(self.ignore_fields)) self._writeln( " Table column(s) not to be compared:\n" + wrapper.fill(ignore_fields) ) self._writeln( f" Maximum number of different data values to be reported: {self.numdiffs}" ) self._writeln( f" Relative tolerance: {self.rtol}, Absolute tolerance: {self.atol}" ) if self.diff_hdu_count: self._fileobj.write("\n") self._writeln("Files contain different numbers of HDUs:") self._writeln(f" a: {self.diff_hdu_count[0]}") self._writeln(f" b: {self.diff_hdu_count[1]}") if not self.diff_hdus: self._writeln("No differences found between common HDUs.") return elif not self.diff_hdus: self._fileobj.write("\n") self._writeln("No differences found.") return for idx, hdu_diff, extname, extver in self.diff_hdus: # print out the extension heading if idx == 0: self._fileobj.write("\n") self._writeln("Primary HDU:") else: self._fileobj.write("\n") if extname: self._writeln(f"Extension HDU {idx} ({extname}, {extver}):") else: self._writeln(f"Extension HDU {idx}:") hdu_diff.report(self._fileobj, indent=self._indent + 1)
FITSDiff
python
sphinx-doc__sphinx
tests/test_search.py
{ "start": 942, "end": 1377 }
class ____: def __init__(self, version: str, domains: DummyDomainsContainer) -> None: self.version = version self.domains = domains def __getattr__(self, name: str) -> Any: if name.startswith('_search_index_'): setattr(self, name, {}) return getattr(self, name, {}) def __str__(self) -> str: return f'DummyEnvironment({self.version!r}, {self.domains!r})'
DummyEnvironment
python
pydantic__pydantic
pydantic/v1/errors.py
{ "start": 16080, "end": 16178 }
class ____(PydanticValueError): msg_template = 'value is not a valid color: {reason}'
ColorError
python
donnemartin__system-design-primer
solutions/system_design/social_graph/social_graph_snippets.py
{ "start": 78, "end": 133 }
class ____(Enum): unvisited = 0 visited = 1
State
python
walkccc__LeetCode
solutions/823. Binary Trees With Factors/823.py
{ "start": 0, "end": 578 }
class ____: def numFactoredBinaryTrees(self, arr: list[int]) -> int: MOD = 1_000_000_007 n = len(arr) # dp[i] := the number of binary trees with arr[i] as the root dp = [1] * n arr.sort() numToIndex = {a: i for i, a in enumerate(arr)} for i, root in enumerate(arr): # arr[i] is the root for j in range(i): if root % arr[j] == 0: # arr[j] is the left subtree right = root // arr[j] if right in numToIndex: dp[i] += dp[j] * dp[numToIndex[right]] dp[i] %= MOD return sum(dp) % MOD
Solution
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF033.py
{ "start": 435, "end": 575 }
class ____: def __something_else__(self, bar = 11, baz = 11) -> None: ... # OK def __post_init__(foo: bool = True) -> None: ... # OK
Foo
python
numba__numba
numba/tests/test_gdb_dwarf.py
{ "start": 2196, "end": 9269 }
class ____(TestCase): # Tests the logic in numba.misc.gdb_print_extension.NumbaArrayPrinter # it's quite involved and susceptible to changes to the string # representation of Numba array and dtypes as it parses these # representations and recreates NumPy array/dtypes based on them! def setUp(self): # Patch sys.modules with mock gdb modules such that the # numba.misc.gdb_print_extension can import ok, the rest of the gdb # classes etc are implemented later mock_modules = {'gdb': Mock(), 'gdb.printing': Mock()} self.patched_sys = patch.dict('sys.modules', mock_modules) self.patched_sys.start() # Now sys.modules has a gdb in it, patch the gdb.selected_inferior. # This function should return a process wrapping object that has a # read_memory method that can read a memory region from a given address # in the process' address space. import gdb class SelectedInferior(): def read_memory(self, data, extent): buf = (ct.c_char * extent).from_address(data) return buf.raw # this is bytes si = SelectedInferior() gdb.configure_mock(**{'selected_inferior': lambda :si}) def tearDown(self): # drop the sys.modules patch self.patched_sys.stop() def get_gdb_repr(self, array): # Returns the gdb repr of an array as reconstructed via the # gdb_print_extension (should be the same as NumPy!). # This is the module being tested, it uses gdb and gdb.printing, both # of which are mocked in self.setUp() from numba.misc import gdb_print_extension # The following classes are ducks for the gdb classes (which are not # easily/guaranteed importable from the test suite). They implement the # absolute bare minimum necessary to test the gdb_print_extension. class DISubrange(): def __init__(self, lo, hi): self._lo = lo self._hi = hi @property def type(self): return self def range(self): return self._lo, self._hi class DW_TAG_array_type(): def __init__(self, lo, hi): self._lo, self._hi = lo, hi def fields(self): return [DISubrange(self._lo, self._hi),] class DIDerivedType_tuple(): def __init__(self, the_tuple): self._type = DW_TAG_array_type(0, len(the_tuple) - 1) self._tuple = the_tuple @property def type(self): return self._type def __getitem__(self, item): return self._tuple[item] class DICompositeType_Array(): def __init__(self, arr, type_str): self._arr = arr self._type_str = type_str def __getitem__(self, item): return getattr(self, item) @property def data(self): return self._arr.ctypes.data @property def itemsize(self): return self._arr.itemsize @property def shape(self): return DIDerivedType_tuple(self._arr.shape) @property def strides(self): return DIDerivedType_tuple(self._arr.strides) @property def type(self): return self._type_str # The type string encoded into the DWARF is the string repr of the Numba # type followed by the LLVM repr of the data model in brackets. dmm = datamodel.default_manager array_model = datamodel.models.ArrayModel(dmm, typeof(array)) data_type = array_model.get_data_type() type_str = f"{typeof(array)} ({data_type.structure_repr()})" fake_gdb_arr = DICompositeType_Array(array, type_str) printer = gdb_print_extension.NumbaArrayPrinter(fake_gdb_arr) return printer.to_string().strip() # strip, there's new lines def check(self, array): gdb_printed = self.get_gdb_repr(array) self.assertEqual(str(gdb_printed), str(array)) def test_np_array_printer_simple_numeric_types(self): # Tests printer over a selection of basic types n = 4 m = 3 for dt in (np.int8, np.uint16, np.int64, np.float32, np.complex128): arr = np.arange(m * n, dtype=dt).reshape(m, n) self.check(arr) def test_np_array_printer_simple_numeric_types_strided(self): # Tests printer over randomized strided arrays n_tests = 30 np.random.seed(0) for _ in range(n_tests): shape = np.random.randint(1, high=12, size=np.random.randint(1, 5)) tmp = np.arange(np.prod(shape)).reshape(shape) slices = [] for x in shape: start = np.random.randint(0, x) # x + 3 is to ensure that sometimes the stop is beyond the # end of the size in a given dimension stop = np.random.randint(start + 1, max(start + 1, x + 3)) step = np.random.randint(1, 3) # step as 1, 2 strd = slice(start, stop, step) slices.append(strd) arr = tmp[tuple(slices)] self.check(arr) def test_np_array_printer_simple_structured_dtype(self): # Tests printer over a selection of basic types n = 4 m = 3 aligned = np.dtype([("x", np.int16), ("y", np.float64)], align=True) unaligned = np.dtype([("x", np.int16), ("y", np.float64)], align=False) for dt in (aligned, unaligned): arr = np.empty(m * n, dtype=dt).reshape(m, n) arr['x'] = np.arange(m * n, dtype=dt['x']).reshape(m, n) arr['y'] = 100 * np.arange(m * n, dtype=dt['y']).reshape(m, n) self.check(arr) def test_np_array_printer_chr_array(self): # Test unichr array arr = np.array(['abcde']) self.check(arr) def test_np_array_printer_unichr_structured_dtype(self): # Not supported yet n = 4 m = 3 dt = np.dtype([("x", '<U5'), ("y", np.float64)], align=True) arr = np.zeros(m * n, dtype=dt).reshape(m, n) rep = self.get_gdb_repr(arr) self.assertIn("array[Exception:", rep) self.assertIn("Unsupported sub-type", rep) self.assertIn("[unichr x 5]", rep) def test_np_array_printer_nested_array_structured_dtype(self): # Not supported yet n = 4 m = 3 dt = np.dtype([("x", np.int16, (2,)), ("y", np.float64)], align=True) arr = np.zeros(m * n, dtype=dt).reshape(m, n) rep = self.get_gdb_repr(arr) self.assertIn("array[Exception:", rep) self.assertIn("Unsupported sub-type", rep) self.assertIn("nestedarray(int16", rep) if __name__ == '__main__': unittest.main()
TestGDBPrettyPrinterLogic
python
tensorflow__tensorflow
tensorflow/compiler/tests/argminmax_test.py
{ "start": 987, "end": 3809 }
class ____(xla_test.XLATestCase): def _assertOpOutputMatchesExpected(self, op, axis, output_type, op_input, expected): """Verifies that 'op' produces 'expected' when fed input 'op_input' . Args: op: argmin or argmax operator to test. axis: integer axis to reduce across. output_type: numpy datatype of the output to produce. op_input: numpy input array to use as input to 'op'. expected: numpy array representing the expected output of 'op'. """ with self.session() as session: with self.test_scope(): pinp = array_ops.placeholder( dtypes.as_dtype(op_input.dtype), op_input.shape, name="a") output = op(pinp, axis=axis, output_type=output_type) result = session.run(output, {pinp: op_input}) self.assertAllEqual(result, expected) def testArgMinMax(self): # Complex numbers do not support argmin/argmax. minmax_types = self.all_types & {np.int32, np.int64} for dtype in self.int_types | self.float_types: # output_type is a numpy data type that is used to specify the desired # output type of the op as well as to convert the Python number to the # array scalar of the type. for output_type in minmax_types: self._assertOpOutputMatchesExpected( math_ops.argmax, axis=0, output_type=output_type, op_input=np.array([1, 10, 27, 3, 3, 4], dtype=dtype), expected=output_type(2)) self._assertOpOutputMatchesExpected( math_ops.argmax, axis=0, output_type=output_type, op_input=np.array([[4, 1, 7], [3, 2, 4]], dtype=dtype), expected=np.array([0, 1, 0], dtype=output_type)) self._assertOpOutputMatchesExpected( math_ops.argmax, axis=1, output_type=output_type, op_input=np.array([[4, 1], [3, 2]], dtype=dtype), expected=np.array([0, 0], dtype=output_type)) self._assertOpOutputMatchesExpected( math_ops.argmin, axis=0, output_type=output_type, op_input=np.array([3, 10, 27, 3, 2, 4], dtype=dtype), expected=output_type(4)) self._assertOpOutputMatchesExpected( math_ops.argmin, axis=0, output_type=output_type, op_input=np.array([[4, 1, 7], [3, 2, 4]], dtype=dtype), expected=np.array([1, 0, 1], dtype=output_type)) self._assertOpOutputMatchesExpected( math_ops.argmin, axis=1, output_type=output_type, op_input=np.array([[4, 1], [3, 2]], dtype=dtype), expected=np.array([1, 1], dtype=output_type)) if __name__ == "__main__": test.main()
ArgMinMaxTest
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP008.py
{ "start": 7048, "end": 7228 }
class ____(B): def f(self): __class__ = B # Local variable __class__ shadows the implicit __class__ return super(__class__, self).f() # Should NOT trigger UP008
C
python
great-expectations__great_expectations
great_expectations/datasource/fluent/data_connector/filesystem_data_connector.py
{ "start": 574, "end": 7982 }
class ____(FilePathDataConnector): """Extension of FilePathDataConnector used to connect to Filesystem (local, networked file storage (NFS), DBFS, etc.). Args: datasource_name: The name of the Datasource associated with this DataConnector instance data_asset_name: The name of the DataAsset using this DataConnector instance base_directory: Relative path to subdirectory containing files of interest glob_directive: glob for selecting files in directory (defaults to `**/*`) or nested directories (e.g. `*/*/*.csv`) data_context_root_directory: Optional GreatExpectations root directory (if installed on filesystem) whole_directory_path_override: Treat an entire directory as a single Asset """ # noqa: E501 # FIXME CoP asset_level_option_keys: ClassVar[tuple[str, ...]] = ("glob_directive",) asset_options_type: ClassVar[Type[FilesystemOptions]] = FilesystemOptions def __init__( # noqa: PLR0913 # FIXME CoP self, datasource_name: str, data_asset_name: str, base_directory: pathlib.Path, glob_directive: str = "**/*", data_context_root_directory: Optional[pathlib.Path] = None, file_path_template_map_fn: Optional[Callable] = None, whole_directory_path_override: PathStr | None = None, ) -> None: self._base_directory = base_directory self._glob_directive: str = glob_directive self._data_context_root_directory: Optional[pathlib.Path] = data_context_root_directory super().__init__( datasource_name=datasource_name, data_asset_name=data_asset_name, file_path_template_map_fn=file_path_template_map_fn, whole_directory_path_override=whole_directory_path_override, ) @property def base_directory(self) -> pathlib.Path: """ Accessor method for base_directory. If directory is a relative path, interpret it as relative to the root directory. If it is absolute, then keep as-is. """ # noqa: E501 # FIXME CoP return normalize_directory_path( dir_path=self._base_directory, root_directory_path=self._data_context_root_directory, ) @classmethod def build_data_connector( # noqa: PLR0913 # FIXME CoP cls, datasource_name: str, data_asset_name: str, base_directory: pathlib.Path, glob_directive: str = "**/*", data_context_root_directory: Optional[pathlib.Path] = None, file_path_template_map_fn: Optional[Callable] = None, whole_directory_path_override: PathStr | None = None, ) -> FilesystemDataConnector: """Builds "FilesystemDataConnector", which links named DataAsset to filesystem. Args: datasource_name: The name of the Datasource associated with this "FilesystemDataConnector" instance data_asset_name: The name of the DataAsset using this "FilesystemDataConnector" instance base_directory: Relative path to subdirectory containing files of interest glob_directive: glob for selecting files in directory (defaults to `**/*`) or nested directories (e.g. `*/*/*.csv`) data_context_root_directory: Optional GreatExpectations root directory (if installed on filesystem) file_path_template_map_fn: Format function mapping path to fully-qualified resource on filesystem (optional) get_unfiltered_batch_definition_list_fn: Function used to get the batch definition list before filtering Returns: Instantiated "FilesystemDataConnector" object """ # noqa: E501 # FIXME CoP return FilesystemDataConnector( datasource_name=datasource_name, data_asset_name=data_asset_name, base_directory=base_directory, glob_directive=glob_directive, data_context_root_directory=data_context_root_directory, file_path_template_map_fn=file_path_template_map_fn, whole_directory_path_override=whole_directory_path_override, ) @classmethod def build_test_connection_error_message( cls, data_asset_name: str, base_directory: pathlib.Path, glob_directive: str = "**/*", data_context_root_directory: Optional[pathlib.Path] = None, ) -> str: """Builds helpful error message for reporting issues when linking named DataAsset to filesystem. Args: data_asset_name: The name of the DataAsset using this "FilesystemDataConnector" instance base_directory: Relative path to subdirectory containing files of interest glob_directive: glob for selecting files in directory (defaults to `**/*`) or nested directories (e.g. `*/*/*.csv`) data_context_root_directory: Optional GreatExpectations root directory (if installed on filesystem) Returns: Customized error message """ # noqa: E501 # FIXME CoP test_connection_error_message_template: str = 'No file at base_directory path "{base_directory}" matched glob_directive "{glob_directive}" for DataAsset "{data_asset_name}".' # noqa: E501 # FIXME CoP return test_connection_error_message_template.format( **{ "data_asset_name": data_asset_name, "base_directory": base_directory.resolve(), "glob_directive": glob_directive, "data_context_root_directory": data_context_root_directory, } ) # Interface Method @override def get_data_references(self) -> List[str]: base_directory: pathlib.Path = self.base_directory glob_directive: str = self._glob_directive path_list: List[str] = get_filesystem_one_level_directory_glob_path_list( base_directory_path=base_directory, glob_directive=glob_directive ) return sorted(path_list) # Interface Method @override def _get_full_file_path(self, path: str) -> str: return str(self.base_directory.joinpath(path)) def normalize_directory_path( dir_path: Union[PathStr], root_directory_path: Optional[PathStr] = None, ) -> pathlib.Path: dir_path = pathlib.Path(dir_path) # If directory is a relative path, interpret it as relative to the root directory. if dir_path.is_absolute() or root_directory_path is None: return dir_path root_directory_path = pathlib.Path(root_directory_path) return root_directory_path.joinpath(dir_path) def get_filesystem_one_level_directory_glob_path_list( base_directory_path: Union[PathStr], glob_directive: str ) -> List[str]: """ List file names, relative to base_directory_path one level deep, with expansion specified by glob_directive. :param base_directory_path -- base directory path, relative to which file paths will be collected :param glob_directive -- glob expansion directive :returns -- list of relative file paths """ # noqa: E501 # FIXME CoP if isinstance(base_directory_path, str): base_directory_path = pathlib.Path(base_directory_path) globbed_paths = base_directory_path.glob(glob_directive) path_list: List[str] = [ os.path.relpath(str(posix_path), base_directory_path) for posix_path in globbed_paths ] return path_list
FilesystemDataConnector
python
google__pytype
pytype/tests/test_errors1.py
{ "start": 33643, "end": 34618 }
class ____(test_base.BaseTest): """Tests for pseudo-builtin reveal_type().""" def test_reveal_type(self): errors = self.CheckWithErrors(""" class Foo: pass reveal_type(Foo) # reveal-type[e1] reveal_type(Foo()) # reveal-type[e2] reveal_type([1,2,3]) # reveal-type[e3] """) self.assertErrorSequences( errors, {"e1": ["type[Foo]"], "e2": ["Foo"], "e3": ["list[int]"]} ) def test_reveal_type_expression(self): errors = self.CheckWithErrors(""" x = 42 y = "foo" reveal_type(x or y) # reveal-type[e] """) self.assertErrorSequences(errors, {"e": ["Union[int, str]"]}) def test_combine_containers(self): errors = self.CheckWithErrors(""" from typing import Set, Union x: Set[Union[int, str]] y: Set[Union[str, bytes]] reveal_type(x | y) # reveal-type[e] """) self.assertErrorSequences(errors, {"e": ["set[Union[bytes, int, str]]"]})
RevealTypeTest
python
Textualize__textual
src/textual/demo/widgets.py
{ "start": 21830, "end": 22484 }
class ____(containers.VerticalGroup): DEFAULT_CLASSES = "column" YOUR_MD = """\ ## Your Widget Here! The Textual API allows you to [build custom re-usable widgets](https://textual.textualize.io/guide/widgets/#custom-widgets) and share them across projects. Custom widgets can be themed, just like the builtin widget library. Combine existing widgets to add new functionality, or use the powerful [Line API](https://textual.textualize.io/guide/widgets/#line-api) for unique creations. """ DEFAULT_CSS = """ YourWidgets { margin-bottom: 2; } """ def compose(self) -> ComposeResult: yield Markdown(self.YOUR_MD)
YourWidgets
python
pytorch__pytorch
test/test_fx.py
{ "start": 152810, "end": 167284 }
class ____(JitTestCase): def setUp(self): super().setUp() self.maxDiff = None # Checking for mutable operations while tracing is feature flagged # Enable it in testing but not by default self.orig_tracer_mutable_flag = ( torch.fx.proxy.TracerBase.check_mutable_operations ) torch.fx.proxy.TracerBase.check_mutable_operations = True def tearDown(self): super().tearDown() torch.fx.proxy.TracerBase.check_mutable_operations = ( self.orig_tracer_mutable_flag ) def _fn_to_stable_annotation_str(self, obj): """ Unfortunately we have to serialize function signatures manually since serialization for `inspect.Signature` objects is not stable across python versions """ fn_name = torch.typename(obj) signature = inspect.signature(obj) sig_str = f"{fn_name}{signature}" arg_strs = [] for k, v in signature.parameters.items(): maybe_type_annotation = ( f": {self._annotation_type_to_stable_str(v.annotation, sig_str)}" if v.annotation is not inspect.Signature.empty else "" ) def default_val_str(val): if isinstance(val, (tuple, list)): str_pieces = ["(" if isinstance(val, tuple) else "["] str_pieces.append(", ".join(default_val_str(v) for v in val)) if isinstance(val, tuple) and len(str_pieces) == 2: str_pieces.append(",") str_pieces.append(")" if isinstance(val, tuple) else "]") return "".join(str_pieces) # Need to fix up some default value strings. # First case: modules. Default module `repr` contains the FS path of the module. # Don't leak that if isinstance(val, types.ModuleType): return f"<module {val.__name__}>" # Second case: callables. Callables (such as lambdas) encode their address in # their string repr. Don't do that if callable(val): return f"<function {val.__name__}>" return str(val) if v.default is not inspect.Signature.empty: default_val_str = ( default_val_str(v.default) if not isinstance(v.default, str) else f"'{v.default}'" ) maybe_default = f" = {default_val_str}" else: maybe_default = "" maybe_stars = "" if v.kind == inspect.Parameter.VAR_POSITIONAL: maybe_stars = "*" elif v.kind == inspect.Parameter.VAR_KEYWORD: maybe_stars = "**" arg_strs.append(f"{maybe_stars}{k}{maybe_type_annotation}{maybe_default}") return_annot = ( f" -> {self._annotation_type_to_stable_str(signature.return_annotation, sig_str)}" if signature.return_annotation is not inspect.Signature.empty else "" ) return f'{fn_name}({", ".join(arg_strs)}){return_annot}' _trivial_mappings = { str: "str", int: "int", float: "float", bool: "bool", torch.dtype: "torch.dtype", torch.Tensor: "torch.Tensor", torch.device: "torch.device", torch.memory_format: "torch.memory_format", slice: "slice", torch.nn.Module: "torch.nn.modules.module.Module", torch.fx.Graph: "torch.fx.graph.Graph", torch.fx.Node: "torch.fx.node.Node", torch.fx.Proxy: "torch.fx.proxy.Proxy", torch.fx.node.Target: "torch.fx.node.Target", torch.fx.node.Argument: "torch.fx.node.Argument", torch.fx.graph.PythonCode: "torch.fx.graph.PythonCode", torch.fx.graph_module.GraphModule: "torch.fx.graph_module.GraphModule", torch.fx.subgraph_rewriter.Match: "torch.fx.subgraph_rewriter.Match", Ellipsis: "...", typing.Any: "Any", type(None): "NoneType", None: "None", typing.Iterator: "Iterator", collections.abc.Iterator: "Iterator", } _UNBOUND_TYPES = { dict, list, tuple, type, typing.Callable, typing.Dict, # noqa: UP006 typing.List, # noqa: UP006 typing.Tuple, # noqa: UP006 typing.Type, # noqa: UP006 typing.Union, } def _annotation_type_to_stable_str(self, t, sig_str, recursive: bool = False): if t is inspect.Signature.empty: return "" # Forward ref if isinstance(t, str): if recursive: return t else: return f"'{t}'" if hasattr(typing, "ForwardRef") and isinstance(t, typing.ForwardRef): return t.__forward_arg__ if hasattr(typing, "_ForwardRef") and isinstance(t, typing._ForwardRef): return t.__forward_arg__ mapping = self._trivial_mappings.get(t, None) if mapping: return mapping # Handle types with contained types contained = getattr(t, "__args__", None) or [] # Callables contain a bare List for arguments contained = t if isinstance(t, list) else contained # Python 3.8 puts type vars into __args__ for unbound types such as Dict if all(isinstance(ct, typing.TypeVar) for ct in contained): contained = [] contained_type_annots = [ self._annotation_type_to_stable_str(ct, sig_str, True) for ct in contained ] contained_type_str = ( f'[{", ".join(contained_type_annots)}]' if len(contained_type_annots) > 0 else "" ) origin = getattr(t, "__origin__", None) if origin is None: # Unbound types don't have `__origin__` in some Python versions, so fix that up here. origin = t if t in self._UNBOUND_TYPES else origin if origin in {tuple, tuple}: return f"Tuple{contained_type_str}" if origin in {typing.Union}: # Annoying hack to detect Optional if len(contained) == 2 and (contained[0] is type(None)) ^ ( contained[1] is type(None) ): not_none_param = ( contained[0] if contained[0] is not type(None) else contained[1] ) return f"Optional[{self._annotation_type_to_stable_str(not_none_param, sig_str, True)}]" return f"Union{contained_type_str}" if origin in {dict, dict}: return f"Dict{contained_type_str}" if origin in {list, list}: return f"List{contained_type_str}" if origin in {type, type}: return f"Type{contained_type_str}" if isinstance(t, typing.Callable): if len(contained) > 0 and contained[0] is not Ellipsis: return f'Callable[[{", ".join(contained_type_annots[:-1])}], {contained_type_annots[-1]}]' else: return f'Callable{contained_type_str}' if t is ArgumentT: # ArgumentT is a TypeVar bound to torch.fx.node.Argument return f'torch.fx.node.Argument{contained_type_str}' raise RuntimeError(f'Unrecognized type {t} used in BC-compatible type signature {sig_str}.' f'Please add support for this type and confirm with the ' f'FX team that your signature change is valid.') raise RuntimeError( f"Unrecognized type {t} used in BC-compatible type signature {sig_str}." f"Please add support for this type and confirm with the " f"FX team that your signature change is valid." ) def test_function_back_compat(self): """ Test backward compatibility for function signatures with @compatibility(is_backward_compatible=True). Currently this checks for exact signature matches, which may lead to false positives. If this becomes too annoying, we can refine this check to actually parse out the saved schema strings and check if the change is truly backward- incompatible. """ signature_strs = [] for obj in _BACK_COMPAT_OBJECTS: if not isinstance(obj, type): signature_strs.append(self._fn_to_stable_annotation_str(obj)) signature_strs.sort() try: self.assertExpected( "\n".join(signature_strs) + "\n", "fx_backcompat_function_signatures" ) except AssertionError as e: msg = ( f"{e}\n****** ERROR ******\nAn FX function that has been marked " f"as backwards-compatible has experienced a signature change. See the " f"above exception context for more information. If this change was " f"unintended, please revert it. If it was intended, check with the FX " f"team to ensure that the proper deprecation protocols have been followed " f"and subsequently --accept the change." ) raise AssertionError(msg) # noqa: B904 def test_class_member_back_compat(self): """ Test backward compatibility for members of classes with @compatibility(is_backward_compatible=True). Currently this checks for exact matches on the publicly visible members of the class. """ class_method_strs = [] for obj in _BACK_COMPAT_OBJECTS: if isinstance(obj, type): public_members = [ name for name in obj.__dict__ if not name.startswith("_") ] class_method_strs.append( f"{torch.typename(obj)} {sorted(public_members)}" ) class_method_strs.sort() try: self.assertExpected( "\n".join(class_method_strs), "fx_backcompat_class_members" ) except AssertionError as e: msg = ( f"{e}\n****** ERROR ******\nAn FX class that has been marked " f"as backwards-compatible has experienced change in its public members. See the " f"above exception context for more information. If this change was " f"unintended, please revert it. If it was intended, check with the FX " f"team to ensure that the proper deprecation protocols have been followed " f"and subsequently --accept the change." ) raise AssertionError(msg) from e def test_public_api_surface(self): non_back_compat_objects = {} def check_symbols_have_bc_designation(m, seen): if not m.__name__.startswith("torch.fx"): return if m.__name__.startswith("torch.fx.experimental"): return # It's really common for inner functions to point to random modules # - make sure we don't recurse into modules we've already checked. seen.add(m.__name__) for k, v in m.__dict__.items(): if hasattr(v, "__name__") and v.__name__ in seen: continue if v is m: continue if k.startswith("_"): continue if isinstance(v, types.ModuleType): check_symbols_have_bc_designation(v, seen) elif isinstance(v, (type, types.FunctionType)): if v not in _MARKED_WITH_COMPATIBILITY: non_back_compat_objects.setdefault(v) check_symbols_have_bc_designation(torch.fx, set()) check_symbols_have_bc_designation(torch.fx.passes, set()) non_back_compat_strs = [ torch.typename(obj) for obj in non_back_compat_objects ] # Only want objects in torch.fx non_back_compat_strs = [ s for s in non_back_compat_strs if s.startswith("torch.fx") and not s.startswith("torch.fx.experimental") ] # Only want objects in public namespaces non_back_compat_strs = [ s for s in non_back_compat_strs if all(not atom.startswith("_") for atom in s.split(".")) ] non_back_compat_strs.sort() if len(non_back_compat_strs) != 0: raise AssertionError( f"Public FX API(s) {non_back_compat_strs} introduced but not given a " f"backwards-compatibility classification! Please decorate these " f"API(s) with `@torch.fx._compatibility.compatibility` to specify " f"BC guarantees." ) def test_adding_side_effect_function(self): class TestModule(torch.nn.Module): def forward(self, x): side_effect_func(x) return x gm = torch.fx.symbolic_trace(TestModule()) self.assertEqual(len(gm.graph.nodes), 3) gm.graph.eliminate_dead_code() gm.recompile() self.assertEqual(len(gm.graph.nodes), 3) found = False for node in gm.graph.nodes: if node.op == "call_function" and node.target is side_effect_func: found = True self.assertTrue(found) def test_preserve_unused_attr_after_unpickle(self): gm = torch.fx.symbolic_trace(Add()) gm.add_submodule("foo", Add()) gm.dummy_buffer = torch.nn.Buffer(torch.empty(1)) gm.register_parameter("dummy_parameter", torch.nn.Parameter(torch.empty(1))) b = io.BytesIO() torch.save(gm, b) b.seek(0) # weights_only=False as this loads a GraphModule # GLOBAL torch.fx.graph_module.reduce_graph_module was not an allowed global by default reload_gm = torch.load(b, weights_only=False) self.assertTrue(hasattr(reload_gm, "foo")) self.assertTrue(hasattr(reload_gm, "dummy_buffer")) self.assertTrue(hasattr(reload_gm, "dummy_parameter")) # This is failing on Python 3.12 : https://github.com/pytorch/pytorch/issues/119454 @unittest.skipIf(sys.version_info >= (3, 12), "Failing on python 3.12+")
TestFXAPIBackwardCompatibility
python
ipython__ipython
IPython/core/guarded_eval.py
{ "start": 6864, "end": 12275 }
class ____(EvaluationPolicy): allowed_getitem: set[InstancesHaveGetItem] = field(default_factory=set) allowed_getitem_external: set[tuple[str, ...] | str] = field(default_factory=set) allowed_getattr: set[MayHaveGetattr] = field(default_factory=set) allowed_getattr_external: set[tuple[str, ...] | str] = field(default_factory=set) allowed_operations: set = field(default_factory=set) allowed_operations_external: set[tuple[str, ...] | str] = field(default_factory=set) allow_getitem_on_types: bool = field(default_factory=bool) _operation_methods_cache: dict[str, set[Callable]] = field( default_factory=dict, init=False ) def can_get_attr(self, value, attr): allowed_getattr_external = _coerce_path_to_tuples(self.allowed_getattr_external) has_original_attribute = _has_original_dunder( value, allowed_types=self.allowed_getattr, allowed_methods=self._getattribute_methods, allowed_external=allowed_getattr_external, method_name="__getattribute__", ) has_original_attr = _has_original_dunder( value, allowed_types=self.allowed_getattr, allowed_methods=self._getattr_methods, allowed_external=allowed_getattr_external, method_name="__getattr__", ) accept = False # Many objects do not have `__getattr__`, this is fine. if has_original_attr is None and has_original_attribute: accept = True else: # Accept objects without modifications to `__getattr__` and `__getattribute__` accept = has_original_attr and has_original_attribute if accept: # We still need to check for overridden properties. value_class = type(value) if not hasattr(value_class, attr): return True class_attr_val = getattr(value_class, attr) is_property = isinstance(class_attr_val, property) if not is_property: return True # Properties in allowed types are ok (although we do not include any # properties in our default allow list currently). if type(value) in self.allowed_getattr: return True # pragma: no cover # Properties in subclasses of allowed types may be ok if not changed for module_name, *access_path in allowed_getattr_external: try: external_class = _get_external(module_name, access_path) external_class_attr_val = getattr(external_class, attr) except (KeyError, AttributeError): return False # pragma: no cover return class_attr_val == external_class_attr_val return False def can_get_item(self, value, item): """Allow accessing `__getiitem__` of allow-listed instances unless it was not modified.""" allowed_getitem_external = _coerce_path_to_tuples(self.allowed_getitem_external) if self.allow_getitem_on_types: # e.g. Union[str, int] or Literal[True, 1] if isinstance(value, (typing._SpecialForm, typing._BaseGenericAlias)): return True # PEP 560 e.g. list[str] if isinstance(value, type) and hasattr(value, "__class_getitem__"): return True return _has_original_dunder( value, allowed_types=self.allowed_getitem, allowed_methods=self._getitem_methods, allowed_external=allowed_getitem_external, method_name="__getitem__", ) def can_operate(self, dunders: tuple[str, ...], a, b=None): allowed_operations_external = _coerce_path_to_tuples( self.allowed_operations_external ) objects = [a] if b is not None: objects.append(b) return all( [ _has_original_dunder( obj, allowed_types=self.allowed_operations, allowed_methods=self._operator_dunder_methods(dunder), allowed_external=allowed_operations_external, method_name=dunder, ) for dunder in dunders for obj in objects ] ) def _operator_dunder_methods(self, dunder: str) -> set[Callable]: if dunder not in self._operation_methods_cache: self._operation_methods_cache[dunder] = self._safe_get_methods( self.allowed_operations, dunder ) return self._operation_methods_cache[dunder] @cached_property def _getitem_methods(self) -> set[Callable]: return self._safe_get_methods(self.allowed_getitem, "__getitem__") @cached_property def _getattr_methods(self) -> set[Callable]: return self._safe_get_methods(self.allowed_getattr, "__getattr__") @cached_property def _getattribute_methods(self) -> set[Callable]: return self._safe_get_methods(self.allowed_getattr, "__getattribute__") def _safe_get_methods(self, classes, name) -> set[Callable]: return { method for class_ in classes for method in [getattr(class_, name, None)] if method }
SelectivePolicy
python
rushter__MLAlgorithms
mla/neuralnet/regularizers.py
{ "start": 508, "end": 601 }
class ____(Regularizer): def _penalty(self, weights): return self.C * weights**2
L2
python
huggingface__transformers
src/transformers/models/phobert/tokenization_phobert.py
{ "start": 1371, "end": 13112 }
class ____(PreTrainedTokenizer): """ Construct a PhoBERT tokenizer. Based on Byte-Pair-Encoding. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to this superclass for more information regarding those methods. Args: vocab_file (`str`): Path to the vocabulary file. merges_file (`str`): Path to the merges file. bos_token (`st`, *optional*, defaults to `"<s>"`): The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token. <Tip> When building a sequence using special tokens, this is not the token that is used for the beginning of sequence. The token used is the `cls_token`. </Tip> eos_token (`str`, *optional*, defaults to `"</s>"`): The end of sequence token. <Tip> When building a sequence using special tokens, this is not the token that is used for the end of sequence. The token used is the `sep_token`. </Tip> sep_token (`str`, *optional*, defaults to `"</s>"`): The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for sequence classification or for a text and a question for question answering. It is also used as the last token of a sequence built with special tokens. cls_token (`str`, *optional*, defaults to `"<s>"`): The classifier token which is used when doing sequence classification (classification of the whole sequence instead of per-token classification). It is the first token of the sequence when built with special tokens. unk_token (`str`, *optional*, defaults to `"<unk>"`): The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead. pad_token (`str`, *optional*, defaults to `"<pad>"`): The token used for padding, for example when batching sequences of different lengths. mask_token (`str`, *optional*, defaults to `"<mask>"`): The token used for masking values. This is the token used when training this model with masked language modeling. This is the token which the model will try to predict. """ vocab_files_names = VOCAB_FILES_NAMES def __init__( self, vocab_file, merges_file, bos_token="<s>", eos_token="</s>", sep_token="</s>", cls_token="<s>", unk_token="<unk>", pad_token="<pad>", mask_token="<mask>", **kwargs, ): self.vocab_file = vocab_file self.merges_file = merges_file self.encoder = {} self.encoder[str(bos_token)] = 0 self.encoder[str(pad_token)] = 1 self.encoder[str(eos_token)] = 2 self.encoder[str(unk_token)] = 3 self.add_from_file(vocab_file) self.decoder = {v: k for k, v in self.encoder.items()} with open(merges_file, encoding="utf-8") as merges_handle: merges = merges_handle.read().split("\n")[:-1] merges = [tuple(merge.split()[:-1]) for merge in merges] self.bpe_ranks = dict(zip(merges, range(len(merges)))) self.cache = {} super().__init__( bos_token=bos_token, eos_token=eos_token, unk_token=unk_token, sep_token=sep_token, cls_token=cls_token, pad_token=pad_token, mask_token=mask_token, **kwargs, ) def build_inputs_with_special_tokens( self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None ) -> list[int]: """ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A PhoBERT sequence has the following format: - single sequence: `<s> X </s>` - pair of sequences: `<s> A </s></s> B </s>` Args: token_ids_0 (`list[int]`): List of IDs to which the special tokens will be added. token_ids_1 (`list[int]`, *optional*): Optional second list of IDs for sequence pairs. Returns: `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens. """ if token_ids_1 is None: return [self.cls_token_id] + token_ids_0 + [self.sep_token_id] cls = [self.cls_token_id] sep = [self.sep_token_id] return cls + token_ids_0 + sep + sep + token_ids_1 + sep def get_special_tokens_mask( self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False ) -> list[int]: """ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer `prepare_for_model` method. Args: token_ids_0 (`list[int]`): List of IDs. token_ids_1 (`list[int]`, *optional*): Optional second list of IDs for sequence pairs. already_has_special_tokens (`bool`, *optional*, defaults to `False`): Whether or not the token list is already formatted with special tokens for the model. Returns: `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token. """ if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True ) if token_ids_1 is None: return [1] + ([0] * len(token_ids_0)) + [1] return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1] def create_token_type_ids_from_sequences( self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None ) -> list[int]: """ Create a mask from the two sequences passed to be used in a sequence-pair classification task. PhoBERT does not make use of token type ids, therefore a list of zeros is returned. Args: token_ids_0 (`list[int]`): List of IDs. token_ids_1 (`list[int]`, *optional*): Optional second list of IDs for sequence pairs. Returns: `list[int]`: List of zeros. """ sep = [self.sep_token_id] cls = [self.cls_token_id] if token_ids_1 is None: return len(cls + token_ids_0 + sep) * [0] return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0] @property def vocab_size(self): return len(self.encoder) def get_vocab(self): return dict(self.encoder, **self.added_tokens_encoder) def bpe(self, token): if token in self.cache: return self.cache[token] word = tuple(token) word = tuple(list(word[:-1]) + [word[-1] + "</w>"]) pairs = get_pairs(word) if not pairs: return token while True: bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf"))) if bigram not in self.bpe_ranks: break first, second = bigram new_word = [] i = 0 while i < len(word): try: j = word.index(first, i) except ValueError: new_word.extend(word[i:]) break else: new_word.extend(word[i:j]) i = j if word[i] == first and i < len(word) - 1 and word[i + 1] == second: new_word.append(first + second) i += 2 else: new_word.append(word[i]) i += 1 new_word = tuple(new_word) word = new_word if len(word) == 1: break else: pairs = get_pairs(word) word = "@@ ".join(word) word = word[:-4] self.cache[token] = word return word def _tokenize(self, text): """Tokenize a string.""" split_tokens = [] words = re.findall(r"\S+\n?", text) for token in words: split_tokens.extend(list(self.bpe(token).split(" "))) return split_tokens def _convert_token_to_id(self, token): """Converts a token (str) in an id using the vocab.""" return self.encoder.get(token, self.encoder.get(self.unk_token)) def _convert_id_to_token(self, index): """Converts an index (integer) in a token (str) using the vocab.""" return self.decoder.get(index, self.unk_token) def convert_tokens_to_string(self, tokens): """Converts a sequence of tokens (string) in a single string.""" out_string = " ".join(tokens).replace("@@ ", "").strip() return out_string def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]: if not os.path.isdir(save_directory): logger.error(f"Vocabulary path ({save_directory}) should be a directory") return out_vocab_file = os.path.join( save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) out_merge_file = os.path.join( save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file, out_vocab_file) elif not os.path.isfile(self.vocab_file): with open(out_vocab_file, "wb") as fi: content_spiece_model = self.sp_model.serialized_model_proto() fi.write(content_spiece_model) if os.path.abspath(self.merges_file) != os.path.abspath(out_merge_file): copyfile(self.merges_file, out_merge_file) return out_vocab_file, out_merge_file # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True): # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)) # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens) # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far) # return ''.join(tokens_generated_so_far) def add_from_file(self, f): """ Loads a pre-existing dictionary from a text file and adds its symbols to this instance. """ if isinstance(f, str): try: with open(f, "r", encoding="utf-8") as fd: self.add_from_file(fd) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception(f"Incorrect encoding detected in {f}, please rebuild the dataset") return lines = f.readlines() for lineTmp in lines: line = lineTmp.strip() idx = line.rfind(" ") if idx == -1: raise ValueError("Incorrect dictionary format, expected '<token> <cnt>'") word = line[:idx] self.encoder[word] = len(self.encoder) __all__ = ["PhobertTokenizer"]
PhobertTokenizer
python
keras-team__keras
keras/src/layers/attention/multi_head_attention.py
{ "start": 585, "end": 32033 }
class ____(Layer): """MultiHeadAttention layer. This is an implementation of multi-headed attention as described in the paper "Attention is all you Need" [Vaswani et al., 2017](https://arxiv.org/abs/1706.03762). If `query`, `key,` `value` are the same, then this is self-attention. Each timestep in `query` attends to the corresponding sequence in `key`, and returns a fixed-width vector. This layer first projects `query`, `key` and `value`. These are (effectively) a list of tensors of length `num_attention_heads`, where the corresponding shapes are `(batch_size, <query dimensions>, key_dim)`, `(batch_size, <key/value dimensions>, key_dim)`, `(batch_size, <key/value dimensions>, value_dim)`. Then, the query and key tensors are dot-producted and scaled. These are softmaxed to obtain attention probabilities. The value tensors are then interpolated by these probabilities, then concatenated back to a single tensor. Finally, the result tensor with the last dimension as `value_dim` can take a linear projection and return. Args: num_heads: Number of attention heads. key_dim: Size of each attention head for query and key. value_dim: Size of each attention head for value. dropout: Dropout probability. use_bias: Boolean, whether the dense layers use bias vectors/matrices. output_shape: The expected shape of an output tensor, besides the batch and sequence dims. If not specified, projects back to the query feature dim (the query input's last dimension). attention_axes: axes over which the attention is applied. `None` means attention over all axes, but batch, heads, and features. flash_attention: If `None`, the layer attempts to use flash attention for faster and more memory-efficient attention computations when possible. This behavior can be configured using `keras.config.enable_flash_attention()` or `keras.config.disable_flash_attention()`. kernel_initializer: Initializer for dense layer kernels. bias_initializer: Initializer for dense layer biases. kernel_regularizer: Regularizer for dense layer kernels. bias_regularizer: Regularizer for dense layer biases. activity_regularizer: Regularizer for dense layer activity. kernel_constraint: Constraint for dense layer kernels. bias_constraint: Constraint for dense layer kernels. seed: Optional integer to seed the dropout layer. Call arguments: query: Query tensor of shape `(B, T, dim)`, where `B` is the batch size, `T` is the target sequence length, and dim is the feature dimension. value: Value tensor of shape `(B, S, dim)`, where `B` is the batch size, `S` is the source sequence length, and dim is the feature dimension. key: Optional key tensor of shape `(B, S, dim)`. If not given, will use `value` for both `key` and `value`, which is the most common case. attention_mask: a boolean mask of shape `(B, T, S)`, that prevents attention to certain positions. The boolean mask specifies which query elements can attend to which key elements, 1 indicates attention and 0 indicates no attention. Broadcasting can happen for the missing batch dimensions and the head dimension. return_attention_scores: A boolean to indicate whether the output should be `(attention_output, attention_scores)` if `True`, or `attention_output` if `False`. Defaults to `False`. training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (no dropout). Will go with either using the training mode of the parent layer/model, or `False` (inference) if there is no parent layer. use_causal_mask: A boolean to indicate whether to apply a causal mask to prevent tokens from attending to future tokens (e.g., used in a decoder Transformer). Returns: attention_output: The result of the computation, of shape `(B, T, E)`, where `T` is for target sequence shapes and `E` is the query input last dimension if `output_shape` is `None`. Otherwise, the multi-head outputs are projected to the shape specified by `output_shape`. attention_scores: (Optional) multi-head attention coefficients over attention axes. """ def __init__( self, num_heads, key_dim, value_dim=None, dropout=0.0, use_bias=True, output_shape=None, attention_axes=None, flash_attention=None, kernel_initializer="glorot_uniform", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, seed=None, **kwargs, ): super().__init__(**kwargs) self.supports_masking = True self._num_heads = num_heads self._key_dim = key_dim self._value_dim = value_dim if value_dim else key_dim self._dropout = dropout self._use_bias = use_bias if output_shape: if isinstance(output_shape, int): output_shape = (output_shape,) try: output_shape = tuple(output_shape) except: raise ValueError( f"Invalid `output_shape`: {output_shape}. When " "specified, the `output_shape` should be of type tuple, " "list, or int." ) self._output_shape = output_shape self._flash_attention = flash_attention or is_flash_attention_enabled() self._kernel_initializer = initializers.get(kernel_initializer) self._bias_initializer = initializers.get(bias_initializer) self._kernel_regularizer = regularizers.get(kernel_regularizer) self._bias_regularizer = regularizers.get(bias_regularizer) self._activity_regularizer = regularizers.get(activity_regularizer) self._kernel_constraint = constraints.get(kernel_constraint) self._bias_constraint = constraints.get(bias_constraint) if isinstance(attention_axes, int): attention_axes = (attention_axes,) elif attention_axes and not isinstance(attention_axes, (list, tuple)): raise ValueError( "`attention_axes` must be an int, list, or tuple." f"Received: attention_axes={attention_axes}" ) self._attention_axes = attention_axes self.seed = seed self._inverse_sqrt_key_dim = 1.0 / math.sqrt(float(self._key_dim)) # Check for flash attention constraints if self._flash_attention and self._dropout > 0.0: raise ValueError( "Dropout is not supported when flash attention is enabled. " "Please set dropout to 0.0 to use flash attention." ) @property def num_heads(self): return self._num_heads @property def key_dim(self): return self._key_dim @property def value_dim(self): return self._value_dim @property def dropout(self): return self._dropout @property def use_bias(self): return self._use_bias # Avoid exposing `output_shape` as it may conflict with `Functional` and # `Sequential` models when calling `summary()`. @property def attention_axes(self): return self._attention_axes def get_config(self): base_config = super().get_config() config = { "num_heads": self._num_heads, "key_dim": self._key_dim, "value_dim": self._value_dim, "dropout": self._dropout, "use_bias": self._use_bias, "output_shape": self._output_shape, "attention_axes": self._attention_axes, "kernel_initializer": initializers.serialize( self._kernel_initializer ), "bias_initializer": initializers.serialize(self._bias_initializer), "kernel_regularizer": regularizers.serialize( self._kernel_regularizer ), "bias_regularizer": regularizers.serialize(self._bias_regularizer), "activity_regularizer": regularizers.serialize( self._activity_regularizer ), "kernel_constraint": constraints.serialize(self._kernel_constraint), "bias_constraint": constraints.serialize(self._bias_constraint), "seed": self.seed, } return {**base_config, **config} def build( self, query_shape, value_shape, key_shape=None, ): """Builds layers and variables. Args: query_shape: Shape of the `query` tensor. value_shape: Shape of the `value` tensor. key: Optional shape of the `key` tensor. """ key_shape = value_shape if key_shape is None else key_shape if value_shape[1:-1] != key_shape[1:-1]: raise ValueError( "All dimensions of `value` and `key`, except the last one, " f"must be equal. Received: value_shape={value_shape} and " f"key_shape={key_shape}" ) query_rank = len(query_shape) value_rank = len(value_shape) key_rank = len(key_shape) einsum_equation, bias_axes, output_rank = _build_proj_equation( query_rank - 1, bound_dims=1, output_dims=2 ) self._query_dense = EinsumDense( einsum_equation, output_shape=_get_output_shape( output_rank - 1, [self._num_heads, self._key_dim] ), bias_axes=bias_axes if self._use_bias else None, name="query", **self._get_common_kwargs_for_sublayer(), ) self._query_dense.build(query_shape) einsum_equation, bias_axes, output_rank = _build_proj_equation( key_rank - 1, bound_dims=1, output_dims=2 ) self._key_dense = EinsumDense( einsum_equation, output_shape=_get_output_shape( output_rank - 1, [self._num_heads, self._key_dim] ), bias_axes=bias_axes if self._use_bias else None, name="key", **self._get_common_kwargs_for_sublayer(), ) self._key_dense.build(key_shape) einsum_equation, bias_axes, output_rank = _build_proj_equation( value_rank - 1, bound_dims=1, output_dims=2 ) self._value_dense = EinsumDense( einsum_equation, output_shape=_get_output_shape( output_rank - 1, [self._num_heads, self._value_dim] ), bias_axes=bias_axes if self._use_bias else None, name="value", **self._get_common_kwargs_for_sublayer(), ) self._value_dense.build(value_shape) # Builds the attention computations for multi-head dot product # attention. These computations could be wrapped into the keras # attention layer once it supports multi-head einsum computations. self._build_attention(output_rank) self._output_dense = self._make_output_dense( query_shape, self._get_common_kwargs_for_sublayer(), "attention_output", ) output_dense_input_shape = list( self._query_dense.compute_output_shape(query_shape) ) output_dense_input_shape[-1] = self._value_dim self._output_dense.build(tuple(output_dense_input_shape)) @property def query_dense(self): return self._query_dense @property def key_dense(self): return self._key_dense @property def value_dense(self): return self._value_dense @property def output_dense(self): return self._output_dense def _get_common_kwargs_for_sublayer(self): common_kwargs = dict( kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer, activity_regularizer=self._activity_regularizer, kernel_constraint=self._kernel_constraint, bias_constraint=self._bias_constraint, dtype=self.dtype_policy, ) # Create new clone of kernel/bias initializer, so that we don't reuse # the initializer instance, which could lead to same init value since # initializer is stateless. kernel_initializer = self._kernel_initializer.__class__.from_config( self._kernel_initializer.get_config() ) bias_initializer = self._bias_initializer.__class__.from_config( self._bias_initializer.get_config() ) common_kwargs["kernel_initializer"] = kernel_initializer common_kwargs["bias_initializer"] = bias_initializer return common_kwargs def _make_output_dense(self, query_shape, common_kwargs, name=None): """Builds the output projection matrix. Args: free_dims: Number of free dimensions for einsum equation building. common_kwargs: Common keyword arguments for einsum layer. name: Name for the projection layer. Returns: Projection layer. """ query_rank = len(query_shape) if self._output_shape: output_shape = self._output_shape else: output_shape = [query_shape[-1]] einsum_equation, bias_axes, output_rank = _build_proj_equation( query_rank - 1, bound_dims=2, output_dims=len(output_shape) ) return EinsumDense( einsum_equation, output_shape=_get_output_shape(output_rank - 1, output_shape), bias_axes=bias_axes if self._use_bias else None, name=name, **common_kwargs, ) def _build_attention(self, rank): """Builds multi-head dot-product attention computations. This function builds attributes necessary for `_compute_attention` to customize attention computation to replace the default dot-product attention. Args: rank: the rank of query, key, value tensors. """ if self._attention_axes is None: self._attention_axes = tuple(range(1, rank - 2)) else: self._attention_axes = tuple( axis if axis >= 0 else (rank - 1) + axis for axis in self._attention_axes ) ( self._dot_product_equation, self._combine_equation, attn_scores_rank, ) = _build_attention_equation(rank, attn_axes=self._attention_axes) norm_axes = tuple( range( attn_scores_rank - len(self._attention_axes), attn_scores_rank ) ) self._softmax = Softmax(axis=norm_axes, dtype=self.dtype_policy) self._dropout_layer = Dropout( rate=self._dropout, dtype=self.dtype_policy, seed=self.seed ) def _masked_softmax(self, attention_scores, attention_mask=None): # Normalize the attention scores to probabilities. # attention_scores = [B, N, T, S] if attention_mask is not None: # The expand dim happens starting from the `num_heads` dimension, # (<batch_dims>, num_heads, <query_attention_dims, # key_attention_dims>) mask_expansion_axis = -len(self._attention_axes) * 2 - 1 for _ in range( len(attention_scores.shape) - len(attention_mask.shape) ): attention_mask = ops.expand_dims( attention_mask, axis=mask_expansion_axis ) return self._softmax(attention_scores, mask=attention_mask) def _compute_attention( self, query, key, value, attention_mask=None, training=None, return_attention_scores=False, ): """Applies Dot-product attention with query, key, value tensors. This function defines the computation inside `call` with projected multi-head Q, K, V inputs. Users can override this function for customized attention implementation. Args: query: Projected query tensor of shape `(B, T, N, key_dim)`. key: Projected key tensor of shape `(B, S, N, key_dim)`. value: Projected value tensor of shape `(B, S, N, value_dim)`. attention_mask: a boolean mask of shape `(B, T, S)`, that prevents attention to certain positions. It is generally not needed if the `query` and `value` (and/or `key`) are masked. training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (doing nothing). Returns: attention_output: Multi-headed outputs of attention computation. attention_scores: Multi-headed attention weights. """ # Check for flash attention constraints if self._flash_attention and return_attention_scores: raise ValueError( "Returning attention scores is not supported when flash " "attention is enabled. Please disable flash attention to access" " attention scores." ) # Determine whether to use dot-product attention use_dot_product_attention = not ( self._dropout > 0.0 or return_attention_scores or (len(query.shape) != 4) ) if use_dot_product_attention: if attention_mask is not None: # Ensure attention_mask has the correct shape for broadcasting # Expected shape: [batch_size, num_heads, query_seq_len, # key_seq_len]. mask_expansion_axis = -len(self._attention_axes) * 2 - 1 len_attention_scores_shape = 4 # Only accepts 4D inputs for _ in range( len_attention_scores_shape - len(attention_mask.shape) ): attention_mask = ops.expand_dims( attention_mask, axis=mask_expansion_axis ) attention_mask = ops.cast(attention_mask, dtype="bool") # Directly compute the attention output using dot-product attention attention_output = ops.dot_product_attention( query=query, key=key, value=value, bias=None, mask=attention_mask, scale=self._inverse_sqrt_key_dim, is_causal=False, flash_attention=self._flash_attention, ) return attention_output, None # Default behavior without flash attention, with explicit attention # scores query = ops.multiply( query, ops.cast(self._inverse_sqrt_key_dim, query.dtype) ) # Take the dot product between "query" and "key" to get the raw # attention scores. attention_scores = ops.einsum(self._dot_product_equation, key, query) # Apply the mask using the custom masked softmax attention_scores = self._masked_softmax( attention_scores, attention_mask ) # Apply dropout to the attention scores if needed if self._dropout > 0.0: final_attn_scores = self._dropout_layer( attention_scores, training=training ) else: final_attn_scores = attention_scores # `context_layer` = [B, T, N, H] attention_output = ops.einsum( self._combine_equation, final_attn_scores, value ) return attention_output, attention_scores def call( self, query, value, key=None, query_mask=None, value_mask=None, key_mask=None, attention_mask=None, return_attention_scores=False, training=None, use_causal_mask=False, ): if key is None: key = value # Delete the masks because the masks are handled at the level of the # layer query_mask = backend.get_keras_mask(query) backend.set_keras_mask(query, None) backend.set_keras_mask(value, None) backend.set_keras_mask(key, None) attention_mask = self._compute_attention_mask( query, value, query_mask=query_mask, value_mask=value_mask, key_mask=key_mask, attention_mask=attention_mask, use_causal_mask=use_causal_mask, ) # N = `num_attention_heads` # H = `size_per_head` # `query` = [B, T, N, H] query = self._query_dense(query) # `key` = [B, S, N, H] key = self._key_dense(key) # `value` = [B, S, N, H] value = self._value_dense(value) attention_output, attention_scores = self._compute_attention( query, key, value, attention_mask, training, return_attention_scores, ) attention_output = self._output_dense(attention_output) # Set mask on output if needed if query_mask is not None: backend.set_keras_mask(attention_output, query_mask) if return_attention_scores: return attention_output, attention_scores return attention_output def _compute_attention_mask( self, query, value, query_mask=None, value_mask=None, key_mask=None, attention_mask=None, use_causal_mask=False, ): """Computes the attention mask, using the Keras masks of the inputs. * The `query`'s mask is reshaped from [B, T] to [B, T, 1]. * The `value`'s mask is reshaped from [B, S] to [B, 1, S]. * The `key`'s mask is reshaped from [B, S] to [B, 1, S]. The `key`'s mask is ignored if `key` is `None` or if `key is value`. * If `use_causal_mask=True`, then the causal mask is computed. Its shape is [1, T, S]. All defined masks are merged using a logical AND operation (`&`). In general, if the `query` and `value` are masked, then there is no need to define the `attention_mask`. Args: query: Projected query tensor of shape `(B, T, N, key_dim)`. key: Projected key tensor of shape `(B, T, N, key_dim)`. value: Projected value tensor of shape `(B, T, N, value_dim)`. attention_mask: a boolean mask of shape `(B, T, S)`, that prevents attention to certain positions. use_causal_mask: A boolean to indicate whether to apply a causal mask to prevent tokens from attending to future tokens (e.g., used in a decoder Transformer). Returns: attention_mask: a boolean mask of shape `(B, T, S)`, that prevents attention to certain positions, based on the Keras masks of the `query`, `key`, `value`, and `attention_mask` tensors, and the causal mask if `use_causal_mask=True`. """ auto_mask = None if query_mask is not None: query_mask = ops.cast(query_mask, "bool") # defensive casting # B = batch size, T = max query length auto_mask = ops.expand_dims(query_mask, -1) # shape is [B, T, 1] if value_mask is not None: value_mask = ops.cast(value_mask, "bool") # defensive casting # B = batch size, S == max value length mask = ops.expand_dims(value_mask, -2) # shape is [B, 1, S] auto_mask = mask if auto_mask is None else auto_mask & mask if key_mask is not None: key_mask = ops.cast(key_mask, "bool") # defensive casting # B == batch size, S == max key length == max value length mask = ops.expand_dims(key_mask, -2) # shape is [B, 1, S] auto_mask = mask if auto_mask is None else auto_mask & mask if use_causal_mask: # the shape of the causal mask is [1, T, S] mask = self._compute_causal_mask(query, value) auto_mask = mask if auto_mask is None else auto_mask & mask if attention_mask is not None: attention_mask = ops.cast(attention_mask, "bool") if auto_mask is not None: # merge attention_mask & automatic mask, to shape [B, T, S] attention_mask = ( auto_mask if attention_mask is None else attention_mask & auto_mask ) return attention_mask def _compute_causal_mask(self, query, value=None): """Computes a causal mask (e.g., for masked self-attention layers). For example, if query and value both contain sequences of length 4, this function returns a boolean tensor equal to: ``` [[[True, False, False, False], [True, True, False, False], [True, True, True, False], [True, True, True, True]]] ``` Args: query: query tensor of shape `(B, T, ...)`. value: value tensor of shape `(B, S, ...)` (optional, defaults to query). Returns: mask: a boolean tensor of shape `(1, T, S)` containing a lower triangular matrix of shape `(T, S)`. """ q_seq_length = ops.shape(query)[1] v_seq_length = q_seq_length if value is None else ops.shape(value)[1] ones_mask = ops.ones((1, q_seq_length, v_seq_length), dtype="int32") row_index = ops.cumsum(ones_mask, axis=-2) col_index = ops.cumsum(ones_mask, axis=-1) return ops.greater_equal(row_index, col_index) def compute_output_shape( self, query_shape, value_shape, key_shape=None, ): query_shape = tuple(query_shape) value_shape = tuple(value_shape) if key_shape is None: key_shape = value_shape else: key_shape = tuple(key_shape) if value_shape[1:-1] != key_shape[1:-1]: raise ValueError( "All dimensions of `value` and `key`, except the last one, " f"must be equal. Received: value_shape={value_shape} and " f"key_shape={key_shape}" ) if self._output_shape: query_shape = query_shape[:-1] + self._output_shape return query_shape def compute_output_spec( self, query, value, key=None, query_mask=None, value_mask=None, key_mask=None, attention_mask=None, return_attention_scores=False, training=None, use_causal_mask=False, ): if key is not None: key_shape = key.shape else: key_shape = None output_shape = self.compute_output_shape( query.shape, value.shape, key_shape ) output_spec = backend.KerasTensor( output_shape, dtype=self.compute_dtype ) if return_attention_scores: length = query.shape[1] attention_shape = (query.shape[0], self.num_heads, length, length) return output_spec, backend.KerasTensor( attention_shape, dtype=self.compute_dtype ) return output_spec def _index_to_einsum_variable(i): """Converts an index to a einsum variable name. We simply map indices to lowercase characters, e.g. 0 -> 'a', 1 -> 'b'. """ return string.ascii_lowercase[i] def _build_attention_equation(rank, attn_axes): """Builds einsum equations for the attention computation. Query, key, value inputs after projection are expected to have the shape as: `(bs, <non-attention dims>, <attention dims>, num_heads, channels)`. `bs` and `<non-attention dims>` are treated as `<batch dims>`. The attention operations can be generalized: 1. Query-key dot product: (<batch dims>, <query attention dims>, num_heads, channels), (<batch dims>, <key attention dims>, num_heads, channels) -> (<batch dims>, num_heads, <query attention dims>, <key attention dims>) 2. Combination: (<batch dims>, num_heads, <query attention dims>, <key attention dims>), (<batch dims>, <value attention dims>, num_heads, channels) -> (<batch dims>, <query attention dims>, num_heads, channels) Args: rank: Rank of query, key, value tensors. attn_axes: List/tuple of axes, `[-1, rank)`, that attention will be applied to. Returns: Einsum equations. """ target_notation = "" for i in range(rank): target_notation += _index_to_einsum_variable(i) # `batch_dims` includes the head dim. batch_dims = tuple(np.delete(range(rank), attn_axes + (rank - 1,))) letter_offset = rank source_notation = "" for i in range(rank): if i in batch_dims or i == rank - 1: source_notation += target_notation[i] else: source_notation += _index_to_einsum_variable(letter_offset) letter_offset += 1 product_notation = "".join( [target_notation[i] for i in batch_dims] + [target_notation[i] for i in attn_axes] + [source_notation[i] for i in attn_axes] ) dot_product_equation = "%s,%s->%s" % ( source_notation, target_notation, product_notation, ) attn_scores_rank = len(product_notation) combine_equation = "%s,%s->%s" % ( product_notation, source_notation, target_notation, ) return dot_product_equation, combine_equation, attn_scores_rank def _build_proj_equation(free_dims, bound_dims, output_dims): """Builds an einsum equation for projections inside multi-head attention.""" input_str = "" kernel_str = "" output_str = "" bias_axes = "" letter_offset = 0 for i in range(free_dims): char = _index_to_einsum_variable(i + letter_offset) input_str += char output_str += char letter_offset += free_dims for i in range(bound_dims): char = _index_to_einsum_variable(i + letter_offset) input_str += char kernel_str += char letter_offset += bound_dims for i in range(output_dims): char = _index_to_einsum_variable(i + letter_offset) kernel_str += char output_str += char bias_axes += char equation = f"{input_str},{kernel_str}->{output_str}" return equation, bias_axes, len(output_str) def _get_output_shape(output_rank, known_last_dims): return [None] * (output_rank - len(known_last_dims)) + list(known_last_dims)
MultiHeadAttention
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-azureaisearch/llama_index/vector_stores/azureaisearch/base.py
{ "start": 63547, "end": 64267 }
class ____(AzureQueryResultSearchBase): def _create_query_vector(self) -> Optional[List[Any]]: """Query vector store.""" from azure.search.documents.models import VectorizedQuery if not self._query.query_embedding: raise ValueError("Query missing embedding") vectorized_query = VectorizedQuery( vector=self._query.query_embedding, k_nearest_neighbors=self._query.hybrid_top_k or self._query.similarity_top_k, fields=self._field_mapping["embedding"], ) vector_queries = [vectorized_query] logger.info("Vector search with supplied embedding") return vector_queries
AzureQueryResultSearchDefault
python
pytorch__pytorch
torch/cuda/__init__.py
{ "start": 56574, "end": 56788 }
class ____(_CudaLegacyStorage): @classproperty def dtype(self): _warn_typed_storage_removal() return self._dtype @classproperty def _dtype(self): return torch.long
LongStorage
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-timescalevector/llama_index/vector_stores/timescalevector/base.py
{ "start": 751, "end": 9592 }
class ____(BasePydanticVectorStore): """ Timescale vector store. Examples: `pip install llama-index-vector-stores-timescalevector` ```python from llama_index.vector_stores.timescalevector import TimescaleVectorStore # Set up the Timescale service URL TIMESCALE_SERVICE_URL = "postgres://tsdbadmin:<password>@<id>.tsdb.cloud.timescale.com:<port>/tsdb?sslmode=require" # Create a TimescaleVectorStore instance vector_store = TimescaleVectorStore.from_params( service_url=TIMESCALE_SERVICE_URL, table_name="your_table_name_here", num_dimensions=1536, ) ``` """ stores_text: bool = True flat_metadata: bool = False service_url: str table_name: str num_dimensions: int time_partition_interval: Optional[timedelta] _sync_client: client.Sync = PrivateAttr() _async_client: client.Async = PrivateAttr() def __init__( self, service_url: str, table_name: str, num_dimensions: int = DEFAULT_EMBEDDING_DIM, time_partition_interval: Optional[timedelta] = None, ) -> None: table_name = table_name.lower() super().__init__( service_url=service_url, table_name=table_name, num_dimensions=num_dimensions, time_partition_interval=time_partition_interval, ) self._create_clients() self._create_tables() @classmethod def class_name(cls) -> str: return "TimescaleVectorStore" @property def client(self) -> Any: """Get client.""" return self._sync_client async def close(self) -> None: self._sync_client.close() await self._async_client.close() @classmethod def from_params( cls, service_url: str, table_name: str, num_dimensions: int = DEFAULT_EMBEDDING_DIM, time_partition_interval: Optional[timedelta] = None, ) -> "TimescaleVectorStore": return cls( service_url=service_url, table_name=table_name, num_dimensions=num_dimensions, time_partition_interval=time_partition_interval, ) def _create_clients(self) -> None: # in the normal case doesn't restrict the id type to even uuid. # Allow arbitrary text id_type = "TEXT" if self.time_partition_interval is not None: # for time partitioned tables, the id type must be UUID v1 id_type = "UUID" self._sync_client = client.Sync( self.service_url, self.table_name, self.num_dimensions, id_type=id_type, time_partition_interval=self.time_partition_interval, ) self._async_client = client.Async( self.service_url, self.table_name, self.num_dimensions, id_type=id_type, time_partition_interval=self.time_partition_interval, ) def _create_tables(self) -> None: self._sync_client.create_tables() def _node_to_row(self, node: BaseNode) -> Any: metadata = node_to_metadata_dict( node, remove_text=True, flat_metadata=self.flat_metadata, ) # reuse the node id in the common case id = node.node_id if self.time_partition_interval is not None: # for time partitioned tables, the id must be a UUID v1, # so generate one if it's not already set try: # Attempt to parse the UUID from the string parsed_uuid = uuid.UUID(id) if parsed_uuid.version != 1: id = str(uuid.uuid1()) except ValueError: id = str(uuid.uuid1()) return [ id, metadata, node.get_content(metadata_mode=MetadataMode.NONE), node.embedding, ] def add(self, nodes: List[BaseNode], **add_kwargs: Any) -> List[str]: rows_to_insert = [self._node_to_row(node) for node in nodes] ids = [result[0] for result in rows_to_insert] self._sync_client.upsert(rows_to_insert) return ids async def async_add(self, nodes: List[BaseNode], **add_kwargs: Any) -> List[str]: rows_to_insert = [self._node_to_row(node) for node in nodes] ids = [result.node_id for result in nodes] await self._async_client.upsert(rows_to_insert) return ids def _filter_to_dict( self, metadata_filters: Optional[MetadataFilters] ) -> Optional[Dict[str, str]]: if metadata_filters is None or len(metadata_filters.legacy_filters()) <= 0: return None res = {} for filter in metadata_filters.legacy_filters(): res[filter.key] = filter.value return res def _db_rows_to_query_result(self, rows: List) -> VectorStoreQueryResult: nodes = [] similarities = [] ids = [] for row in rows: try: node = metadata_dict_to_node(row[client.SEARCH_RESULT_METADATA_IDX]) node.set_content(str(row[client.SEARCH_RESULT_CONTENTS_IDX])) except Exception: # NOTE: deprecated legacy logic for backward compatibility node = TextNode( id_=row[client.SEARCH_RESULT_ID_IDX], text=row[client.SEARCH_RESULT_CONTENTS_IDX], metadata=row[client.SEARCH_RESULT_METADATA_IDX], ) similarities.append(row[client.SEARCH_RESULT_DISTANCE_IDX]) ids.append(row[client.SEARCH_RESULT_ID_IDX]) nodes.append(node) return VectorStoreQueryResult( nodes=nodes, similarities=similarities, ids=ids, ) def date_to_range_filter(self, **kwargs: Any) -> Any: constructor_args = { key: kwargs[key] for key in [ "start_date", "end_date", "time_delta", "start_inclusive", "end_inclusive", ] if key in kwargs } if not constructor_args or len(constructor_args) == 0: return None return client.UUIDTimeRange(**constructor_args) def _query_with_score( self, embedding: Optional[List[float]], limit: int = 10, metadata_filters: Optional[MetadataFilters] = None, **kwargs: Any, ) -> VectorStoreQueryResult: filter = self._filter_to_dict(metadata_filters) res = self._sync_client.search( embedding, limit, filter, uuid_time_filter=self.date_to_range_filter(**kwargs), ) return self._db_rows_to_query_result(res) async def _aquery_with_score( self, embedding: Optional[List[float]], limit: int = 10, metadata_filters: Optional[MetadataFilters] = None, **kwargs: Any, ) -> VectorStoreQueryResult: filter = self._filter_to_dict(metadata_filters) res = await self._async_client.search( embedding, limit, filter, uuid_time_filter=self.date_to_range_filter(**kwargs), ) return self._db_rows_to_query_result(res) def query(self, query: VectorStoreQuery, **kwargs: Any) -> VectorStoreQueryResult: return self._query_with_score( query.query_embedding, query.similarity_top_k, query.filters, **kwargs ) async def aquery( self, query: VectorStoreQuery, **kwargs: Any ) -> VectorStoreQueryResult: return await self._aquery_with_score( query.query_embedding, query.similarity_top_k, query.filters, **kwargs, ) def delete(self, ref_doc_id: str, **delete_kwargs: Any) -> None: filter: Dict[str, str] = {"doc_id": ref_doc_id} self._sync_client.delete_by_metadata(filter) DEFAULT_INDEX_TYPE: ClassVar = IndexType.TIMESCALE_VECTOR def create_index( self, index_type: IndexType = DEFAULT_INDEX_TYPE, **kwargs: Any ) -> None: if index_type == IndexType.PGVECTOR_IVFFLAT: self._sync_client.create_embedding_index(client.IvfflatIndex(**kwargs)) if index_type == IndexType.PGVECTOR_HNSW: self._sync_client.create_embedding_index(client.HNSWIndex(**kwargs)) if index_type == IndexType.TIMESCALE_VECTOR: self._sync_client.create_embedding_index( client.TimescaleVectorIndex(**kwargs) ) def drop_index(self) -> None: self._sync_client.drop_embedding_index()
TimescaleVectorStore
python
apache__avro
lang/py/avro/test/test_datafile.py
{ "start": 2688, "end": 6304 }
class ____(unittest.TestCase): files = None def setUp(self): """Initialize tempfiles collection.""" self.files = [] def tempfile(self): """Generate a tempfile and register it for cleanup.""" with tempfile.NamedTemporaryFile(delete=False, suffix=".avro") as f: pass self.files.append(f.name) return f.name def tearDown(self): """Clean up temporary files.""" for f in self.files: os.unlink(f) def test_append(self): """A datafile can be written to, appended to, and read from.""" for codec in CODECS_TO_VALIDATE: for schema, datum in TEST_PAIRS: # write data in binary to file once path = self.tempfile() with writer(path, schema, codec) as dfw: dfw.append(datum) # open file, write, and close nine times for _ in range(9): with writer(path, mode="ab+") as dfw: dfw.append(datum) # read data in binary from file with reader(path) as dfr: data = list(itertools.islice(dfr, 10)) self.assertRaises(StopIteration, next, dfr) self.assertEqual(len(data), 10) self.assertEqual(data, [datum] * 10) def test_round_trip(self): """A datafile can be written to and read from.""" for codec in CODECS_TO_VALIDATE: for schema, datum in TEST_PAIRS: # write data in binary to file 10 times path = self.tempfile() with writer(path, schema, codec) as dfw: for _ in range(10): dfw.append(datum) # read data in binary from file with reader(path) as dfr: data = list(itertools.islice(dfr, 10)) self.assertRaises(StopIteration, next, dfr) self.assertEqual(len(data), 10) self.assertEqual(data, [datum] * 10) def test_context_manager(self): """A datafile closes its buffer object when it exits a with block.""" path = self.tempfile() for schema, _ in TEST_PAIRS: with writer(path, schema) as dfw: self.assertFalse(dfw.writer.closed) self.assertTrue(dfw.writer.closed) with reader(path) as dfr: self.assertFalse(dfr.reader.closed) self.assertTrue(dfr.reader.closed) def test_metadata(self): """Metadata can be written to a datafile, and read from it later.""" path = self.tempfile() for schema, _ in TEST_PAIRS: with writer(path, schema) as dfw: dfw.set_meta("test.string", b"foo") dfw.set_meta("test.number", b"1") with reader(path) as dfr: self.assertEqual(b"foo", dfr.get_meta("test.string")) self.assertEqual(b"1", dfr.get_meta("test.number")) def test_empty_datafile(self): """A reader should not fail to read a file consisting of a single empty block.""" path = self.tempfile() for schema, _ in TEST_PAIRS: with writer(path, schema) as dfw: dfw.flush() # Write an empty block dfw.encoder.write_long(0) dfw.encoder.write_long(0) dfw.writer.write(dfw.sync_marker) with reader(path) as dfr: self.assertRaises(StopIteration, next, dfr)
TestDataFile
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-snowflake-cortex/destination_snowflake_cortex/cortex_processor.py
{ "start": 1433, "end": 2929 }
class ____(SqlConfig): """A Snowflake configuration for use with Cortex functions.""" host: str username: str password: SecretString warehouse: str database: str role: str schema_name: str = Field(default="PUBLIC") @property def cortex_embedding_model(self) -> str | None: """Return the Cortex embedding model name. If 'None', then we are loading pre-calculated embeddings. TODO: Implement this property or remap. """ return None @overrides def get_database_name(self) -> str: """Return the name of the database.""" return self.database @overrides def get_sql_alchemy_url(self) -> SecretString: """Return the SQLAlchemy URL to use.""" return SecretString( URL( account=self.host, user=self.username, password=self.password, database=self.database, warehouse=self.warehouse, schema=self.schema_name, role=self.role, ) ) def get_vendor_client(self) -> object: """Return the Snowflake connection object.""" return connector.connect( user=self.username, password=self.password, account=self.host, warehouse=self.warehouse, database=self.database, schema=self.schema_name, role=self.role, )
SnowflakeCortexConfig
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/base.py
{ "start": 46130, "end": 46195 }
class ____(sqltypes.TypeEngine): __visit_name__ = "MONEY"
MONEY
python
walkccc__LeetCode
solutions/2511. Maximum Enemy Forts That Can Be Captured/2511.py
{ "start": 0, "end": 254 }
class ____: def captureForts(self, forts: list[int]) -> int: ans = 0 j = 0 for i, fort in enumerate(forts): if fort != 0: # -1 or 1 if fort == -forts[j]: ans = max(ans, i - j - 1) j = i return ans
Solution
python
psf__requests
src/requests/models.py
{ "start": 6052, "end": 6788 }
class ____: def register_hook(self, event, hook): """Properly register a hook.""" if event not in self.hooks: raise ValueError(f'Unsupported event specified, with event name "{event}"') if isinstance(hook, Callable): self.hooks[event].append(hook) elif hasattr(hook, "__iter__"): self.hooks[event].extend(h for h in hook if isinstance(h, Callable)) def deregister_hook(self, event, hook): """Deregister a previously registered hook. Returns True if the hook existed, False if not. """ try: self.hooks[event].remove(hook) return True except ValueError: return False
RequestHooksMixin
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 759635, "end": 760141 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("is_private", "name", "name_with_owner") is_private = sgqlc.types.Field( sgqlc.types.non_null(Boolean), graphql_name="isPrivate" ) name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name") name_with_owner = sgqlc.types.Field( sgqlc.types.non_null(String), graphql_name="nameWithOwner" )
EnterpriseRepositoryInfo
python
getsentry__sentry
src/sentry/integrations/slack/message_builder/metric_alerts.py
{ "start": 527, "end": 2174 }
class ____(BlockSlackMessageBuilder): def __init__( self, alert_rule: AlertRule, incident: Incident | None = None, new_status: IncidentStatus | None = None, metric_value: int | None = None, chart_url: str | None = None, ) -> None: """ Builds a metric alert attachment for slack unfurling. :param alert_rule: The `AlertRule` for which to build the attachment. :param incident: The `Incident` for which to build the attachment. :param [new_status]: The new status of a metric alert incident :param [metric_value]: The value of the metric that triggered this alert to fire. If not provided we'll attempt to calculate this ourselves. """ super().__init__() self.alert_rule = alert_rule self.incident = incident self.metric_value = metric_value self.new_status = new_status self.chart_url = chart_url def build(self) -> SlackBody: data = metric_alert_unfurl_attachment_info( self.alert_rule, self.incident, self.new_status, self.metric_value ) blocks = [ self.get_markdown_block( text=f"<{data['title_link']}|*{escape_slack_text(data['title'])}*> \n{data['text']}" ) ] if self.chart_url: blocks.append(self.get_image_block(self.chart_url, alt="Metric Alert Chart")) color = LEVEL_TO_COLOR.get(INCIDENT_COLOR_MAPPING.get(data["status"], "")) return self._build_blocks( *blocks, color=color, )
SlackMetricAlertMessageBuilder
python
ray-project__ray
python/ray/data/block.py
{ "start": 1800, "end": 2383 }
class ____(str, Enum): # NOTE: This is to maintain compatibility w/ existing APIs ARROW = "pyarrow" PANDAS = "pandas" NUMPY = "numpy" # User-facing data batch type. This is the data type for data that is supplied to and # returned from batch UDFs. DataBatch = Union["pyarrow.Table", "pandas.DataFrame", Dict[str, np.ndarray]] # User-facing data column type. This is the data type for data that is supplied to and # returned from column UDFs. DataBatchColumn = Union[BlockColumn, np.ndarray] # A class type that implements __call__. CallableClass = type
BatchFormat
python
scrapy__scrapy
tests/test_spidermiddleware.py
{ "start": 21610, "end": 23700 }
class ____(TestSpiderMiddleware): @deferred_f_from_coro_f async def test_deprecated_mw_spider_arg(self): class DeprecatedSpiderArgMiddleware: def process_spider_input(self, response, spider): return None def process_spider_output(self, response, result, spider): 1 / 0 def process_spider_exception(self, response, exception, spider): return [] with ( pytest.warns( ScrapyDeprecationWarning, match=r"process_spider_input\(\) requires a spider argument", ), pytest.warns( ScrapyDeprecationWarning, match=r"process_spider_output\(\) requires a spider argument", ), pytest.warns( ScrapyDeprecationWarning, match=r"process_spider_exception\(\) requires a spider argument", ), ): self.mwman._add_middleware(DeprecatedSpiderArgMiddleware()) await self._scrape_response() @deferred_f_from_coro_f async def test_deprecated_mwman_spider_arg(self): with pytest.warns( ScrapyDeprecationWarning, match=r"Passing a spider argument to SpiderMiddlewareManager.process_start\(\)" r" is deprecated and the passed value is ignored", ): await self.mwman.process_start(DefaultSpider()) @deferred_f_from_coro_f async def test_deprecated_mwman_spider_arg_no_crawler(self): with pytest.warns( ScrapyDeprecationWarning, match=r"MiddlewareManager.__init__\(\) was called without the crawler argument", ): mwman = SpiderMiddlewareManager() with pytest.warns( ScrapyDeprecationWarning, match=r"Passing a spider argument to SpiderMiddlewareManager.process_start\(\)" r" is deprecated, SpiderMiddlewareManager should be instantiated with a Crawler", ): await mwman.process_start(DefaultSpider())
TestDeprecatedSpiderArg
python
pandas-dev__pandas
pandas/tests/indexing/test_loc.py
{ "start": 84296, "end": 86835 }
class ____: def test_loc_getitem_partial_string_slicing_datetimeindex(self): # GH#35509 df = DataFrame( {"col1": ["a", "b", "c"], "col2": [1, 2, 3]}, index=to_datetime(["2020-08-01", "2020-07-02", "2020-08-05"]), ) expected = DataFrame( {"col1": ["a", "c"], "col2": [1, 3]}, index=to_datetime(["2020-08-01", "2020-08-05"]), ) result = df.loc["2020-08"] tm.assert_frame_equal(result, expected) def test_loc_getitem_partial_string_slicing_with_periodindex(self): pi = pd.period_range(start="2017-01-01", end="2018-01-01", freq="M") ser = pi.to_series() result = ser.loc[:"2017-12"] expected = ser.iloc[:-1] tm.assert_series_equal(result, expected) def test_loc_getitem_partial_string_slicing_with_timedeltaindex(self): ix = timedelta_range(start="1 day", end="2 days", freq="1h") ser = ix.to_series() result = ser.loc[:"1 days"] expected = ser.iloc[:-1] tm.assert_series_equal(result, expected) def test_loc_getitem_str_timedeltaindex(self): # GH#16896 df = DataFrame({"x": range(3)}, index=to_timedelta(range(3), unit="days")) expected = df.iloc[0] sliced = df.loc["0 days"] tm.assert_series_equal(sliced, expected) @pytest.mark.parametrize("indexer_end", [None, "2020-01-02 23:59:59.999999999"]) def test_loc_getitem_partial_slice_non_monotonicity( self, tz_aware_fixture, indexer_end, frame_or_series ): # GH#33146 obj = frame_or_series( [1] * 5, index=DatetimeIndex( [ Timestamp("2019-12-30"), Timestamp("2020-01-01"), Timestamp("2019-12-25"), Timestamp("2020-01-02 23:59:59.999999999"), Timestamp("2019-12-19"), ], tz=tz_aware_fixture, ), ) expected = frame_or_series( [1] * 2, index=DatetimeIndex( [ Timestamp("2020-01-01"), Timestamp("2020-01-02 23:59:59.999999999"), ], tz=tz_aware_fixture, ), ) indexer = slice("2020-01-01", indexer_end) result = obj[indexer] tm.assert_equal(result, expected) result = obj.loc[indexer] tm.assert_equal(result, expected)
TestPartialStringSlicing
python
spyder-ide__spyder
spyder/plugins/plots/widgets/main_widget.py
{ "start": 1437, "end": 1636 }
class ____: ZoomSpinBox = 'zoom_spin' ToolbarStretcher = 'toolbar_stretcher' # --- Widgets # ----------------------------------------------------------------------------
PlotsWidgetToolbarItems
python
pydantic__pydantic
pydantic-core/tests/serializers/test_any.py
{ "start": 28919, "end": 29031 }
class ____(ipaddress.IPv4Address): def __str__(self): return super().__str__() + '_subclassed'
SubIpV4
python
xlwings__xlwings
tests/restapi/__init__.py
{ "start": 105, "end": 1417 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls): # Flask api.config["TESTING"] = True cls.client = api.test_client() # xlwings cls.app1 = xw.App() cls.app2 = xw.App() cls.wb1 = cls.app1.books.add() cls.wb1b = cls.app1.books.add() cls.wb2 = cls.app2.books.add() for wb in [cls.wb1, cls.wb2]: if len(wb.sheets) == 1: wb.sheets.add(after=1) sheet1 = cls.wb1.sheets[0] sheet1["A1"].value = [[1.1, "a string"], [dt.datetime.now(), None]] sheet1["A1"].formula = "=1+1.1" chart = sheet1.charts.add() chart.set_source_data(sheet1["A1"]) chart.chart_type = "line" pic = os.path.abspath(os.path.join("..", "sample_picture.png")) pic = sheet1.pictures.add(pic) pic.name = "Picture 1" cls.wb1.sheets[0].range("B2:C3").name = "Sheet1!myname1" cls.wb1.sheets[0].range("A1").name = "myname2" cls.wb1.save("Book1.xlsx") cls.wb1 = xw.Book("Book1.xlsx") # hack as save doesn't return the wb properly cls.app1.activate() @classmethod def tearDownClass(cls): wb_path = cls.wb1.fullname cls.app1.kill() cls.app2.kill() os.remove(wb_path)
TestCase
python
getsentry__sentry
src/sentry/seer/anomaly_detection/types.py
{ "start": 1827, "end": 1997 }
class ____(StrEnum): HIGH_CONFIDENCE = "anomaly_higher_confidence" LOW_CONFIDENCE = "anomaly_lower_confidence" NONE = "none" NO_DATA = "no_data"
AnomalyType
python
huggingface__transformers
tests/models/cwm/test_modeling_cwm.py
{ "start": 1112, "end": 1709 }
class ____(CausalLMModelTester): if is_torch_available(): config_class = CwmConfig base_model_class = CwmModel causal_lm_class = CwmForCausalLM def get_config(self): config = super().get_config() config.sliding_window = 8192 config.rope_parameters = { "factor": 16.0, "high_freq_factor": 4.0, "low_freq_factor": 1.0, "original_max_position_embeddings": 8192, "rope_type": "llama3", "rope_theta": 1000000.0, } return config @require_torch
CwmModelTester
python
pytorch__pytorch
test/functorch/test_aotdispatch.py
{ "start": 176685, "end": 221778 }
class ____(AOTTestCase): def setUp(self): super().setUp() torch._dynamo.reset() def test_aot_export_ban_dropout_mut_pre_dispatch(self): def fn(p, x): y = torch.ops.aten.dropout.default(x, 0.1, train=False) y.add_(1) return (y,) mod = TestMod(fn) inp = torch.randn(2, 2) with self.assertRaisesRegex( RuntimeError, "cannot mutate tensors with frozen storage" ): aot_export_module(mod, [inp], trace_joint=False, pre_dispatch=True) gm, _ = aot_export_module(mod, [inp], trace_joint=False, pre_dispatch=False) self.assertExpectedInline( str(gm.code).strip(), """\ def forward(self, arg0_1, arg1_1): clone = torch.ops.aten.clone.default(arg1_1); arg1_1 = None add = torch.ops.aten.add.Tensor(clone, 1); clone = None return (add,)""", ) fw_graph_cell = [None] bw_graph_cell = [None] aot_function( fn, fw_compiler=partial(extract_graph, graph_cell=fw_graph_cell), bw_compiler=partial(extract_graph, graph_cell=bw_graph_cell), partition_fn=default_partition, decompositions=default_decompositions, dynamic=True, )(*inp) fw_graph = fw_graph_cell[0] self.assertExpectedInline( str(fw_graph.code).strip(), """\ def forward(self, arg0_1, arg1_1): clone = torch.ops.aten.clone.default(arg1_1); arg1_1 = None add = torch.ops.aten.add.Tensor(clone, 1); clone = None return (add,)""", ) def test_aot_export_predispatch_func_simple(self): def fn(p, x): y = x + 2 with torch.no_grad(): y.add_(2) return (x * 2 + y,) mod = TestMod(fn) inp = torch.randn(2, 2) with torch.no_grad(): gm, _ = aot_export_module(mod, [inp], trace_joint=False, pre_dispatch=True) self.assertExpectedInline( str(gm.code).strip(), """\ def forward(self, arg0_1, arg1_1): add = torch.ops.aten.add.Tensor(arg1_1, 2) _set_grad_enabled = torch._C._set_grad_enabled(False); _set_grad_enabled = None add_1 = torch.ops.aten.add.Tensor(add, 2); add = None _set_grad_enabled_1 = torch._C._set_grad_enabled(False); _set_grad_enabled_1 = None mul = torch.ops.aten.mul.Tensor(arg1_1, 2); arg1_1 = None add_2 = torch.ops.aten.add.Tensor(mul, add_1); mul = add_1 = None return (add_2,)""", ) def test_aot_export_predispatch_func_composite_implicit(self): def fn(p, x): with torch.enable_grad(): y = x @ x y.add_(2) return (x.sum() + y.sum(),) mod = TestMod(fn) inp = torch.randn(2, 2) with torch.no_grad(): gm, _ = aot_export_module(mod, [inp], trace_joint=False, pre_dispatch=True) self.assertExpectedInline( str(gm.code).strip(), """\ def forward(self, arg0_1, arg1_1): _set_grad_enabled = torch._C._set_grad_enabled(True); _set_grad_enabled = None matmul = torch.ops.aten.matmul.default(arg1_1, arg1_1) _set_grad_enabled_1 = torch._C._set_grad_enabled(False); _set_grad_enabled_1 = None add = torch.ops.aten.add.Tensor(matmul, 2); matmul = None sum_1 = torch.ops.aten.sum.default(arg1_1); arg1_1 = None sum_2 = torch.ops.aten.sum.default(add); add = None add_1 = torch.ops.aten.add.Tensor(sum_1, sum_2); sum_1 = sum_2 = None return (add_1,)""", ) def test_aot_export_predispatch_composite_implicit_inplace(self): def fn(x, p): return (torch.ops.aten.absolute_.default(x.clone()),) mod = TestMod(fn) inp = torch.randn(2, 2) gm, _ = aot_export_module(mod, [inp], trace_joint=False, pre_dispatch=True) self.assertExpectedInline( str(gm.code).strip(), """\ def forward(self, arg0_1, arg1_1): clone = torch.ops.aten.clone.default(arg0_1); arg0_1 = None abs_1 = torch.ops.aten.abs.default(clone); clone = None return (abs_1,)""", ) def test_aot_export_predispatch_composite_implicit_linear(self): class MM(torch.nn.Module): def __init__(self) -> None: super().__init__() self.linear = torch.nn.Linear(2, 2) def forward(self, x): return (self.linear(x),) mod = MM() inp = torch.randn(2, 2) gm, _ = aot_export_module(mod, [inp], trace_joint=False, pre_dispatch=True) self.assertExpectedInline( str(gm.code).strip(), """\ def forward(self, arg0_1, arg1_1, arg2_1): linear = torch.ops.aten.linear.default(arg2_1, arg0_1, arg1_1); arg2_1 = arg0_1 = arg1_1 = None return (linear,)""", ) @unittest.expectedFailure def test_aot_export_predispatch_outdtype(self): class M(torch.nn.Module): def __init__(self, weight): super().__init__() self.weight = weight def forward(self, x): y = x + 2 y.add_(5) return ( out_dtype(torch.ops.aten.mm.default, torch.int32, y, self.weight), ) weight = torch.randint(-128, 127, (5, 5), dtype=torch.int8) mod = M(weight) inp = torch.randint(-128, 127, (5, 5), dtype=torch.int8) gm, _ = aot_export_module(mod, [inp], trace_joint=False, pre_dispatch=True) self.assertExpectedInline( str(gm.code).strip(), """\ def forward(self, arg0_1, arg1_1): _set_grad_enabled = torch._C._set_grad_enabled(True); _set_grad_enabled = None mm = torch.ops.aten.mm.default(arg1_1, arg1_1) _set_grad_enabled_1 = torch._C._set_grad_enabled(False); _set_grad_enabled_1 = None add = torch.ops.aten.add.Tensor(mm, 2); mm = None sum_1 = torch.ops.aten.sum.default(arg1_1); arg1_1 = None sum_2 = torch.ops.aten.sum.default(add); add = None add_1 = torch.ops.aten.add.Tensor(sum_1, sum_2); sum_1 = sum_2 = None return (add_1,)""", ) def test_aot_export_predispatch_func_view(self): def fn(p, x): y = x @ x y.add_(2) return (x.sum() + y.view(1, 4).sum(),) mod = TestMod(fn) inp = torch.randn(2, 2) gm, _ = aot_export_module(mod, [inp], trace_joint=False, pre_dispatch=True) self.assertExpectedInline( str(gm.code).strip(), """\ def forward(self, arg0_1, arg1_1): matmul = torch.ops.aten.matmul.default(arg1_1, arg1_1) add = torch.ops.aten.add.Tensor(matmul, 2); matmul = None sum_1 = torch.ops.aten.sum.default(arg1_1); arg1_1 = None view_1 = torch.ops.aten.view.default(add, [1, 4]); add = None sum_2 = torch.ops.aten.sum.default(view_1); view_1 = None add_1 = torch.ops.aten.add.Tensor(sum_1, sum_2); sum_1 = sum_2 = None return (add_1,)""", ) def test_aot_export_predispatch_buffer_mutation_metadata(self): class Foo(torch.nn.Module): def __init__(self) -> None: super().__init__() self.foo = torch.nn.Buffer(torch.zeros(2, 2)) def forward(self, x): self.foo.add_(4) return (x.sum() + self.foo.sum(),) inp = torch.randn(2, 2) gm, graph_sig = aot_export_module( Foo(), [inp], trace_joint=False, pre_dispatch=True ) self.assertExpectedInline( str(gm.code).strip(), """\ def forward(self, arg0_1, arg1_1): add = torch.ops.aten.add.Tensor(arg0_1, 4); arg0_1 = None sum_1 = torch.ops.aten.sum.default(arg1_1); arg1_1 = None sum_2 = torch.ops.aten.sum.default(add) add_1 = torch.ops.aten.add.Tensor(sum_1, sum_2); sum_1 = sum_2 = None return (add, add_1)""", ) eager_mod = Foo() output_1, output_2 = gm(torch.zeros(2, 2), inp) eager_output = eager_mod(inp) self.assertTrue(torch.allclose(output_2, eager_output[0])) _, output_2 = gm(output_1, inp) eager_output = eager_mod(inp) self.assertTrue(torch.allclose(output_2, eager_output[0])) self.assertTrue("foo" in graph_sig.buffers) self.assertTrue(graph_sig.inputs_to_buffers["arg0_1"] == "foo") def test_aot_export_predispatch_with_autograd_op(self): def foo(p, x): with torch.enable_grad(): y = x + 5 y.add_(5) y.add_(7) return (x.cos() + y.sin(),) inp = torch.randn(2, 2) mod = TestMod(foo) with torch.no_grad(): gm, _ = aot_export_module(mod, [inp], trace_joint=False, pre_dispatch=True) self.assertExpectedInline( str(gm.code).strip(), """\ def forward(self, arg0_1, arg1_1): _set_grad_enabled = torch._C._set_grad_enabled(True); _set_grad_enabled = None add = torch.ops.aten.add.Tensor(arg1_1, 5) add_1 = torch.ops.aten.add.Tensor(add, 5); add = None add_2 = torch.ops.aten.add.Tensor(add_1, 7); add_1 = None cos = torch.ops.aten.cos.default(arg1_1); arg1_1 = None sin = torch.ops.aten.sin.default(add_2); add_2 = None add_3 = torch.ops.aten.add.Tensor(cos, sin); cos = sin = None _set_grad_enabled_1 = torch._C._set_grad_enabled(False); _set_grad_enabled_1 = None return (add_3,)""", ) @unittest.skipIf(IS_WINDOWS, "Windows isn't supported for this case") @unittest.skipIf( not torchdynamo.is_dynamo_supported(), "TorchDynamo is not supported" ) def test_aot_export_predispatch_with_cond_nested(self): class M(torch.nn.Module): def __init__(self) -> None: super().__init__() def forward(self, x): def true_fn(x): y = x.sin() y.add_(5) def true_true_fn(x): y = x.sin() y.add_(7) return y.sin() def true_false_fn(x): return x.cos() return torch.cond( y.cos().sum() > 5, true_true_fn, true_false_fn, [y.cos()] ) def false_fn(x): z = x.cos() z.add_(6) return z.sin() a = torch.cond(x.sum() > 4, true_fn, false_fn, [x]) return (a + 3, a + 4) inp = torch.randn(2, 2) gm, _ = aot_export_module(M(), [inp], trace_joint=False, pre_dispatch=True) self.assertExpectedInline( str(gm.code).strip(), """\ def forward(self, arg0_1): sum_1 = torch.ops.aten.sum.default(arg0_1) gt = torch.ops.aten.gt.Scalar(sum_1, 4); sum_1 = None true_graph_0 = self.true_graph_0 false_graph_0 = self.false_graph_0 cond = torch.ops.higher_order.cond(gt, true_graph_0, false_graph_0, (arg0_1,)); gt = true_graph_0 = false_graph_0 = arg0_1 = None getitem = cond[0]; cond = None add = torch.ops.aten.add.Tensor(getitem, 3) add_1 = torch.ops.aten.add.Tensor(getitem, 4); getitem = None return (add, add_1)""", # noqa: B950 ) self.assertExpectedInline( str(gm.true_graph_0.code).strip(), """\ def forward(self, arg0_1): sin = torch.ops.aten.sin.default(arg0_1); arg0_1 = None add = torch.ops.aten.add.Tensor(sin, 5); sin = None cos = torch.ops.aten.cos.default(add) sum_1 = torch.ops.aten.sum.default(cos); cos = None gt = torch.ops.aten.gt.Scalar(sum_1, 5); sum_1 = None cos_1 = torch.ops.aten.cos.default(add); add = None true_graph_0 = self.true_graph_0 false_graph_0 = self.false_graph_0 cond = torch.ops.higher_order.cond(gt, true_graph_0, false_graph_0, (cos_1,)); gt = true_graph_0 = false_graph_0 = cos_1 = None getitem = cond[0]; cond = None return (getitem,)""", # noqa: B950 ) self.assertExpectedInline( str(gm.true_graph_0.true_graph_0.code).strip(), """\ def forward(self, arg0_1): sin = torch.ops.aten.sin.default(arg0_1); arg0_1 = None add = torch.ops.aten.add.Tensor(sin, 7); sin = None sin_1 = torch.ops.aten.sin.default(add); add = None return (sin_1,)""", ) @unittest.skipIf(IS_WINDOWS, "Windows isn't supported for this case") @unittest.skipIf( not torchdynamo.is_dynamo_supported(), "TorchDynamo is not supported" ) def test_aot_export_predispatch_map_1(self): class M(torch.nn.Module): def __init__(self) -> None: super().__init__() def forward(self, x, y): def true_fn(x, r): y = x.sin() y.add_(5) return y.cos() + r.sum() def false_fn(x, r): z = x.cos() def f(x, y): a = x.cos() a.add_(5) return a + y return ( z + control_flow.map(f, z, r).sum() + control_flow.map(f, z, r).sum() ) a = torch.cond(x.sum() > 4, true_fn, false_fn, [x, y]) return (a + 3, a + 4) inps = [torch.randn(2, 2), torch.ones(2)] gm, _ = aot_export_module(M(), inps, trace_joint=False, pre_dispatch=True) self.assertExpectedInline( normalize_gm(gm.print_readable(False, expanded_def=True)), """\ class <lambda>(torch.nn.Module): def forward( self, arg0_1: "f32[2, 2]", # PlainAOTInput(idx=0) arg1_1: "f32[2]", # PlainAOTInput(idx=1) ): sum_1: "f32[]" = torch.ops.aten.sum.default(arg0_1) gt: "b8[]" = torch.ops.aten.gt.Scalar(sum_1, 4); sum_1 = None true_graph_0 = self.true_graph_0 false_graph_0 = self.false_graph_0 cond = torch.ops.higher_order.cond(gt, true_graph_0, false_graph_0, (arg0_1, arg1_1)); gt = true_graph_0 = false_graph_0 = arg0_1 = arg1_1 = None getitem: "f32[2, 2]" = cond[0]; cond = None add: "f32[2, 2]" = torch.ops.aten.add.Tensor(getitem, 3) add_1: "f32[2, 2]" = torch.ops.aten.add.Tensor(getitem, 4); getitem = None return ( add, # PlainAOTOutput(idx=0) add_1, # PlainAOTOutput(idx=1) ) class true_graph_0(torch.nn.Module): def forward(self, arg0_1: "f32[2, 2]", arg1_1: "f32[2]"): sin: "f32[2, 2]" = torch.ops.aten.sin.default(arg0_1); arg0_1 = None add: "f32[2, 2]" = torch.ops.aten.add.Tensor(sin, 5); sin = None cos: "f32[2, 2]" = torch.ops.aten.cos.default(add); add = None sum_1: "f32[]" = torch.ops.aten.sum.default(arg1_1); arg1_1 = None add_1: "f32[2, 2]" = torch.ops.aten.add.Tensor(cos, sum_1); cos = sum_1 = None return (add_1,) class false_graph_0(torch.nn.Module): def forward(self, arg0_1: "f32[2, 2]", arg1_1: "f32[2]"): cos: "f32[2, 2]" = torch.ops.aten.cos.default(arg0_1); arg0_1 = None body_graph_0 = self.body_graph_0 map_impl = torch.ops.higher_order.map_impl(body_graph_0, [cos], [arg1_1]); body_graph_0 = None getitem_2: "f32[2, 2]" = map_impl[0]; map_impl = None sum_1: "f32[]" = torch.ops.aten.sum.default(getitem_2); getitem_2 = None add: "f32[2, 2]" = torch.ops.aten.add.Tensor(cos, sum_1); sum_1 = None body_graph_1 = self.body_graph_1 map_impl_1 = torch.ops.higher_order.map_impl(body_graph_1, [cos], [arg1_1]); body_graph_1 = cos = arg1_1 = None getitem_5: "f32[2, 2]" = map_impl_1[0]; map_impl_1 = None sum_2: "f32[]" = torch.ops.aten.sum.default(getitem_5); getitem_5 = None add_1: "f32[2, 2]" = torch.ops.aten.add.Tensor(add, sum_2); add = sum_2 = None return (add_1,) class body_graph_0(torch.nn.Module): def forward(self, arg0_1: "f32[2]", arg1_1: "f32[2]"): cos: "f32[2]" = torch.ops.aten.cos.default(arg0_1); arg0_1 = None add: "f32[2]" = torch.ops.aten.add.Tensor(cos, 5); cos = None add_1: "f32[2]" = torch.ops.aten.add.Tensor(add, arg1_1); add = arg1_1 = None return (add_1,) class body_graph_1(torch.nn.Module): def forward(self, arg0_1: "f32[2]", arg1_1: "f32[2]"): cos: "f32[2]" = torch.ops.aten.cos.default(arg0_1); arg0_1 = None add: "f32[2]" = torch.ops.aten.add.Tensor(cos, 5); cos = None add_1: "f32[2]" = torch.ops.aten.add.Tensor(add, arg1_1); add = arg1_1 = None return (add_1,) """, # noqa: B950 ) def test_aot_export_predispatch_map_2(self): class M(torch.nn.Module): def __init__(self) -> None: super().__init__() def forward(self, x, y): z = x.cos() def f(x, y): a = x.cos() a.add_(5) return a + y return (z + control_flow.map(f, z, y).sum(),) inps = [torch.randn(2, 2), torch.ones(2)] gm, _ = aot_export_module(M(), inps, trace_joint=False, pre_dispatch=True) self.assertExpectedInline( normalize_gm(gm.print_readable(False, expanded_def=True)), """\ class <lambda>(torch.nn.Module): def forward( self, arg0_1: "f32[2, 2]", # PlainAOTInput(idx=0) arg1_1: "f32[2]", # PlainAOTInput(idx=1) ): cos: "f32[2, 2]" = torch.ops.aten.cos.default(arg0_1); arg0_1 = None body_graph_0 = self.body_graph_0 map_impl = torch.ops.higher_order.map_impl(body_graph_0, [cos], [arg1_1]); body_graph_0 = arg1_1 = None getitem_2: "f32[2, 2]" = map_impl[0]; map_impl = None sum_1: "f32[]" = torch.ops.aten.sum.default(getitem_2); getitem_2 = None add: "f32[2, 2]" = torch.ops.aten.add.Tensor(cos, sum_1); cos = sum_1 = None return ( add, # PlainAOTOutput(idx=0) ) class body_graph_0(torch.nn.Module): def forward(self, arg0_1: "f32[2]", arg1_1: "f32[2]"): cos: "f32[2]" = torch.ops.aten.cos.default(arg0_1); arg0_1 = None add: "f32[2]" = torch.ops.aten.add.Tensor(cos, 5); cos = None add_1: "f32[2]" = torch.ops.aten.add.Tensor(add, arg1_1); add = arg1_1 = None return (add_1,) """, ) @unittest.skipIf(IS_WINDOWS, "Windows isn't supported for this case") @unittest.skipIf( not torchdynamo.is_dynamo_supported(), "TorchDynamo is not supported" ) def test_aot_export_predispatch_with_cond(self): class M(torch.nn.Module): def __init__(self) -> None: super().__init__() def forward(self, x): def true_fn(x): y = x.sin() z = torch.ops.aten.linear.default(y, torch.randn(2, 2)) z.add_(5) return z.cos() def false_fn(x): z = x.cos() z.add_(6) return z.sin() a = torch.cond(x.sum() > 4, true_fn, false_fn, [x]) return (a + 3, a + 4) inp = torch.randn(2, 2) gm, _ = aot_export_module(M(), [inp], trace_joint=False, pre_dispatch=True) self.assertExpectedInline( str(gm.code).strip(), """\ def forward(self, arg0_1): sum_1 = torch.ops.aten.sum.default(arg0_1) gt = torch.ops.aten.gt.Scalar(sum_1, 4); sum_1 = None true_graph_0 = self.true_graph_0 false_graph_0 = self.false_graph_0 cond = torch.ops.higher_order.cond(gt, true_graph_0, false_graph_0, (arg0_1,)); gt = true_graph_0 = false_graph_0 = arg0_1 = None getitem = cond[0]; cond = None add = torch.ops.aten.add.Tensor(getitem, 3) add_1 = torch.ops.aten.add.Tensor(getitem, 4); getitem = None return (add, add_1)""", # noqa: B950 ) self.assertExpectedInline( str(gm.true_graph_0.code).strip(), """\ def forward(self, arg0_1): sin = torch.ops.aten.sin.default(arg0_1); arg0_1 = None randn = torch.ops.aten.randn.default([2, 2], device = device(type='cpu'), pin_memory = False) linear = torch.ops.aten.linear.default(sin, randn); sin = randn = None add = torch.ops.aten.add.Tensor(linear, 5); linear = None cos = torch.ops.aten.cos.default(add); add = None return (cos,)""", ) def test_aot_export_predispatch_conv_and_bn(self): class ConvBatchnorm(torch.nn.Module): def __init__(self) -> None: super().__init__() self.conv = torch.nn.Conv2d(1, 3, 1, 1) self.bn = torch.nn.BatchNorm2d(3) def forward(self, x): x = self.conv(x) x = self.bn(x) return (x,) mod = ConvBatchnorm() mod.train() inp = torch.randn(1, 1, 3, 3) gm, _ = aot_export_module(mod, [inp], trace_joint=False, pre_dispatch=True) self.assertExpectedInline( str(gm.code).strip(), """\ def forward(self, arg0_1, arg1_1, arg2_1, arg3_1, arg4_1, arg5_1, arg6_1, arg7_1): conv2d = torch.ops.aten.conv2d.default(arg7_1, arg0_1, arg1_1); arg7_1 = arg0_1 = arg1_1 = None add = torch.ops.aten.add.Tensor(arg6_1, 1); arg6_1 = None _native_batch_norm_legit_functional = torch.ops.aten._native_batch_norm_legit_functional.default(conv2d, arg2_1, arg3_1, arg4_1, arg5_1, True, 0.1, 1e-05); conv2d = arg2_1 = arg3_1 = arg4_1 = arg5_1 = None getitem = _native_batch_norm_legit_functional[0] getitem_3 = _native_batch_norm_legit_functional[3] getitem_4 = _native_batch_norm_legit_functional[4]; _native_batch_norm_legit_functional = None return (getitem_3, getitem_4, add, getitem)""", # noqa: B950 ) def test_aot_export_predispatch_reshape(self): class Reshape(torch.nn.Module): def forward(self, x): y = x.reshape(4, 4) return (y.sum(),) mod = Reshape() inp = torch.randn(2, 8) gm, _ = aot_export_module(mod, [inp], trace_joint=False, pre_dispatch=True) self.assertExpectedInline( str(gm.code).strip(), """\ def forward(self, arg0_1): view = torch.ops.aten.view.default(arg0_1, [4, 4]); arg0_1 = None sum_1 = torch.ops.aten.sum.default(view); view = None return (sum_1,)""", ) # noqa: B950 def test_aot_export_predispatch_contiguous(self): class Cont(torch.nn.Module): def forward(self, x): y = torch.ops.aten.contiguous.default(x) return (y.sum(),) mod = Cont() inp = torch.randn(2, 8) gm, _ = aot_export_module(mod, [inp], trace_joint=False, pre_dispatch=True) self.assertExpectedInline( str(gm.code).strip(), """\ def forward(self, arg0_1): sum_1 = torch.ops.aten.sum.default(arg0_1); arg0_1 = None return (sum_1,)""", ) # noqa: B950 def test_aot_export_module_joint(self): class ConvBatchnormRelu(torch.nn.Module): def __init__(self) -> None: super().__init__() self.conv = torch.nn.Conv2d(1, 3, 1, 1) self.bn = torch.nn.BatchNorm2d(3) def forward(self, x): x = self.conv(x) x = self.bn(x) user_out = torch.nn.functional.relu(x) loss = user_out.sum() return loss, user_out.detach() mod = ConvBatchnormRelu() mod.train() inp = torch.randn(1, 1, 3, 3) mod(inp) fx_g, signature = aot_export_module( mod, [inp], trace_joint=True, output_loss_index=0 ) # Some important characteristics of the exported graph below: # 8 arguments: 2 params from conv, 2 params from batchnorm, 2 buffers from 1 batchnorm, 1 user input # 9 outputs: 3 mutated buffers (from batchnorm), 2 user outputs and 4 gradients (since there were 4 parameters) for node in fx_g.graph.nodes: node.meta.pop("stack_trace", None) self.assertExpectedInline( fx_g.print_readable(print_output=False, expanded_def=True), """\ class <lambda>(torch.nn.Module): def forward( self, arg0_1: "f32[3, 1, 1, 1]", arg1_1: "f32[3]", arg2_1: "f32[3]", arg3_1: "f32[3]", arg4_1: "f32[3]", arg5_1: "f32[3]", arg6_1: "i64[]", arg7_1: "f32[1, 1, 3, 3]", ): # No stacktrace found for following nodes convolution: "f32[1, 3, 3, 3]" = torch.ops.aten.convolution.default(arg7_1, arg0_1, arg1_1, [1, 1], [0, 0], [1, 1], False, [0, 0], 1); arg1_1 = None add: "i64[]" = torch.ops.aten.add.Tensor(arg6_1, 1); arg6_1 = None _native_batch_norm_legit_functional = torch.ops.aten._native_batch_norm_legit_functional.default(convolution, arg2_1, arg3_1, arg4_1, arg5_1, True, 0.1, 1e-05); arg3_1 = arg4_1 = arg5_1 = None getitem: "f32[1, 3, 3, 3]" = _native_batch_norm_legit_functional[0] getitem_1: "f32[3]" = _native_batch_norm_legit_functional[1] getitem_2: "f32[3]" = _native_batch_norm_legit_functional[2] getitem_3: "f32[3]" = _native_batch_norm_legit_functional[3] getitem_4: "f32[3]" = _native_batch_norm_legit_functional[4]; _native_batch_norm_legit_functional = None relu: "f32[1, 3, 3, 3]" = torch.ops.aten.relu.default(getitem); getitem = None detach: "f32[1, 3, 3, 3]" = torch.ops.aten.detach.default(relu); detach = None detach_1: "f32[1, 3, 3, 3]" = torch.ops.aten.detach.default(relu) sum_1: "f32[]" = torch.ops.aten.sum.default(relu) detach_2: "f32[1, 3, 3, 3]" = torch.ops.aten.detach.default(relu); relu = None ones_like: "f32[]" = torch.ops.aten.ones_like.default(sum_1, pin_memory = False, memory_format = torch.preserve_format) expand: "f32[1, 3, 3, 3]" = torch.ops.aten.expand.default(ones_like, [1, 3, 3, 3]); ones_like = None detach_3: "f32[1, 3, 3, 3]" = torch.ops.aten.detach.default(detach_1); detach_1 = None threshold_backward: "f32[1, 3, 3, 3]" = torch.ops.aten.threshold_backward.default(expand, detach_3, 0); expand = detach_3 = None native_batch_norm_backward = torch.ops.aten.native_batch_norm_backward.default(threshold_backward, convolution, arg2_1, getitem_3, getitem_4, getitem_1, getitem_2, True, 1e-05, [True, True, True]); threshold_backward = convolution = arg2_1 = getitem_1 = getitem_2 = None getitem_5: "f32[1, 3, 3, 3]" = native_batch_norm_backward[0] getitem_6: "f32[3]" = native_batch_norm_backward[1] getitem_7: "f32[3]" = native_batch_norm_backward[2]; native_batch_norm_backward = None convolution_backward = torch.ops.aten.convolution_backward.default(getitem_5, arg7_1, arg0_1, [3], [1, 1], [0, 0], [1, 1], False, [0, 0], 1, [False, True, True]); getitem_5 = arg7_1 = arg0_1 = None getitem_8 = convolution_backward[0]; getitem_8 = None getitem_9: "f32[3, 1, 1, 1]" = convolution_backward[1] getitem_10: "f32[3]" = convolution_backward[2]; convolution_backward = None return (getitem_3, getitem_4, add, sum_1, detach_2, getitem_9, getitem_10, getitem_6, getitem_7) """, # noqa: B950 ) self.assertExpectedInline( str(signature.parameters), """['conv.weight', 'conv.bias', 'bn.weight', 'bn.bias']""", ) self.assertExpectedInline( str(signature.buffers), """['bn.running_mean', 'bn.running_var', 'bn.num_batches_tracked']""", ) self.assertExpectedInline(str(signature.user_inputs), """['arg7_1']""") self.assertExpectedInline( str(signature.inputs_to_parameters), """{'arg0_1': 'conv.weight', 'arg1_1': 'conv.bias', 'arg2_1': 'bn.weight', 'arg3_1': 'bn.bias'}""", ) # noqa: B950 self.assertExpectedInline( str(signature.inputs_to_buffers), """{'arg4_1': 'bn.running_mean', 'arg5_1': 'bn.running_var', 'arg6_1': 'bn.num_batches_tracked'}""", ) # noqa: B950 self.assertExpectedInline( str(signature.buffers_to_mutate), """{'getitem_3': 'bn.running_mean', 'getitem_4': 'bn.running_var', 'add': 'bn.num_batches_tracked'}""", ) # noqa: B950 self.assertExpectedInline( str(signature.backward_signature.gradients_to_parameters), """{'getitem_9': 'conv.weight', 'getitem_10': 'conv.bias', 'getitem_6': 'bn.weight', 'getitem_7': 'bn.bias'}""", ) # noqa: B950 self.assertExpectedInline( str(signature.backward_signature.gradients_to_user_inputs), """{}""" ) self.assertExpectedInline( str(signature.backward_signature.loss_output), """getitem_3""" ) # Also check the inference graph # Main important thing here is that there are 5 total outputs: 3 total mutated buffers (from batchnorm), 2 user outputs. fx_g_inference, signature_inference = aot_export_module( mod, [inp], trace_joint=False ) for node in fx_g_inference.graph.nodes: node.meta.pop("stack_trace", None) self.assertExpectedInline( fx_g_inference.print_readable(print_output=False, expanded_def=True), """\ class <lambda>(torch.nn.Module): def forward( self, arg0_1: "f32[3, 1, 1, 1]", # PlainAOTInput(idx=0) arg1_1: "f32[3]", # PlainAOTInput(idx=1) arg2_1: "f32[3]", # PlainAOTInput(idx=2) arg3_1: "f32[3]", # PlainAOTInput(idx=3) arg4_1: "f32[3]", # PlainAOTInput(idx=4) arg5_1: "f32[3]", # PlainAOTInput(idx=5) arg6_1: "i64[]", # PlainAOTInput(idx=6) arg7_1: "f32[1, 1, 3, 3]", # PlainAOTInput(idx=7) ): # No stacktrace found for following nodes convolution: "f32[1, 3, 3, 3]" = torch.ops.aten.convolution.default(arg7_1, arg0_1, arg1_1, [1, 1], [0, 0], [1, 1], False, [0, 0], 1); arg7_1 = arg0_1 = arg1_1 = None add: "i64[]" = torch.ops.aten.add.Tensor(arg6_1, 1); arg6_1 = None _native_batch_norm_legit_functional = torch.ops.aten._native_batch_norm_legit_functional.default(convolution, arg2_1, arg3_1, arg4_1, arg5_1, True, 0.1, 1e-05); convolution = arg2_1 = arg3_1 = arg4_1 = arg5_1 = None getitem: "f32[1, 3, 3, 3]" = _native_batch_norm_legit_functional[0] getitem_3: "f32[3]" = _native_batch_norm_legit_functional[3] getitem_4: "f32[3]" = _native_batch_norm_legit_functional[4]; _native_batch_norm_legit_functional = None relu: "f32[1, 3, 3, 3]" = torch.ops.aten.relu.default(getitem); getitem = None sum_1: "f32[]" = torch.ops.aten.sum.default(relu) detach: "f32[1, 3, 3, 3]" = torch.ops.aten.detach.default(relu); relu = None return ( getitem_3, # InputMutationAOTOutput(mutated_input=PlainAOTInput(idx=4)) getitem_4, # InputMutationAOTOutput(mutated_input=PlainAOTInput(idx=5)) add, # InputMutationAOTOutput(mutated_input=PlainAOTInput(idx=6)) sum_1, # PlainAOTOutput(idx=0) detach, # PlainAOTOutput(idx=1) ) """, # noqa: B950 ) # Some important characteristics of the exported graph below: # 8 arguments: 2 params from conv, 2 params from batchnorm, 2 buffers from 1 batchnorm, 1 user input # 9 outputs: 2 mutated buffers (from batchnorm), 2 user outputs and 4 gradients (since there were 4 parameters) def test_aot_export_simplified_basic(self): def f(x, y): return x * y, y * y.detach() x = torch.randn(2, requires_grad=True) y = torch.randn(2, requires_grad=True) f_graph_fw = aot_export_joint_simple(f, [x, y], trace_joint=False) out_ref = f(x, y) # No calling convention changes necessary to invoke the traced graph out_test = f_graph_fw(x, y) self.assertEqual(out_ref, out_test) # Now test the backward x = torch.randn(2, requires_grad=True) y = torch.randn(2, requires_grad=True) x2 = x.detach().clone().requires_grad_(True) y2 = y.detach().clone().requires_grad_(True) x3 = x.detach().clone().requires_grad_(True) y3 = y.detach().clone().requires_grad_(True) f_graph_joint = aot_export_joint_simple(f, [x, y], trace_joint=True) num_fw_outputs = 2 fw_g, bw_g = default_partition( f_graph_joint, [x, y], num_fwd_outputs=num_fw_outputs ) out_ref2 = f(x2, y2) fw_outs = fw_g(x3, y3) out_test2, activations = fw_outs[:num_fw_outputs], fw_outs[num_fw_outputs:] self.assertEqual(out_ref2, out_test2) # Test running the traced backward graph with a mocked-up grad_output grad_outs = [torch.ones_like(x) for x in out_ref2] grads_ref = torch.autograd.grad(out_ref2, [x2, y2], grad_outputs=grad_outs) grads_test = bw_g(*activations, *grad_outs) for g_ref, g_test in zip(grads_ref, grads_test): self.assertEqual(g_ref, g_test) def test_aot_export_metadata_mutation_banned(self): def fn(p, x): x.t_() return (x * 2,) mod = TestMod(fn) inp = torch.randn(2, 4) with self.assertRaisesRegex( RuntimeError, "Found an input that received a metadata mutation" ): aot_export_joint_simple(fn, [mod.p, inp], trace_joint=False) aot_export_joint_simple(fn, [mod.p, inp], trace_joint=True) aot_export_module(mod, [inp], trace_joint=False) def test_aot_export_forward_mutation_no_buffer_mut(self): class M(torch.nn.Module): def __init__(self) -> None: super().__init__() self.buffer1 = torch.nn.Buffer(torch.ones(6, 4)) def forward(self, x): x.add_(4) return (x.cos().sum() + self.buffer1.sum(),) mod = M() inp = torch.ones(6, 4) gm, sig = aot_export_module(mod, [inp], trace_joint=False) self.assertExpectedInline( str(gm.code).strip(), """\ def forward(self, arg0_1, arg1_1): add = torch.ops.aten.add.Tensor(arg1_1, 4); arg1_1 = None cos = torch.ops.aten.cos.default(add) sum_1 = torch.ops.aten.sum.default(cos); cos = None sum_2 = torch.ops.aten.sum.default(arg0_1); arg0_1 = None add_1 = torch.ops.aten.add.Tensor(sum_1, sum_2); sum_1 = sum_2 = None return (add, add_1)""", ) # noqa: B950 self.assertEqual(sig.user_inputs_to_mutate, {"add": "arg1_1"}) def test_aot_export_forward_mutation_multiple_mut(self): class M(torch.nn.Module): def __init__(self) -> None: super().__init__() self.buffer1 = torch.nn.Buffer(torch.ones(6, 4)) def forward(self, x, y): y.add_(4) self.buffer1.add_(5) return ( x.cos().sum() + y.sin().sum(), self.buffer1.sum(), ) mod = M() inp = [torch.ones(6, 4), torch.zeros(6, 4)] gm, sig = aot_export_module(mod, inp, trace_joint=False) self.assertExpectedInline( str(gm.code).strip(), """\ def forward(self, arg0_1, arg1_1, arg2_1): add = torch.ops.aten.add.Tensor(arg2_1, 4); arg2_1 = None add_1 = torch.ops.aten.add.Tensor(arg0_1, 5); arg0_1 = None cos = torch.ops.aten.cos.default(arg1_1); arg1_1 = None sum_1 = torch.ops.aten.sum.default(cos); cos = None sin = torch.ops.aten.sin.default(add) sum_2 = torch.ops.aten.sum.default(sin); sin = None add_2 = torch.ops.aten.add.Tensor(sum_1, sum_2); sum_1 = sum_2 = None sum_3 = torch.ops.aten.sum.default(add_1) return (add_1, add, add_2, sum_3)""", ) # noqa: B950 self.assertEqual(sig.user_inputs_to_mutate, {"add": "arg2_1"}) self.assertEqual(sig.buffers_to_mutate, {"add_1": "buffer1"}) def test_aot_export_input_mutation_on_input_requiring_grad_banned(self): class M(torch.nn.Module): def forward(self, x): x.add_(4) return (x,) mod = M() inp = torch.randn(2, requires_grad=True) gm, _ = aot_export_module(mod, [inp], trace_joint=False) self.assertExpectedInline( str(gm.graph).strip(), """\ graph(): %arg0_1 : [num_users=1] = placeholder[target=arg0_1] %add : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%arg0_1, 4), kwargs = {}) return (add, add)""", ) def test_aot_export_input_mutation_on_parameter_banned(self): def fn(p, x): p.mul_(2) return (p + x,) mod = TestMod(fn) inp = torch.randn(2) with self.assertRaisesRegex( RuntimeError, "aot_export_joint_simple does not support input mutations. ViewAndMutationMeta", ): aot_export_joint_simple(fn, [mod.p, inp], trace_joint=False) with self.assertRaisesRegex( RuntimeError, "Found a graph input that requires gradients, and received a mutation", ): aot_export_joint_simple(fn, [mod.p, inp], trace_joint=True) gm, _ = aot_export_module(mod, [inp], trace_joint=False) self.assertExpectedInline( str(gm.graph).strip(), """\ graph(): %arg0_1 : [num_users=1] = placeholder[target=arg0_1] %arg1_1 : [num_users=1] = placeholder[target=arg1_1] %mul : [num_users=2] = call_function[target=torch.ops.aten.mul.Tensor](args = (%arg0_1, 2), kwargs = {}) %add : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%mul, %arg1_1), kwargs = {}) return (mul, add)""", ) def test_aot_export_synthetic_bases_banned(self): def fn(p, x, y): x.mul_(2) return (x + y,) mod = TestMod(fn) inp = torch.randn(2) inp2 = inp.view(-1) with self.assertRaisesRegex( RuntimeError, "Encountered aliased inputs that are mutated" ): aot_export_joint_simple(fn, [mod.p, inp, inp2], trace_joint=False) aot_export_joint_simple(fn, [mod.p, inp, inp2], trace_joint=True) aot_export_module(mod, [inp, inp2], trace_joint=False) def test_aot_export_input_dupes_banned(self): def fn(p, x, y): x.mul_(2) return (x + y,) mod = TestMod(fn) inp = torch.randn(2) with self.assertRaisesRegex( RuntimeError, "Encountered duplicated inputs that are mutated in the graph" ): aot_export_joint_simple(fn, [mod.p, inp, inp], trace_joint=False) aot_export_joint_simple(fn, [mod.p, inp, inp], trace_joint=True) aot_export_module(mod, [inp, inp], trace_joint=False) def test_aot_export_multiple_outputs_require_grad_banned(self): def fn(p, x): out = p * x return out, out.sum() mod = TestMod(fn) inp = torch.randn(2) with self.assertRaisesRegex( RuntimeError, "Found an output of the forward that requires gradients, that was not", ): aot_export_module(mod, [inp], trace_joint=True, output_loss_index=1) @unittest.skipIf(IS_WINDOWS, "Windows isn't supported for this case") @unittest.skipIf( not torch._dynamo.is_dynamo_supported(), "Cond needs dynamo to run" ) def test_aot_export_with_torch_cond(self): class M(torch.nn.Module): def __init__(self) -> None: super().__init__() def forward(self, x): def true_fn(x): y = x + 4 y.add_(5) return x.cos() def false_fn(x): y = x + 5 y.add_(6) return x.sin() a = torch.cond(x.sum() > 4, true_fn, false_fn, [x]) return (a + 3, a + 4) inp = torch.randn(3, 4) gm, _ = aot_export_module(M(), (inp,), trace_joint=False) self.assertExpectedInline( gm.code.strip(), """\ def forward(self, arg0_1): sum_1 = torch.ops.aten.sum.default(arg0_1) gt = torch.ops.aten.gt.Scalar(sum_1, 4); sum_1 = None true_graph_0 = self.true_graph_0 false_graph_0 = self.false_graph_0 cond = torch.ops.higher_order.cond(gt, true_graph_0, false_graph_0, (arg0_1,)); gt = true_graph_0 = false_graph_0 = arg0_1 = None getitem = cond[0]; cond = None add = torch.ops.aten.add.Tensor(getitem, 3) add_1 = torch.ops.aten.add.Tensor(getitem, 4); getitem = None return (add, add_1)""", # noqa: B950 ) self.assertExpectedInline( gm.true_graph_0.code.strip(), """\ def forward(self, arg0_1): cos = torch.ops.aten.cos.default(arg0_1); arg0_1 = None return (cos,)""", ) self.assertExpectedInline( gm.false_graph_0.code.strip(), """\ def forward(self, arg0_1): sin = torch.ops.aten.sin.default(arg0_1); arg0_1 = None return (sin,)""", ) def test_aot_export_simplified_pytrees_banned(self): def fn(inps): return (inps[0] + inps[1],) inp1 = torch.randn(2) inp2 = torch.randn(2) inps = [inp1, inp2] with self.assertRaisesRegex( RuntimeError, "aot_export_joint_simple requires individual inputs not to be pytrees", ): aot_export_joint_simple(fn, [inps], trace_joint=False) aot_export_joint_simple(fn, [inps], trace_joint=True) def test_aot_export_functionalized_rng_banned(self): def fn(p, x): return (p + x,) mod = TestMod(fn) inp = torch.randn(2) with ( patch("functorch.compile.config.functionalize_rng_ops", True), self.assertRaisesRegex( RuntimeError, "Functionalized RNG is not currently supported in the aot_export", ), ): aot_export_joint_simple(fn, [mod.p, inp], trace_joint=False) aot_export_joint_simple(fn, [mod.p, inp], trace_joint=True) aot_export_module(mod, [inp], trace_joint=False) def test_aot_export_unbacked_arg(self): class M(torch.nn.Module): def forward(self): full = torch.full((), 11) i0 = full.item() return (torch.full((i0,), 0),) gm, _ = aot_export_module( mod=M(), args=(), trace_joint=False, dynamic_shapes=True ) self.assertExpectedInline( gm.code.strip(), """\ def forward(self): full = torch.ops.aten.full.default([], 11, device = device(type='cpu'), pin_memory = False) _local_scalar_dense = torch.ops.aten._local_scalar_dense.default(full); full = None full_1 = torch.ops.aten.full.default([_local_scalar_dense], 0, device = device(type='cpu'), pin_memory = False); _local_scalar_dense = None return (full_1,)""", # noqa: B950 ) def test_aot_export_input_mutation(self): def f(x, buf): buf.add_(1) return buf * x x = torch.randn(2, requires_grad=True) buf = torch.zeros(2, requires_grad=False) gm, _, _, _ = _aot_export_function( f, (x, buf), decompositions={}, num_params_buffers=1, no_tangents=False, pre_dispatch=False, dynamic_shapes=False, keep_input_mutations=True, kwargs={}, ) self.assertExpectedInline( gm.code.strip(), """\ def forward(self, primals, tangents): primals_1, primals_2, tangents_1, = fx_pytree.tree_flatten_spec([primals, tangents], self._in_spec) add = torch.ops.aten.add.Tensor(primals_2, 1) mul = torch.ops.aten.mul.Tensor(add, primals_1); primals_1 = None mul_1 = torch.ops.aten.mul.Tensor(tangents_1, add); tangents_1 = None copy_ = torch.ops.aten.copy_.default(primals_2, add); primals_2 = add = copy_ = None return pytree.tree_unflatten([mul, mul_1, None], self._out_spec)""", )
TestAOTExport
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/partitions/utils/time_window.py
{ "start": 1131, "end": 1455 }
class ____(NamedTuple): """An interval that is closed at the start and open at the end. Args: start (datetime): A datetime that marks the start of the window. end (datetime): A datetime that marks the end of the window. """ start: PublicAttr[datetime] end: PublicAttr[datetime]
TimeWindow
python
huggingface__transformers
src/transformers/models/cpmant/modeling_cpmant.py
{ "start": 9735, "end": 10516 }
class ____(nn.Module): def __init__(self, config: CpmAntConfig): super().__init__() self.w_in = CpmAntDenseGatedACT(config) if config.dropout_p is not None: self.dropout = torch.nn.Dropout(config.dropout_p) else: self.dropout = None self.w_out = nn.Linear(config.dim_ff, config.hidden_size, bias=False) def forward(self, hidden_states: torch.Tensor): """ Args: hidden_states (`torch.Tensor` of shape `(batch, seq_len, dim_in)`) """ hidden_states = self.w_in(hidden_states) if self.dropout is not None: hidden_states = self.dropout(hidden_states) hidden_states = self.w_out(hidden_states) return hidden_states
CpmAntFeedForward
python
huggingface__transformers
src/transformers/models/herbert/tokenization_herbert.py
{ "start": 1034, "end": 4420 }
class ____(TokenizersBackend): """ Construct a BPE tokenizer for HerBERT (backed by HuggingFace's tokenizers library). Peculiarities: - uses BERT's pre-tokenizer: BertPreTokenizer splits tokens on spaces, and also on punctuation. Each occurrence of a punctuation character will be treated separately. This tokenizer inherits from [`TokenizersBackend`] which contains most of the methods. Users should refer to the superclass for more information regarding methods. Args: vocab_file (`str`): Path to the vocabulary file. merges_file (`str`): Path to the merges file. cls_token (`str`, *optional*, defaults to `"<s>"`): The classifier token. unk_token (`str`, *optional*, defaults to `"<unk>"`): The unknown token. pad_token (`str`, *optional*, defaults to `"<pad>"`): The padding token. mask_token (`str`, *optional*, defaults to `"<mask>"`): The mask token. sep_token (`str`, *optional*, defaults to `"</s>"`): The separator token. vocab (`dict`, *optional*): Custom vocabulary dictionary. merges (`list`, *optional*): Custom merges list. """ vocab_files_names = VOCAB_FILES_NAMES slow_tokenizer_class = None def __init__( self, vocab: Optional[dict] = None, merges: Optional[list] = None, cls_token: str = "<s>", unk_token: str = "<unk>", pad_token: str = "<pad>", mask_token: str = "<mask>", sep_token: str = "</s>", vocab_file: Optional[str] = None, merges_file: Optional[str] = None, **kwargs, ): if vocab is not None: self._vocab = ( {token: idx for idx, (token, _score) in enumerate(vocab)} if isinstance(vocab, list) else vocab ) else: self._vocab = {} if merges is not None: # Convert lists to tuples if necessary (happens when loading from JSON) self._merges = [tuple(merge) if isinstance(merge, list) else merge for merge in merges] else: self._merges = [] self._tokenizer = Tokenizer( BPE( vocab=self._vocab, merges=self._merges, dropout=None, unk_token=str(unk_token), end_of_word_suffix="</w>", ) ) self._tokenizer.normalizer = normalizers.BertNormalizer( lowercase=False, strip_accents=False, clean_text=True, handle_chinese_chars=True ) self._tokenizer.pre_tokenizer = pre_tokenizers.BertPreTokenizer() self._tokenizer.decoder = decoders.BPEDecoder(suffix="</w>") tokenizer_object = self._tokenizer self.vocab_file = vocab_file self.merges_file = merges_file super().__init__( tokenizer_object=tokenizer_object, cls_token=cls_token, unk_token=unk_token, pad_token=pad_token, mask_token=mask_token, sep_token=sep_token, **kwargs, ) self._tokenizer.post_processor = processors.BertProcessing( sep=(self.sep_token, 2), cls=(self.cls_token, 0), ) __all__ = ["HerbertTokenizer"]
HerbertTokenizer
python
numba__numba
numba/np/linalg.py
{ "start": 3521, "end": 92462 }
class ____: """ Functions to return type signatures for wrapped LAPACK functions. """ def __init__(self): ensure_lapack() @classmethod def numba_xxgetrf(cls, dtype): sig = types.intc(types.char, # kind types.intp, # m types.intp, # n types.CPointer(dtype), # a types.intp, # lda types.CPointer(F_INT_nbtype) # ipiv ) return types.ExternalFunction("numba_xxgetrf", sig) @classmethod def numba_ez_xxgetri(cls, dtype): sig = types.intc(types.char, # kind types.intp, # n types.CPointer(dtype), # a types.intp, # lda types.CPointer(F_INT_nbtype) # ipiv ) return types.ExternalFunction("numba_ez_xxgetri", sig) @classmethod def numba_ez_rgeev(cls, dtype): sig = types.intc(types.char, # kind types.char, # jobvl types.char, # jobvr types.intp, # n types.CPointer(dtype), # a types.intp, # lda types.CPointer(dtype), # wr types.CPointer(dtype), # wi types.CPointer(dtype), # vl types.intp, # ldvl types.CPointer(dtype), # vr types.intp # ldvr ) return types.ExternalFunction("numba_ez_rgeev", sig) @classmethod def numba_ez_cgeev(cls, dtype): sig = types.intc(types.char, # kind types.char, # jobvl types.char, # jobvr types.intp, # n types.CPointer(dtype), # a types.intp, # lda types.CPointer(dtype), # w types.CPointer(dtype), # vl types.intp, # ldvl types.CPointer(dtype), # vr types.intp # ldvr ) return types.ExternalFunction("numba_ez_cgeev", sig) @classmethod def numba_ez_xxxevd(cls, dtype): wtype = getattr(dtype, "underlying_float", dtype) sig = types.intc(types.char, # kind types.char, # jobz types.char, # uplo types.intp, # n types.CPointer(dtype), # a types.intp, # lda types.CPointer(wtype), # w ) return types.ExternalFunction("numba_ez_xxxevd", sig) @classmethod def numba_xxpotrf(cls, dtype): sig = types.intc(types.char, # kind types.char, # uplo types.intp, # n types.CPointer(dtype), # a types.intp # lda ) return types.ExternalFunction("numba_xxpotrf", sig) @classmethod def numba_ez_gesdd(cls, dtype): stype = getattr(dtype, "underlying_float", dtype) sig = types.intc( types.char, # kind types.char, # jobz types.intp, # m types.intp, # n types.CPointer(dtype), # a types.intp, # lda types.CPointer(stype), # s types.CPointer(dtype), # u types.intp, # ldu types.CPointer(dtype), # vt types.intp # ldvt ) return types.ExternalFunction("numba_ez_gesdd", sig) @classmethod def numba_ez_geqrf(cls, dtype): sig = types.intc( types.char, # kind types.intp, # m types.intp, # n types.CPointer(dtype), # a types.intp, # lda types.CPointer(dtype), # tau ) return types.ExternalFunction("numba_ez_geqrf", sig) @classmethod def numba_ez_xxgqr(cls, dtype): sig = types.intc( types.char, # kind types.intp, # m types.intp, # n types.intp, # k types.CPointer(dtype), # a types.intp, # lda types.CPointer(dtype), # tau ) return types.ExternalFunction("numba_ez_xxgqr", sig) @classmethod def numba_ez_gelsd(cls, dtype): rtype = getattr(dtype, "underlying_float", dtype) sig = types.intc( types.char, # kind types.intp, # m types.intp, # n types.intp, # nrhs types.CPointer(dtype), # a types.intp, # lda types.CPointer(dtype), # b types.intp, # ldb types.CPointer(rtype), # S types.float64, # rcond types.CPointer(types.intc) # rank ) return types.ExternalFunction("numba_ez_gelsd", sig) @classmethod def numba_xgesv(cls, dtype): sig = types.intc( types.char, # kind types.intp, # n types.intp, # nhrs types.CPointer(dtype), # a types.intp, # lda types.CPointer(F_INT_nbtype), # ipiv types.CPointer(dtype), # b types.intp # ldb ) return types.ExternalFunction("numba_xgesv", sig) @contextlib.contextmanager def make_contiguous(context, builder, sig, args): """ Ensure that all array arguments are contiguous, if necessary by copying them. A new (sig, args) tuple is yielded. """ newtys = [] newargs = [] copies = [] for ty, val in zip(sig.args, args): if not isinstance(ty, types.Array) or ty.layout in 'CF': newty, newval = ty, val else: newty = ty.copy(layout='C') copysig = signature(newty, ty) newval = array_copy(context, builder, copysig, (val,)) copies.append((newty, newval)) newtys.append(newty) newargs.append(newval) yield signature(sig.return_type, *newtys), tuple(newargs) for ty, val in copies: context.nrt.decref(builder, ty, val) def check_c_int(context, builder, n): """ Check whether *n* fits in a C `int`. """ _maxint = 2**31 - 1 def impl(n): if n > _maxint: raise OverflowError("array size too large to fit in C int") context.compile_internal(builder, impl, signature(types.none, types.intp), (n,)) def check_blas_return(context, builder, res): """ Check the integer error return from one of the BLAS wrappers in _helperlib.c. """ with builder.if_then(cgutils.is_not_null(builder, res), likely=False): # Those errors shouldn't happen, it's easier to just abort the process pyapi = context.get_python_api(builder) pyapi.gil_ensure() pyapi.fatal_error("BLAS wrapper returned with an error") def check_lapack_return(context, builder, res): """ Check the integer error return from one of the LAPACK wrappers in _helperlib.c. """ with builder.if_then(cgutils.is_not_null(builder, res), likely=False): # Those errors shouldn't happen, it's easier to just abort the process pyapi = context.get_python_api(builder) pyapi.gil_ensure() pyapi.fatal_error("LAPACK wrapper returned with an error") def call_xxdot(context, builder, conjugate, dtype, n, a_data, b_data, out_data): """ Call the BLAS vector * vector product function for the given arguments. """ fnty = ir.FunctionType(ir.IntType(32), [ll_char, ll_char, intp_t, # kind, conjugate, n ll_void_p, ll_void_p, ll_void_p, # a, b, out ]) fn = cgutils.get_or_insert_function(builder.module, fnty, "numba_xxdot") kind = get_blas_kind(dtype) kind_val = ir.Constant(ll_char, ord(kind)) conjugate = ir.Constant(ll_char, int(conjugate)) res = builder.call(fn, (kind_val, conjugate, n, builder.bitcast(a_data, ll_void_p), builder.bitcast(b_data, ll_void_p), builder.bitcast(out_data, ll_void_p))) check_blas_return(context, builder, res) def call_xxgemv(context, builder, do_trans, m_type, m_shapes, m_data, v_data, out_data): """ Call the BLAS matrix * vector product function for the given arguments. """ fnty = ir.FunctionType(ir.IntType(32), [ll_char, ll_char, # kind, trans intp_t, intp_t, # m, n ll_void_p, ll_void_p, intp_t, # alpha, a, lda ll_void_p, ll_void_p, ll_void_p, # x, beta, y ]) fn = cgutils.get_or_insert_function(builder.module, fnty, "numba_xxgemv") dtype = m_type.dtype alpha = make_constant_slot(context, builder, dtype, 1.0) beta = make_constant_slot(context, builder, dtype, 0.0) if m_type.layout == 'F': m, n = m_shapes lda = m_shapes[0] else: n, m = m_shapes lda = m_shapes[1] kind = get_blas_kind(dtype) kind_val = ir.Constant(ll_char, ord(kind)) trans = ir.Constant(ll_char, ord('t') if do_trans else ord('n')) res = builder.call(fn, (kind_val, trans, m, n, builder.bitcast(alpha, ll_void_p), builder.bitcast(m_data, ll_void_p), lda, builder.bitcast(v_data, ll_void_p), builder.bitcast(beta, ll_void_p), builder.bitcast(out_data, ll_void_p))) check_blas_return(context, builder, res) def call_xxgemm(context, builder, x_type, x_shapes, x_data, y_type, y_shapes, y_data, out_type, out_shapes, out_data): """ Call the BLAS matrix * matrix product function for the given arguments. """ fnty = ir.FunctionType(ir.IntType(32), [ll_char, # kind ll_char, ll_char, # transa, transb intp_t, intp_t, intp_t, # m, n, k ll_void_p, ll_void_p, intp_t, # alpha, a, lda ll_void_p, intp_t, ll_void_p, # b, ldb, beta ll_void_p, intp_t, # c, ldc ]) fn = cgutils.get_or_insert_function(builder.module, fnty, "numba_xxgemm") m, k = x_shapes _k, n = y_shapes dtype = x_type.dtype alpha = make_constant_slot(context, builder, dtype, 1.0) beta = make_constant_slot(context, builder, dtype, 0.0) trans = ir.Constant(ll_char, ord('t')) notrans = ir.Constant(ll_char, ord('n')) def get_array_param(ty, shapes, data): return ( # Transpose if layout different from result's notrans if ty.layout == out_type.layout else trans, # Size of the inner dimension in physical array order shapes[1] if ty.layout == 'C' else shapes[0], # The data pointer, unit-less builder.bitcast(data, ll_void_p), ) transa, lda, data_a = get_array_param(y_type, y_shapes, y_data) transb, ldb, data_b = get_array_param(x_type, x_shapes, x_data) _, ldc, data_c = get_array_param(out_type, out_shapes, out_data) kind = get_blas_kind(dtype) kind_val = ir.Constant(ll_char, ord(kind)) res = builder.call(fn, (kind_val, transa, transb, n, m, k, builder.bitcast(alpha, ll_void_p), data_a, lda, data_b, ldb, builder.bitcast(beta, ll_void_p), data_c, ldc)) check_blas_return(context, builder, res) def dot_2_mm(context, builder, sig, args): """ np.dot(matrix, matrix) """ def dot_impl(a, b): m, k = a.shape _k, n = b.shape if k == 0: return np.zeros((m, n), a.dtype) out = np.empty((m, n), a.dtype) return np.dot(a, b, out) res = context.compile_internal(builder, dot_impl, sig, args) return impl_ret_new_ref(context, builder, sig.return_type, res) def dot_2_vm(context, builder, sig, args): """ np.dot(vector, matrix) """ def dot_impl(a, b): m, = a.shape _m, n = b.shape if m == 0: return np.zeros((n, ), a.dtype) out = np.empty((n, ), a.dtype) return np.dot(a, b, out) res = context.compile_internal(builder, dot_impl, sig, args) return impl_ret_new_ref(context, builder, sig.return_type, res) def dot_2_mv(context, builder, sig, args): """ np.dot(matrix, vector) """ def dot_impl(a, b): m, n = a.shape _n, = b.shape if n == 0: return np.zeros((m, ), a.dtype) out = np.empty((m, ), a.dtype) return np.dot(a, b, out) res = context.compile_internal(builder, dot_impl, sig, args) return impl_ret_new_ref(context, builder, sig.return_type, res) def dot_2_vv(context, builder, sig, args, conjugate=False): """ np.dot(vector, vector) np.vdot(vector, vector) """ aty, bty = sig.args dtype = sig.return_type a = make_array(aty)(context, builder, args[0]) b = make_array(bty)(context, builder, args[1]) n, = cgutils.unpack_tuple(builder, a.shape) def check_args(a, b): m, = a.shape n, = b.shape if m != n: raise ValueError("incompatible array sizes for np.dot(a, b) " "(vector * vector)") context.compile_internal(builder, check_args, signature(types.none, *sig.args), args) check_c_int(context, builder, n) out = cgutils.alloca_once(builder, context.get_value_type(dtype)) call_xxdot(context, builder, conjugate, dtype, n, a.data, b.data, out) return builder.load(out) @overload(np.dot) def dot_2(left, right): """ np.dot(a, b) """ return dot_2_impl('np.dot()', left, right) @overload(operator.matmul) def matmul_2(left, right): """ a @ b """ return dot_2_impl("'@'", left, right) def dot_2_impl(name, left, right): if isinstance(left, types.Array) and isinstance(right, types.Array): @intrinsic def _impl(typingcontext, left, right): ndims = (left.ndim, right.ndim) def _dot2_codegen(context, builder, sig, args): ensure_blas() with make_contiguous(context, builder, sig, args) as (sig, args): if ndims == (2, 2): return dot_2_mm(context, builder, sig, args) elif ndims == (2, 1): return dot_2_mv(context, builder, sig, args) elif ndims == (1, 2): return dot_2_vm(context, builder, sig, args) elif ndims == (1, 1): return dot_2_vv(context, builder, sig, args) else: raise AssertionError('unreachable') if left.dtype != right.dtype: raise TypingError( "%s arguments must all have the same dtype" % name) if ndims == (2, 2): return_type = types.Array(left.dtype, 2, 'C') elif ndims == (2, 1) or ndims == (1, 2): return_type = types.Array(left.dtype, 1, 'C') elif ndims == (1, 1): return_type = left.dtype else: raise TypingError(("%s: inputs must have compatible " "dimensions") % name) return signature(return_type, left, right), _dot2_codegen if left.layout not in 'CF' or right.layout not in 'CF': warnings.warn( "%s is faster on contiguous arrays, called on %s" % ( name, (left, right),), NumbaPerformanceWarning) return lambda left, right: _impl(left, right) @overload(np.vdot) def vdot(left, right): """ np.vdot(a, b) """ if isinstance(left, types.Array) and isinstance(right, types.Array): @intrinsic def _impl(typingcontext, left, right): def codegen(context, builder, sig, args): ensure_blas() with make_contiguous(context, builder, sig, args) as\ (sig, args): return dot_2_vv(context, builder, sig, args, conjugate=True) if left.ndim != 1 or right.ndim != 1: raise TypingError("np.vdot() only supported on 1-D arrays") if left.dtype != right.dtype: raise TypingError( "np.vdot() arguments must all have the same dtype") return signature(left.dtype, left, right), codegen if left.layout not in 'CF' or right.layout not in 'CF': warnings.warn( "np.vdot() is faster on contiguous arrays, called on %s" % ((left, right),), NumbaPerformanceWarning) return lambda left, right: _impl(left, right) def dot_3_vm_check_args(a, b, out): m, = a.shape _m, n = b.shape if m != _m: raise ValueError("incompatible array sizes for " "np.dot(a, b) (vector * matrix)") if out.shape != (n,): raise ValueError("incompatible output array size for " "np.dot(a, b, out) (vector * matrix)") def dot_3_mv_check_args(a, b, out): m, _n = a.shape n, = b.shape if n != _n: raise ValueError("incompatible array sizes for np.dot(a, b) " "(matrix * vector)") if out.shape != (m,): raise ValueError("incompatible output array size for " "np.dot(a, b, out) (matrix * vector)") def dot_3_vm(context, builder, sig, args): """ np.dot(vector, matrix, out) np.dot(matrix, vector, out) """ xty, yty, outty = sig.args assert outty == sig.return_type dtype = xty.dtype x = make_array(xty)(context, builder, args[0]) y = make_array(yty)(context, builder, args[1]) out = make_array(outty)(context, builder, args[2]) x_shapes = cgutils.unpack_tuple(builder, x.shape) y_shapes = cgutils.unpack_tuple(builder, y.shape) out_shapes = cgutils.unpack_tuple(builder, out.shape) if xty.ndim < yty.ndim: # Vector * matrix # Asked for x * y, we will compute y.T * x mty = yty m_shapes = y_shapes v_shape = x_shapes[0] lda = m_shapes[1] do_trans = yty.layout == 'F' m_data, v_data = y.data, x.data check_args = dot_3_vm_check_args else: # Matrix * vector # We will compute x * y mty = xty m_shapes = x_shapes v_shape = y_shapes[0] lda = m_shapes[0] do_trans = xty.layout == 'C' m_data, v_data = x.data, y.data check_args = dot_3_mv_check_args context.compile_internal(builder, check_args, signature(types.none, *sig.args), args) for val in m_shapes: check_c_int(context, builder, val) zero = context.get_constant(types.intp, 0) both_empty = builder.icmp_signed('==', v_shape, zero) matrix_empty = builder.icmp_signed('==', lda, zero) is_empty = builder.or_(both_empty, matrix_empty) with builder.if_else(is_empty, likely=False) as (empty, nonempty): with empty: cgutils.memset(builder, out.data, builder.mul(out.itemsize, out.nitems), 0) with nonempty: call_xxgemv(context, builder, do_trans, mty, m_shapes, m_data, v_data, out.data) return impl_ret_borrowed(context, builder, sig.return_type, out._getvalue()) def dot_3_mm(context, builder, sig, args): """ np.dot(matrix, matrix, out) """ xty, yty, outty = sig.args assert outty == sig.return_type dtype = xty.dtype x = make_array(xty)(context, builder, args[0]) y = make_array(yty)(context, builder, args[1]) out = make_array(outty)(context, builder, args[2]) x_shapes = cgutils.unpack_tuple(builder, x.shape) y_shapes = cgutils.unpack_tuple(builder, y.shape) out_shapes = cgutils.unpack_tuple(builder, out.shape) m, k = x_shapes _k, n = y_shapes # The only case Numpy supports assert outty.layout == 'C' def check_args(a, b, out): m, k = a.shape _k, n = b.shape if k != _k: raise ValueError("incompatible array sizes for np.dot(a, b) " "(matrix * matrix)") if out.shape != (m, n): raise ValueError("incompatible output array size for " "np.dot(a, b, out) (matrix * matrix)") context.compile_internal(builder, check_args, signature(types.none, *sig.args), args) check_c_int(context, builder, m) check_c_int(context, builder, k) check_c_int(context, builder, n) x_data = x.data y_data = y.data out_data = out.data # If eliminated dimension is zero, set all entries to zero and return zero = context.get_constant(types.intp, 0) both_empty = builder.icmp_signed('==', k, zero) x_empty = builder.icmp_signed('==', m, zero) y_empty = builder.icmp_signed('==', n, zero) is_empty = builder.or_(both_empty, builder.or_(x_empty, y_empty)) with builder.if_else(is_empty, likely=False) as (empty, nonempty): with empty: cgutils.memset(builder, out.data, builder.mul(out.itemsize, out.nitems), 0) with nonempty: # Check if any of the operands is really a 1-d vector represented # as a (1, k) or (k, 1) 2-d array. In those cases, it is pessimal # to call the generic matrix * matrix product BLAS function. one = context.get_constant(types.intp, 1) is_left_vec = builder.icmp_signed('==', m, one) is_right_vec = builder.icmp_signed('==', n, one) with builder.if_else(is_right_vec) as (r_vec, r_mat): with r_vec: with builder.if_else(is_left_vec) as (v_v, m_v): with v_v: # V * V call_xxdot(context, builder, False, dtype, k, x_data, y_data, out_data) with m_v: # M * V do_trans = xty.layout == outty.layout call_xxgemv(context, builder, do_trans, xty, x_shapes, x_data, y_data, out_data) with r_mat: with builder.if_else(is_left_vec) as (v_m, m_m): with v_m: # V * M do_trans = yty.layout != outty.layout call_xxgemv(context, builder, do_trans, yty, y_shapes, y_data, x_data, out_data) with m_m: # M * M call_xxgemm(context, builder, xty, x_shapes, x_data, yty, y_shapes, y_data, outty, out_shapes, out_data) return impl_ret_borrowed(context, builder, sig.return_type, out._getvalue()) @overload(np.dot) def dot_3(left, right, out): """ np.dot(a, b, out) """ if (isinstance(left, types.Array) and isinstance(right, types.Array) and isinstance(out, types.Array)): @intrinsic def _impl(typingcontext, left, right, out): def codegen(context, builder, sig, args): ensure_blas() with make_contiguous(context, builder, sig, args) as (sig, args): ndims = set(x.ndim for x in sig.args[:2]) if ndims == {2}: return dot_3_mm(context, builder, sig, args) elif ndims == {1, 2}: return dot_3_vm(context, builder, sig, args) else: raise AssertionError('unreachable') if left.dtype != right.dtype or left.dtype != out.dtype: raise TypingError( "np.dot() arguments must all have the same dtype") return signature(out, left, right, out), codegen if left.layout not in 'CF' or right.layout not in 'CF' or out.layout\ not in 'CF': warnings.warn( "np.vdot() is faster on contiguous arrays, called on %s" % ((left, right),), NumbaPerformanceWarning) return lambda left, right, out: _impl(left, right, out) if config.USE_LEGACY_TYPE_SYSTEM: fatal_error_func = types.ExternalFunction("numba_fatal_error", types.intc()) else: fatal_error_func = types.ExternalFunction("numba_fatal_error", types.c_intp()) @register_jitable def _check_finite_matrix(a): for v in np.nditer(a): if not np.isfinite(v.item()): raise np.linalg.LinAlgError( "Array must not contain infs or NaNs.") def _check_linalg_matrix(a, func_name, la_prefix=True): # la_prefix is present as some functions, e.g. np.trace() # are documented under "linear algebra" but aren't in the # module prefix = "np.linalg" if la_prefix else "np" interp = (prefix, func_name) # Unpack optional type if isinstance(a, types.Optional): a = a.type if not isinstance(a, types.Array): msg = "%s.%s() only supported for array types" % interp raise TypingError(msg, highlighting=False) if not a.ndim == 2: msg = "%s.%s() only supported on 2-D arrays." % interp raise TypingError(msg, highlighting=False) if not isinstance(a.dtype, (types.Float, types.Complex)): msg = "%s.%s() only supported on "\ "float and complex arrays." % interp raise TypingError(msg, highlighting=False) def _check_homogeneous_types(func_name, *types): t0 = types[0].dtype for t in types[1:]: if t.dtype != t0: msg = "np.linalg.%s() only supports inputs that have homogeneous dtypes." % func_name raise TypingError(msg, highlighting=False) def _copy_to_fortran_order(): pass @overload(_copy_to_fortran_order) def ol_copy_to_fortran_order(a): # This function copies the array 'a' into a new array with fortran order. # This exists because the copy routines don't take order flags yet. F_layout = a.layout == 'F' A_layout = a.layout == 'A' def impl(a): if F_layout: # it's F ordered at compile time, just copy acpy = np.copy(a) elif A_layout: # decide based on runtime value flag_f = a.flags.f_contiguous if flag_f: # it's already F ordered, so copy but in a round about way to # ensure that the copy is also F ordered acpy = np.copy(a.T).T else: # it's something else ordered, so let asfortranarray deal with # copying and making it fortran ordered acpy = np.asfortranarray(a) else: # it's C ordered at compile time, asfortranarray it. acpy = np.asfortranarray(a) return acpy return impl @register_jitable def _inv_err_handler(r): if r != 0: if r < 0: fatal_error_func() assert 0 # unreachable if r > 0: raise np.linalg.LinAlgError( "Matrix is singular to machine precision.") @register_jitable def _dummy_liveness_func(a): """pass a list of variables to be preserved through dead code elimination""" return a[0] @overload(np.linalg.inv) def inv_impl(a): ensure_lapack() _check_linalg_matrix(a, "inv") numba_xxgetrf = _LAPACK().numba_xxgetrf(a.dtype) numba_xxgetri = _LAPACK().numba_ez_xxgetri(a.dtype) kind = ord(get_blas_kind(a.dtype, "inv")) def inv_impl(a): n = a.shape[-1] if a.shape[-2] != n: msg = "Last 2 dimensions of the array must be square." raise np.linalg.LinAlgError(msg) _check_finite_matrix(a) acpy = _copy_to_fortran_order(a) if n == 0: return acpy ipiv = np.empty(n, dtype=F_INT_nptype) r = numba_xxgetrf(kind, n, n, acpy.ctypes, n, ipiv.ctypes) _inv_err_handler(r) r = numba_xxgetri(kind, n, acpy.ctypes, n, ipiv.ctypes) _inv_err_handler(r) # help liveness analysis _dummy_liveness_func([acpy.size, ipiv.size]) return acpy return inv_impl @register_jitable def _handle_err_maybe_convergence_problem(r): if r != 0: if r < 0: fatal_error_func() assert 0 # unreachable if r > 0: raise ValueError("Internal algorithm failed to converge.") def _check_linalg_1_or_2d_matrix(a, func_name, la_prefix=True): # la_prefix is present as some functions, e.g. np.trace() # are documented under "linear algebra" but aren't in the # module prefix = "np.linalg" if la_prefix else "np" interp = (prefix, func_name) # checks that a matrix is 1 or 2D if not isinstance(a, types.Array): raise TypingError("%s.%s() only supported for array types " % interp) if not a.ndim <= 2: raise TypingError("%s.%s() only supported on 1 and 2-D arrays " % interp) if not isinstance(a.dtype, (types.Float, types.Complex)): raise TypingError("%s.%s() only supported on " "float and complex arrays." % interp) @overload(np.linalg.cholesky) def cho_impl(a): ensure_lapack() _check_linalg_matrix(a, "cholesky") numba_xxpotrf = _LAPACK().numba_xxpotrf(a.dtype) kind = ord(get_blas_kind(a.dtype, "cholesky")) UP = ord('U') LO = ord('L') def cho_impl(a): n = a.shape[-1] if a.shape[-2] != n: msg = "Last 2 dimensions of the array must be square." raise np.linalg.LinAlgError(msg) # The output is allocated in C order out = a.copy() if n == 0: return out # Pass UP since xxpotrf() operates in F order # The semantics ensure this works fine # (out is really its Hermitian in F order, but UP instructs # xxpotrf to compute the Hermitian of the upper triangle # => they cancel each other) r = numba_xxpotrf(kind, UP, n, out.ctypes, n) if r != 0: if r < 0: fatal_error_func() assert 0 # unreachable if r > 0: raise np.linalg.LinAlgError( "Matrix is not positive definite.") # Zero out upper triangle, in F order for col in range(n): out[:col, col] = 0 return out return cho_impl @overload(np.linalg.eig) def eig_impl(a): ensure_lapack() _check_linalg_matrix(a, "eig") numba_ez_rgeev = _LAPACK().numba_ez_rgeev(a.dtype) numba_ez_cgeev = _LAPACK().numba_ez_cgeev(a.dtype) kind = ord(get_blas_kind(a.dtype, "eig")) JOBVL = ord('N') JOBVR = ord('V') def real_eig_impl(a): """ eig() implementation for real arrays. """ n = a.shape[-1] if a.shape[-2] != n: msg = "Last 2 dimensions of the array must be square." raise np.linalg.LinAlgError(msg) _check_finite_matrix(a) acpy = _copy_to_fortran_order(a) ldvl = 1 ldvr = n wr = np.empty(n, dtype=a.dtype) wi = np.empty(n, dtype=a.dtype) vl = np.empty((n, ldvl), dtype=a.dtype) vr = np.empty((n, ldvr), dtype=a.dtype) if n == 0: return (wr, vr.T) r = numba_ez_rgeev(kind, JOBVL, JOBVR, n, acpy.ctypes, n, wr.ctypes, wi.ctypes, vl.ctypes, ldvl, vr.ctypes, ldvr) _handle_err_maybe_convergence_problem(r) # By design numba does not support dynamic return types, however, # Numpy does. Numpy uses this ability in the case of returning # eigenvalues/vectors of a real matrix. The return type of # np.linalg.eig(), when operating on a matrix in real space # depends on the values present in the matrix itself (recalling # that eigenvalues are the roots of the characteristic polynomial # of the system matrix, which will by construction depend on the # values present in the system matrix). As numba cannot handle # the case of a runtime decision based domain change relative to # the input type, if it is required numba raises as below. if np.any(wi): raise ValueError( "eig() argument must not cause a domain change.") # put these in to help with liveness analysis, # `.ctypes` doesn't keep the vars alive _dummy_liveness_func([acpy.size, vl.size, vr.size, wr.size, wi.size]) return (wr, vr.T) def cmplx_eig_impl(a): """ eig() implementation for complex arrays. """ n = a.shape[-1] if a.shape[-2] != n: msg = "Last 2 dimensions of the array must be square." raise np.linalg.LinAlgError(msg) _check_finite_matrix(a) acpy = _copy_to_fortran_order(a) ldvl = 1 ldvr = n w = np.empty(n, dtype=a.dtype) vl = np.empty((n, ldvl), dtype=a.dtype) vr = np.empty((n, ldvr), dtype=a.dtype) if n == 0: return (w, vr.T) r = numba_ez_cgeev(kind, JOBVL, JOBVR, n, acpy.ctypes, n, w.ctypes, vl.ctypes, ldvl, vr.ctypes, ldvr) _handle_err_maybe_convergence_problem(r) # put these in to help with liveness analysis, # `.ctypes` doesn't keep the vars alive _dummy_liveness_func([acpy.size, vl.size, vr.size, w.size]) return (w, vr.T) if isinstance(a.dtype, types.scalars.Complex): return cmplx_eig_impl else: return real_eig_impl @overload(np.linalg.eigvals) def eigvals_impl(a): ensure_lapack() _check_linalg_matrix(a, "eigvals") numba_ez_rgeev = _LAPACK().numba_ez_rgeev(a.dtype) numba_ez_cgeev = _LAPACK().numba_ez_cgeev(a.dtype) kind = ord(get_blas_kind(a.dtype, "eigvals")) JOBVL = ord('N') JOBVR = ord('N') def real_eigvals_impl(a): """ eigvals() implementation for real arrays. """ n = a.shape[-1] if a.shape[-2] != n: msg = "Last 2 dimensions of the array must be square." raise np.linalg.LinAlgError(msg) _check_finite_matrix(a) acpy = _copy_to_fortran_order(a) ldvl = 1 ldvr = 1 wr = np.empty(n, dtype=a.dtype) if n == 0: return wr wi = np.empty(n, dtype=a.dtype) # not referenced but need setting for MKL null check vl = np.empty((1), dtype=a.dtype) vr = np.empty((1), dtype=a.dtype) r = numba_ez_rgeev(kind, JOBVL, JOBVR, n, acpy.ctypes, n, wr.ctypes, wi.ctypes, vl.ctypes, ldvl, vr.ctypes, ldvr) _handle_err_maybe_convergence_problem(r) # By design numba does not support dynamic return types, however, # Numpy does. Numpy uses this ability in the case of returning # eigenvalues/vectors of a real matrix. The return type of # np.linalg.eigvals(), when operating on a matrix in real space # depends on the values present in the matrix itself (recalling # that eigenvalues are the roots of the characteristic polynomial # of the system matrix, which will by construction depend on the # values present in the system matrix). As numba cannot handle # the case of a runtime decision based domain change relative to # the input type, if it is required numba raises as below. if np.any(wi): raise ValueError( "eigvals() argument must not cause a domain change.") # put these in to help with liveness analysis, # `.ctypes` doesn't keep the vars alive _dummy_liveness_func([acpy.size, vl.size, vr.size, wr.size, wi.size]) return wr def cmplx_eigvals_impl(a): """ eigvals() implementation for complex arrays. """ n = a.shape[-1] if a.shape[-2] != n: msg = "Last 2 dimensions of the array must be square." raise np.linalg.LinAlgError(msg) _check_finite_matrix(a) acpy = _copy_to_fortran_order(a) ldvl = 1 ldvr = 1 w = np.empty(n, dtype=a.dtype) if n == 0: return w vl = np.empty((1), dtype=a.dtype) vr = np.empty((1), dtype=a.dtype) r = numba_ez_cgeev(kind, JOBVL, JOBVR, n, acpy.ctypes, n, w.ctypes, vl.ctypes, ldvl, vr.ctypes, ldvr) _handle_err_maybe_convergence_problem(r) # put these in to help with liveness analysis, # `.ctypes` doesn't keep the vars alive _dummy_liveness_func([acpy.size, vl.size, vr.size, w.size]) return w if isinstance(a.dtype, types.scalars.Complex): return cmplx_eigvals_impl else: return real_eigvals_impl @overload(np.linalg.eigh) def eigh_impl(a): ensure_lapack() _check_linalg_matrix(a, "eigh") # convert typing floats to numpy floats for use in the impl w_type = getattr(a.dtype, "underlying_float", a.dtype) w_dtype = np_support.as_dtype(w_type) numba_ez_xxxevd = _LAPACK().numba_ez_xxxevd(a.dtype) kind = ord(get_blas_kind(a.dtype, "eigh")) JOBZ = ord('V') UPLO = ord('L') def eigh_impl(a): n = a.shape[-1] if a.shape[-2] != n: msg = "Last 2 dimensions of the array must be square." raise np.linalg.LinAlgError(msg) _check_finite_matrix(a) acpy = _copy_to_fortran_order(a) w = np.empty(n, dtype=w_dtype) if n == 0: return (w, acpy) r = numba_ez_xxxevd(kind, # kind JOBZ, # jobz UPLO, # uplo n, # n acpy.ctypes, # a n, # lda w.ctypes # w ) _handle_err_maybe_convergence_problem(r) # help liveness analysis _dummy_liveness_func([acpy.size, w.size]) return (w, acpy) return eigh_impl @overload(np.linalg.eigvalsh) def eigvalsh_impl(a): ensure_lapack() _check_linalg_matrix(a, "eigvalsh") # convert typing floats to numpy floats for use in the impl w_type = getattr(a.dtype, "underlying_float", a.dtype) w_dtype = np_support.as_dtype(w_type) numba_ez_xxxevd = _LAPACK().numba_ez_xxxevd(a.dtype) kind = ord(get_blas_kind(a.dtype, "eigvalsh")) JOBZ = ord('N') UPLO = ord('L') def eigvalsh_impl(a): n = a.shape[-1] if a.shape[-2] != n: msg = "Last 2 dimensions of the array must be square." raise np.linalg.LinAlgError(msg) _check_finite_matrix(a) acpy = _copy_to_fortran_order(a) w = np.empty(n, dtype=w_dtype) if n == 0: return w r = numba_ez_xxxevd(kind, # kind JOBZ, # jobz UPLO, # uplo n, # n acpy.ctypes, # a n, # lda w.ctypes # w ) _handle_err_maybe_convergence_problem(r) # help liveness analysis _dummy_liveness_func([acpy.size, w.size]) return w return eigvalsh_impl @overload(np.linalg.svd) def svd_impl(a, full_matrices=1): ensure_lapack() _check_linalg_matrix(a, "svd") # convert typing floats to numpy floats for use in the impl s_type = getattr(a.dtype, "underlying_float", a.dtype) s_dtype = np_support.as_dtype(s_type) numba_ez_gesdd = _LAPACK().numba_ez_gesdd(a.dtype) kind = ord(get_blas_kind(a.dtype, "svd")) JOBZ_A = ord('A') JOBZ_S = ord('S') def svd_impl(a, full_matrices=1): n = a.shape[-1] m = a.shape[-2] if n == 0 or m == 0: raise np.linalg.LinAlgError("Arrays cannot be empty") _check_finite_matrix(a) acpy = _copy_to_fortran_order(a) ldu = m minmn = min(m, n) if full_matrices: JOBZ = JOBZ_A ucol = m ldvt = n else: JOBZ = JOBZ_S ucol = minmn ldvt = minmn u = np.empty((ucol, ldu), dtype=a.dtype) s = np.empty(minmn, dtype=s_dtype) vt = np.empty((n, ldvt), dtype=a.dtype) r = numba_ez_gesdd( kind, # kind JOBZ, # jobz m, # m n, # n acpy.ctypes, # a m, # lda s.ctypes, # s u.ctypes, # u ldu, # ldu vt.ctypes, # vt ldvt # ldvt ) _handle_err_maybe_convergence_problem(r) # help liveness analysis _dummy_liveness_func([acpy.size, vt.size, u.size, s.size]) return (u.T, s, vt.T) return svd_impl @overload(np.linalg.qr) def qr_impl(a): ensure_lapack() _check_linalg_matrix(a, "qr") # Need two functions, the first computes R, storing it in the upper # triangle of A with the below diagonal part of A containing elementary # reflectors needed to construct Q. The second turns the below diagonal # entries of A into Q, storing Q in A (creates orthonormal columns from # the elementary reflectors). numba_ez_geqrf = _LAPACK().numba_ez_geqrf(a.dtype) numba_ez_xxgqr = _LAPACK().numba_ez_xxgqr(a.dtype) kind = ord(get_blas_kind(a.dtype, "qr")) def qr_impl(a): n = a.shape[-1] m = a.shape[-2] if n == 0 or m == 0: raise np.linalg.LinAlgError("Arrays cannot be empty") _check_finite_matrix(a) # copy A as it will be destroyed q = _copy_to_fortran_order(a) lda = m minmn = min(m, n) tau = np.empty((minmn), dtype=a.dtype) ret = numba_ez_geqrf( kind, # kind m, # m n, # n q.ctypes, # a m, # lda tau.ctypes # tau ) if ret < 0: fatal_error_func() assert 0 # unreachable # pull out R, this is transposed because of Fortran r = np.zeros((n, minmn), dtype=a.dtype).T # the triangle in R for i in range(minmn): for j in range(i + 1): r[j, i] = q[j, i] # and the possible square in R for i in range(minmn, n): for j in range(minmn): r[j, i] = q[j, i] ret = numba_ez_xxgqr( kind, # kind m, # m minmn, # n minmn, # k q.ctypes, # a m, # lda tau.ctypes # tau ) _handle_err_maybe_convergence_problem(ret) # help liveness analysis _dummy_liveness_func([tau.size, q.size]) return (q[:, :minmn], r) return qr_impl # helpers and jitted specialisations required for np.linalg.lstsq # and np.linalg.solve. These functions have "system" in their name # as a differentiator. def _system_copy_in_b(bcpy, b, nrhs): """ Correctly copy 'b' into the 'bcpy' scratch space. """ raise NotImplementedError @overload(_system_copy_in_b) def _system_copy_in_b_impl(bcpy, b, nrhs): if b.ndim == 1: def oneD_impl(bcpy, b, nrhs): bcpy[:b.shape[-1], 0] = b return oneD_impl else: def twoD_impl(bcpy, b, nrhs): bcpy[:b.shape[-2], :nrhs] = b return twoD_impl def _system_compute_nrhs(b): """ Compute the number of right hand sides in the system of equations """ raise NotImplementedError @overload(_system_compute_nrhs) def _system_compute_nrhs_impl(b): if b.ndim == 1: def oneD_impl(b): return 1 return oneD_impl else: def twoD_impl(b): return b.shape[-1] return twoD_impl def _system_check_dimensionally_valid(a, b): """ Check that AX=B style system input is dimensionally valid. """ raise NotImplementedError @overload(_system_check_dimensionally_valid) def _system_check_dimensionally_valid_impl(a, b): ndim = b.ndim if ndim == 1: def oneD_impl(a, b): am = a.shape[-2] bm = b.shape[-1] if am != bm: raise np.linalg.LinAlgError( "Incompatible array sizes, system is not dimensionally valid.") return oneD_impl else: def twoD_impl(a, b): am = a.shape[-2] bm = b.shape[-2] if am != bm: raise np.linalg.LinAlgError( "Incompatible array sizes, system is not dimensionally valid.") return twoD_impl def _system_check_non_empty(a, b): """ Check that AX=B style system input is not empty. """ raise NotImplementedError @overload(_system_check_non_empty) def _system_check_non_empty_impl(a, b): ndim = b.ndim if ndim == 1: def oneD_impl(a, b): am = a.shape[-2] an = a.shape[-1] bm = b.shape[-1] if am == 0 or bm == 0 or an == 0: raise np.linalg.LinAlgError('Arrays cannot be empty') return oneD_impl else: def twoD_impl(a, b): am = a.shape[-2] an = a.shape[-1] bm = b.shape[-2] bn = b.shape[-1] if am == 0 or bm == 0 or an == 0 or bn == 0: raise np.linalg.LinAlgError('Arrays cannot be empty') return twoD_impl def _lstsq_residual(b, n, nrhs): """ Compute the residual from the 'b' scratch space. """ raise NotImplementedError @overload(_lstsq_residual) def _lstsq_residual_impl(b, n, nrhs): ndim = b.ndim dtype = b.dtype real_dtype = np_support.as_dtype(getattr(dtype, "underlying_float", dtype)) if ndim == 1: if isinstance(dtype, (types.Complex)): def cmplx_impl(b, n, nrhs): res = np.empty((1,), dtype=real_dtype) res[0] = np.sum(np.abs(b[n:, 0])**2) return res return cmplx_impl else: def real_impl(b, n, nrhs): res = np.empty((1,), dtype=real_dtype) res[0] = np.sum(b[n:, 0]**2) return res return real_impl else: assert ndim == 2 if isinstance(dtype, (types.Complex)): def cmplx_impl(b, n, nrhs): res = np.empty((nrhs), dtype=real_dtype) for k in range(nrhs): res[k] = np.sum(np.abs(b[n:, k])**2) return res return cmplx_impl else: def real_impl(b, n, nrhs): res = np.empty((nrhs), dtype=real_dtype) for k in range(nrhs): res[k] = np.sum(b[n:, k]**2) return res return real_impl def _lstsq_solution(b, bcpy, n): """ Extract 'x' (the lstsq solution) from the 'bcpy' scratch space. Note 'b' is only used to check the system input dimension... """ raise NotImplementedError @overload(_lstsq_solution) def _lstsq_solution_impl(b, bcpy, n): if b.ndim == 1: def oneD_impl(b, bcpy, n): return bcpy.T.ravel()[:n] return oneD_impl else: def twoD_impl(b, bcpy, n): return bcpy[:n, :].copy() return twoD_impl @overload(np.linalg.lstsq) def lstsq_impl(a, b, rcond=-1.0): ensure_lapack() _check_linalg_matrix(a, "lstsq") # B can be 1D or 2D. _check_linalg_1_or_2d_matrix(b, "lstsq") _check_homogeneous_types("lstsq", a, b) np_dt = np_support.as_dtype(a.dtype) nb_dt = a.dtype # convert typing floats to np floats for use in the impl r_type = getattr(nb_dt, "underlying_float", nb_dt) real_dtype = np_support.as_dtype(r_type) # lapack solver numba_ez_gelsd = _LAPACK().numba_ez_gelsd(a.dtype) kind = ord(get_blas_kind(nb_dt, "lstsq")) # The following functions select specialisations based on # information around 'b', a lot of this effort is required # as 'b' can be either 1D or 2D, and then there are # some optimisations available depending on real or complex # space. def lstsq_impl(a, b, rcond=-1.0): n = a.shape[-1] m = a.shape[-2] nrhs = _system_compute_nrhs(b) # check the systems have no inf or NaN _check_finite_matrix(a) _check_finite_matrix(b) # check the system is not empty _system_check_non_empty(a, b) # check the systems are dimensionally valid _system_check_dimensionally_valid(a, b) minmn = min(m, n) maxmn = max(m, n) # a is destroyed on exit, copy it acpy = _copy_to_fortran_order(a) # b is overwritten on exit with the solution, copy allocate bcpy = np.empty((nrhs, maxmn), dtype=np_dt).T # specialised copy in due to b being 1 or 2D _system_copy_in_b(bcpy, b, nrhs) # Allocate returns s = np.empty(minmn, dtype=real_dtype) rank_ptr = np.empty(1, dtype=np.int32) r = numba_ez_gelsd( kind, # kind m, # m n, # n nrhs, # nrhs acpy.ctypes, # a m, # lda bcpy.ctypes, # a maxmn, # ldb s.ctypes, # s rcond, # rcond rank_ptr.ctypes # rank ) _handle_err_maybe_convergence_problem(r) # set rank to that which was computed rank = rank_ptr[0] # compute residuals if rank < n or m <= n: res = np.empty((0), dtype=real_dtype) else: # this requires additional dispatch as there's a faster # impl if the result is in the real domain (no abs() required) res = _lstsq_residual(bcpy, n, nrhs) # extract 'x', the solution x = _lstsq_solution(b, bcpy, n) # help liveness analysis _dummy_liveness_func([acpy.size, bcpy.size, s.size, rank_ptr.size]) return (x, res, rank, s[:minmn]) return lstsq_impl def _solve_compute_return(b, bcpy): """ Extract 'x' (the solution) from the 'bcpy' scratch space. Note 'b' is only used to check the system input dimension... """ raise NotImplementedError @overload(_solve_compute_return) def _solve_compute_return_impl(b, bcpy): if b.ndim == 1: def oneD_impl(b, bcpy): return bcpy.T.ravel() return oneD_impl else: def twoD_impl(b, bcpy): return bcpy return twoD_impl @overload(np.linalg.solve) def solve_impl(a, b): ensure_lapack() _check_linalg_matrix(a, "solve") _check_linalg_1_or_2d_matrix(b, "solve") _check_homogeneous_types("solve", a, b) np_dt = np_support.as_dtype(a.dtype) nb_dt = a.dtype # the lapack solver numba_xgesv = _LAPACK().numba_xgesv(a.dtype) kind = ord(get_blas_kind(nb_dt, "solve")) def solve_impl(a, b): n = a.shape[-1] nrhs = _system_compute_nrhs(b) # check the systems have no inf or NaN _check_finite_matrix(a) _check_finite_matrix(b) # check the systems are dimensionally valid _system_check_dimensionally_valid(a, b) # a is destroyed on exit, copy it acpy = _copy_to_fortran_order(a) # b is overwritten on exit with the solution, copy allocate bcpy = np.empty((nrhs, n), dtype=np_dt).T if n == 0: return _solve_compute_return(b, bcpy) # specialised copy in due to b being 1 or 2D _system_copy_in_b(bcpy, b, nrhs) # allocate pivot array (needs to be fortran int size) ipiv = np.empty(n, dtype=F_INT_nptype) r = numba_xgesv( kind, # kind n, # n nrhs, # nhrs acpy.ctypes, # a n, # lda ipiv.ctypes, # ipiv bcpy.ctypes, # b n # ldb ) _inv_err_handler(r) # help liveness analysis _dummy_liveness_func([acpy.size, bcpy.size, ipiv.size]) return _solve_compute_return(b, bcpy) return solve_impl @overload(np.linalg.pinv) def pinv_impl(a, rcond=1.e-15): ensure_lapack() _check_linalg_matrix(a, "pinv") # convert typing floats to numpy floats for use in the impl s_type = getattr(a.dtype, "underlying_float", a.dtype) s_dtype = np_support.as_dtype(s_type) numba_ez_gesdd = _LAPACK().numba_ez_gesdd(a.dtype) numba_xxgemm = _BLAS().numba_xxgemm(a.dtype) kind = ord(get_blas_kind(a.dtype, "pinv")) JOB = ord('S') # need conjugate transposes TRANSA = ord('C') TRANSB = ord('C') # scalar constants dt = np_support.as_dtype(a.dtype) zero = np.array([0.], dtype=dt) one = np.array([1.], dtype=dt) def pinv_impl(a, rcond=1.e-15): # The idea is to build the pseudo-inverse via inverting the singular # value decomposition of a matrix `A`. Mathematically, this is roughly # A = U*S*V^H [The SV decomposition of A] # A^+ = V*(S^+)*U^H [The inverted SV decomposition of A] # where ^+ is pseudo inversion and ^H is Hermitian transpose. # As V and U are unitary, their inverses are simply their Hermitian # transpose. S has singular values on its diagonal and zero elsewhere, # it is inverted trivially by reciprocal of the diagonal values with # the exception that zero singular values remain as zero. # # The practical implementation can take advantage of a few things to # gain a few % performance increase: # * A is destroyed by the SVD algorithm from LAPACK so a copy is # required, this memory is exactly the right size in which to return # the pseudo-inverse and so can be reused for this purpose. # * The pseudo-inverse of S can be applied to either V or U^H, this # then leaves a GEMM operation to compute the inverse via either: # A^+ = (V*(S^+))*U^H # or # A^+ = V*((S^+)*U^H) # however application of S^+ to V^H or U is more convenient as they # are the result of the SVD algorithm. The application of the # diagonal system is just a matrix multiplication which results in a # row/column scaling (direction depending). To save effort, this # "matrix multiplication" is applied to the smallest of U or V^H and # only up to the point of "cut-off" (see next note) just as a direct # scaling. # * The cut-off level for application of S^+ can be used to reduce # total effort, this cut-off can come via rcond or may just naturally # be present as a result of zeros in the singular values. Regardless # there's no need to multiply by zeros in the application of S^+ to # V^H or U as above. Further, the GEMM operation can be shrunk in # effort by noting that the possible zero block generated by the # presence of zeros in S^+ has no effect apart from wasting cycles as # it is all fmadd()s where one operand is zero. The inner dimension # of the GEMM operation can therefore be set as shrunk accordingly! n = a.shape[-1] m = a.shape[-2] _check_finite_matrix(a) acpy = _copy_to_fortran_order(a) if m == 0 or n == 0: return acpy.T.ravel().reshape(a.shape).T minmn = min(m, n) u = np.empty((minmn, m), dtype=a.dtype) s = np.empty(minmn, dtype=s_dtype) vt = np.empty((n, minmn), dtype=a.dtype) r = numba_ez_gesdd( kind, # kind JOB, # job m, # m n, # n acpy.ctypes, # a m, # lda s.ctypes, # s u.ctypes, # u m, # ldu vt.ctypes, # vt minmn # ldvt ) _handle_err_maybe_convergence_problem(r) # Invert singular values under threshold. Also find the index of # the threshold value as this is the upper limit for the application # of the inverted singular values. Finding this value saves # multiplication by a block of zeros that would be created by the # application of these values to either U or V^H ahead of multiplying # them together. This is done by simply in BLAS parlance via # restricting the `k` dimension to `cut_idx` in `xgemm` whilst keeping # the leading dimensions correct. cut_at = s[0] * rcond cut_idx = 0 for k in range(minmn): if s[k] > cut_at: s[k] = 1. / s[k] cut_idx = k cut_idx += 1 # Use cut_idx so there's no scaling by 0. if m >= n: # U is largest so apply S^+ to V^H. for i in range(n): for j in range(cut_idx): vt[i, j] = vt[i, j] * s[j] else: # V^H is largest so apply S^+ to U. for i in range(cut_idx): s_local = s[i] for j in range(minmn): u[i, j] = u[i, j] * s_local # Do (v^H)^H*U^H (obviously one of the matrices includes the S^+ # scaling) and write back to acpy. Note the innner dimension of cut_idx # taking account of the possible zero block. # We can store the result in acpy, given we had to create it # for use in the SVD, and it is now redundant and the right size # but wrong shape. r = numba_xxgemm( kind, TRANSA, # TRANSA TRANSB, # TRANSB n, # M m, # N cut_idx, # K one.ctypes, # ALPHA vt.ctypes, # A minmn, # LDA u.ctypes, # B m, # LDB zero.ctypes, # BETA acpy.ctypes, # C n # LDC ) # help liveness analysis #acpy.size #vt.size #u.size #s.size #one.size #zero.size _dummy_liveness_func([acpy.size, vt.size, u.size, s.size, one.size, zero.size]) return acpy.T.ravel().reshape(a.shape).T return pinv_impl def _get_slogdet_diag_walker(a): """ Walks the diag of a LUP decomposed matrix uses that det(A) = prod(diag(lup(A))) and also that log(a)+log(b) = log(a*b) The return sign is adjusted based on the values found such that the log(value) stays in the real domain. """ if isinstance(a.dtype, types.Complex): @register_jitable def cmplx_diag_walker(n, a, sgn): # walk diagonal csgn = sgn + 0.j acc = 0. for k in range(n): absel = np.abs(a[k, k]) csgn = csgn * (a[k, k] / absel) acc = acc + np.log(absel) return (csgn, acc) return cmplx_diag_walker else: @register_jitable def real_diag_walker(n, a, sgn): # walk diagonal acc = 0. for k in range(n): v = a[k, k] if v < 0.: sgn = -sgn v = -v acc = acc + np.log(v) # sgn is a float dtype return (sgn + 0., acc) return real_diag_walker @overload(np.linalg.slogdet) def slogdet_impl(a): ensure_lapack() _check_linalg_matrix(a, "slogdet") numba_xxgetrf = _LAPACK().numba_xxgetrf(a.dtype) kind = ord(get_blas_kind(a.dtype, "slogdet")) diag_walker = _get_slogdet_diag_walker(a) ONE = a.dtype(1) ZERO = getattr(a.dtype, "underlying_float", a.dtype)(0) def slogdet_impl(a): n = a.shape[-1] if a.shape[-2] != n: msg = "Last 2 dimensions of the array must be square." raise np.linalg.LinAlgError(msg) if n == 0: return (ONE, ZERO) _check_finite_matrix(a) acpy = _copy_to_fortran_order(a) ipiv = np.empty(n, dtype=F_INT_nptype) r = numba_xxgetrf(kind, n, n, acpy.ctypes, n, ipiv.ctypes) if r > 0: # factorisation failed, return same defaults as np return (0., -np.inf) _inv_err_handler(r) # catch input-to-lapack problem # The following, prior to the call to diag_walker, is present # to account for the effect of possible permutations to the # sign of the determinant. # This is the same idea as in numpy: # File name `umath_linalg.c.src` e.g. # https://github.com/numpy/numpy/blob/master/numpy/linalg/umath_linalg.c.src # in function `@TYPE@_slogdet_single_element`. sgn = 1 for k in range(n): sgn = sgn + (ipiv[k] != (k + 1)) sgn = sgn & 1 if sgn == 0: sgn = -1 # help liveness analysis _dummy_liveness_func([ipiv.size]) return diag_walker(n, acpy, sgn) return slogdet_impl @overload(np.linalg.det) def det_impl(a): ensure_lapack() _check_linalg_matrix(a, "det") def det_impl(a): (sgn, slogdet) = np.linalg.slogdet(a) return sgn * np.exp(slogdet) return det_impl def _compute_singular_values(a): """ Compute singular values of *a*. """ raise NotImplementedError @overload(_compute_singular_values) def _compute_singular_values_impl(a): """ Returns a function to compute singular values of `a` """ numba_ez_gesdd = _LAPACK().numba_ez_gesdd(a.dtype) kind = ord(get_blas_kind(a.dtype, "svd")) # Flag for "only compute `S`" to give to xgesdd JOBZ_N = ord('N') nb_ret_type = getattr(a.dtype, "underlying_float", a.dtype) np_ret_type = np_support.as_dtype(nb_ret_type) np_dtype = np_support.as_dtype(a.dtype) # These are not referenced in the computation but must be set # for MKL. u = np.empty((1, 1), dtype=np_dtype) vt = np.empty((1, 1), dtype=np_dtype) def sv_function(a): """ Computes singular values. """ # Don't use the np.linalg.svd impl instead # call LAPACK to shortcut doing the "reconstruct # singular vectors from reflectors" step and just # get back the singular values. n = a.shape[-1] m = a.shape[-2] if m == 0 or n == 0: raise np.linalg.LinAlgError('Arrays cannot be empty') _check_finite_matrix(a) ldu = m minmn = min(m, n) # need to be >=1 but aren't referenced ucol = 1 ldvt = 1 acpy = _copy_to_fortran_order(a) # u and vt are not referenced however need to be # allocated (as done above) for MKL as it # checks for ref is nullptr. s = np.empty(minmn, dtype=np_ret_type) r = numba_ez_gesdd( kind, # kind JOBZ_N, # jobz m, # m n, # n acpy.ctypes, # a m, # lda s.ctypes, # s u.ctypes, # u ldu, # ldu vt.ctypes, # vt ldvt # ldvt ) _handle_err_maybe_convergence_problem(r) # help liveness analysis _dummy_liveness_func([acpy.size, vt.size, u.size, s.size]) return s return sv_function def _oneD_norm_2(a): """ Compute the L2-norm of 1D-array *a*. """ raise NotImplementedError @overload(_oneD_norm_2) def _oneD_norm_2_impl(a): nb_ret_type = getattr(a.dtype, "underlying_float", a.dtype) np_ret_type = np_support.as_dtype(nb_ret_type) xxnrm2 = _BLAS().numba_xxnrm2(a.dtype) kind = ord(get_blas_kind(a.dtype, "norm")) def impl(a): # Just ignore order, calls are guarded to only come # from cases where order=None or order=2. n = len(a) # Call L2-norm routine from BLAS ret = np.empty((1,), dtype=np_ret_type) jmp = int(a.strides[0] / a.itemsize) r = xxnrm2( kind, # kind n, # n a.ctypes, # x jmp, # incx ret.ctypes # result ) if r < 0: fatal_error_func() assert 0 # unreachable # help liveness analysis #ret.size #a.size _dummy_liveness_func([ret.size, a.size]) return ret[0] return impl def _get_norm_impl(x, ord_flag): # This function is quite involved as norm supports a large # range of values to select different norm types via kwarg `ord`. # The implementation below branches on dimension of the input # (1D or 2D). The default for `ord` is `None` which requires # special handling in numba, this is dealt with first in each of # the dimension branches. Following this the various norms are # computed via code that is in most cases simply a loop version # of a ufunc based version as found in numpy. # The following is common to both 1D and 2D cases. # Convert typing floats to numpy floats for use in the impl. # The return type is always a float, numba differs from numpy in # that it returns an input precision specific value whereas numpy # always returns np.float64. nb_ret_type = getattr(x.dtype, "underlying_float", x.dtype) np_ret_type = np_support.as_dtype(nb_ret_type) np_dtype = np_support.as_dtype(x.dtype) xxnrm2 = _BLAS().numba_xxnrm2(x.dtype) kind = ord(get_blas_kind(x.dtype, "norm")) if x.ndim == 1: # 1D cases # handle "ord" being "None", must be done separately if ord_flag in (None, types.none): def oneD_impl(x, ord=None): return _oneD_norm_2(x) else: def oneD_impl(x, ord=None): n = len(x) # Shortcut to handle zero length arrays # this differs slightly to numpy in that # numpy raises a ValueError for kwarg ord= # +/-np.inf as the reduction operations like # max() and min() don't accept zero length # arrays if n == 0: return 0.0 # Note: on order == 2 # This is the same as for ord=="None" but because # we have to handle "None" specially this condition # is separated if ord == 2: return _oneD_norm_2(x) elif ord == np.inf: # max(abs(x)) ret = abs(x[0]) for k in range(1, n): val = abs(x[k]) if val > ret: ret = val return ret elif ord == -np.inf: # min(abs(x)) ret = abs(x[0]) for k in range(1, n): val = abs(x[k]) if val < ret: ret = val return ret elif ord == 0: # sum(x != 0) ret = 0.0 for k in range(n): if x[k] != 0.: ret += 1. return ret elif ord == 1: # sum(abs(x)) ret = 0.0 for k in range(n): ret += abs(x[k]) return ret else: # sum(abs(x)**ord)**(1./ord) ret = 0.0 for k in range(n): ret += abs(x[k])**ord return ret**(1. / ord) return oneD_impl elif x.ndim == 2: # 2D cases # handle "ord" being "None" if ord_flag in (None, types.none): # Force `x` to be C-order, so that we can take a contiguous # 1D view. if x.layout == 'C': @register_jitable def array_prepare(x): return x elif x.layout == 'F': @register_jitable def array_prepare(x): # Legal since L2(x) == L2(x.T) return x.T else: @register_jitable def array_prepare(x): return x.copy() # Compute the Frobenius norm, this is the L2,2 induced norm of `x` # which is the L2-norm of x.ravel() and so can be computed via BLAS def twoD_impl(x, ord=None): n = x.size if n == 0: # reshape() currently doesn't support zero-sized arrays return 0.0 x_c = array_prepare(x) return _oneD_norm_2(x_c.reshape(n)) else: # max value for this dtype max_val = np.finfo(np_ret_type.type).max def twoD_impl(x, ord=None): n = x.shape[-1] m = x.shape[-2] # Shortcut to handle zero size arrays # this differs slightly to numpy in that # numpy raises errors for some ord values # and in other cases returns zero. if x.size == 0: return 0.0 if ord == np.inf: # max of sum of abs across rows # max(sum(abs(x)), axis=1) global_max = 0. for ii in range(m): tmp = 0. for jj in range(n): tmp += abs(x[ii, jj]) if tmp > global_max: global_max = tmp return global_max elif ord == -np.inf: # min of sum of abs across rows # min(sum(abs(x)), axis=1) global_min = max_val for ii in range(m): tmp = 0. for jj in range(n): tmp += abs(x[ii, jj]) if tmp < global_min: global_min = tmp return global_min elif ord == 1: # max of sum of abs across cols # max(sum(abs(x)), axis=0) global_max = 0. for ii in range(n): tmp = 0. for jj in range(m): tmp += abs(x[jj, ii]) if tmp > global_max: global_max = tmp return global_max elif ord == -1: # min of sum of abs across cols # min(sum(abs(x)), axis=0) global_min = max_val for ii in range(n): tmp = 0. for jj in range(m): tmp += abs(x[jj, ii]) if tmp < global_min: global_min = tmp return global_min # Results via SVD, singular values are sorted on return # by definition. elif ord == 2: # max SV return _compute_singular_values(x)[0] elif ord == -2: # min SV return _compute_singular_values(x)[-1] else: # replicate numpy error raise ValueError("Invalid norm order for matrices.") return twoD_impl else: assert 0 # unreachable @overload(np.linalg.norm) def norm_impl(x, ord=None): ensure_lapack() _check_linalg_1_or_2d_matrix(x, "norm") return _get_norm_impl(x, ord) @overload(np.linalg.cond) def cond_impl(x, p=None): ensure_lapack() _check_linalg_matrix(x, "cond") def impl(x, p=None): # This is extracted for performance, numpy does approximately: # `condition = norm(x) * norm(inv(x))` # in the cases of `p == 2` or `p ==-2` singular values are used # for computing norms. This costs numpy an svd of `x` then an # inversion of `x` and another svd of `x`. # Below is a different approach, which also gives a more # accurate answer as there is no inversion involved. # Recall that the singular values of an inverted matrix are the # reciprocal of singular values of the original matrix. # Therefore calling `svd(x)` once yields all the information # needed about both `x` and `inv(x)` without the cost or # potential loss of accuracy incurred through inversion. # For the case of `p == 2`, the result is just the ratio of # `largest singular value/smallest singular value`, and for the # case of `p==-2` the result is simply the # `smallest singular value/largest singular value`. # As a result of this, numba accepts non-square matrices as # input when p==+/-2 as well as when p==None. if p == 2 or p == -2 or p is None: s = _compute_singular_values(x) if p == 2 or p is None: r = np.divide(s[0], s[-1]) else: r = np.divide(s[-1], s[0]) else: # cases np.inf, -np.inf, 1, -1 norm_x = np.linalg.norm(x, p) norm_inv_x = np.linalg.norm(np.linalg.inv(x), p) r = norm_x * norm_inv_x # NumPy uses a NaN mask, if the input has a NaN, it will return NaN, # Numba calls ban NaN through the use of _check_finite_matrix but this # catches cases where NaN occurs through floating point use if np.isnan(r): return np.inf else: return r return impl @register_jitable def _get_rank_from_singular_values(sv, t): """ Gets rank from singular values with cut-off at a given tolerance """ rank = 0 for k in range(len(sv)): if sv[k] > t: rank = rank + 1 else: # sv is ordered big->small so break on condition not met break return rank @overload(np.linalg.matrix_rank) def matrix_rank_impl(A, tol=None): """ Computes rank for matrices and vectors. The only issue that may arise is that because numpy uses double precision lapack calls whereas numba uses type specific lapack calls, some singular values may differ and therefore counting the number of them above a tolerance may lead to different counts, and therefore rank, in some cases. """ ensure_lapack() _check_linalg_1_or_2d_matrix(A, "matrix_rank") def _2d_matrix_rank_impl(A, tol): # handle the tol==None case separately for type inference to work if tol in (None, types.none): nb_type = getattr(A.dtype, "underlying_float", A.dtype) np_type = np_support.as_dtype(nb_type) eps_val = np.finfo(np_type).eps def _2d_tol_none_impl(A, tol=None): s = _compute_singular_values(A) # replicate numpy default tolerance calculation r = A.shape[0] c = A.shape[1] l = max(r, c) t = s[0] * l * eps_val return _get_rank_from_singular_values(s, t) return _2d_tol_none_impl else: def _2d_tol_not_none_impl(A, tol=None): s = _compute_singular_values(A) return _get_rank_from_singular_values(s, tol) return _2d_tol_not_none_impl def _get_matrix_rank_impl(A, tol): ndim = A.ndim if ndim == 1: # NOTE: Technically, the numpy implementation could be argued as # incorrect for the case of a vector (1D matrix). If a tolerance # is provided and a vector with a singular value below tolerance is # encountered this should report a rank of zero, the numpy # implementation does not do this and instead elects to report that # if any value in the vector is nonzero then the rank is 1. # An example would be [0, 1e-15, 0, 2e-15] which numpy reports as # rank 1 invariant of `tol`. The singular value for this vector is # obviously sqrt(5)*1e-15 and so a tol of e.g. sqrt(6)*1e-15 should # lead to a reported rank of 0 whereas a tol of 1e-15 should lead # to a reported rank of 1, numpy reports 1 regardless. # The code below replicates the numpy behaviour. def _1d_matrix_rank_impl(A, tol=None): for k in range(len(A)): if A[k] != 0.: return 1 return 0 return _1d_matrix_rank_impl elif ndim == 2: return _2d_matrix_rank_impl(A, tol) else: assert 0 # unreachable return _get_matrix_rank_impl(A, tol) @overload(np.linalg.matrix_power) def matrix_power_impl(a, n): """ Computes matrix power. Only integer powers are supported in numpy. """ _check_linalg_matrix(a, "matrix_power") np_dtype = np_support.as_dtype(a.dtype) nt = getattr(n, 'dtype', n) if not isinstance(nt, types.Integer): raise NumbaTypeError("Exponent must be an integer.") def matrix_power_impl(a, n): if n == 0: # this should be eye() but it doesn't support # the dtype kwarg yet so do it manually to save # the copy required by eye(a.shape[0]).asdtype() A = np.zeros(a.shape, dtype=np_dtype) for k in range(a.shape[0]): A[k, k] = 1. return A am, an = a.shape[-1], a.shape[-2] if am != an: raise ValueError('input must be a square array') # empty, return a copy if am == 0: return a.copy() # note: to be consistent over contiguousness, C order is # returned as that is what dot() produces and the most common # paths through matrix_power will involve that. Therefore # copies are made here to ensure the data ordering is # correct for paths not going via dot(). if n < 0: A = np.linalg.inv(a).copy() if n == -1: # return now return A n = -n else: if n == 1: # return a copy now return a.copy() A = a # this is safe, `a` is only read if n < 4: if n == 2: return np.dot(A, A) if n == 3: return np.dot(np.dot(A, A), A) else: acc = A exp = n # Initialise ret, SSA cannot see the loop will execute, without this # it appears as uninitialised. ret = acc # tried a loop split and branchless using identity matrix as # input but it seems like having a "first entry" flag is quicker flag = True while exp != 0: if exp & 1: if flag: ret = acc flag = False else: ret = np.dot(ret, acc) acc = np.dot(acc, acc) exp = exp >> 1 return ret return matrix_power_impl # This is documented under linalg despite not being in the module @overload(np.trace) def matrix_trace_impl(a, offset=0): """ Computes the trace of an array. """ _check_linalg_matrix(a, "trace", la_prefix=False) if not isinstance(offset, (int, types.Integer)): raise NumbaTypeError("integer argument expected, got %s" % offset) def matrix_trace_impl(a, offset=0): rows, cols = a.shape k = offset if k < 0: rows = rows + k if k > 0: cols = cols - k n = max(min(rows, cols), 0) ret = 0 if k >= 0: for i in range(n): ret += a[i, k + i] else: for i in range(n): ret += a[i - k, i] return ret return matrix_trace_impl def _check_scalar_or_lt_2d_mat(a, func_name, la_prefix=True): prefix = "np.linalg" if la_prefix else "np" interp = (prefix, func_name) # checks that a matrix is 1 or 2D if isinstance(a, types.Array): if not a.ndim <= 2: raise TypingError("%s.%s() only supported on 1 and 2-D arrays " % interp, highlighting=False) @register_jitable def outer_impl_none(a, b, out): aa = np.asarray(a) bb = np.asarray(b) return np.multiply(aa.ravel().reshape((aa.size, 1)), bb.ravel().reshape((1, bb.size))) @register_jitable def outer_impl_arr(a, b, out): aa = np.asarray(a) bb = np.asarray(b) np.multiply(aa.ravel().reshape((aa.size, 1)), bb.ravel().reshape((1, bb.size)), out) return out def _get_outer_impl(a, b, out): if out in (None, types.none): return outer_impl_none else: return outer_impl_arr @overload(np.outer) def outer_impl(a, b, out=None): _check_scalar_or_lt_2d_mat(a, "outer", la_prefix=False) _check_scalar_or_lt_2d_mat(b, "outer", la_prefix=False) impl = _get_outer_impl(a, b, out) def outer_impl(a, b, out=None): return impl(a, b, out) return outer_impl def _kron_normaliser_impl(x): # makes x into a 2d array if isinstance(x, types.Array): if x.layout not in ('C', 'F'): raise TypingError("np.linalg.kron only supports 'C' or 'F' layout " "input arrays. Received an input of " "layout '{}'.".format(x.layout)) elif x.ndim == 2: @register_jitable def nrm_shape(x): xn = x.shape[-1] xm = x.shape[-2] return x.reshape(xm, xn) return nrm_shape else: @register_jitable def nrm_shape(x): xn = x.shape[-1] return x.reshape(1, xn) return nrm_shape else: # assume its a scalar @register_jitable def nrm_shape(x): a = np.empty((1, 1), type(x)) a[0] = x return a return nrm_shape def _kron_return(a, b): # transforms c into something that kron would return # based on the shapes of a and b a_is_arr = isinstance(a, types.Array) b_is_arr = isinstance(b, types.Array) if a_is_arr and b_is_arr: if a.ndim == 2 or b.ndim == 2: @register_jitable def ret(a, b, c): return c return ret else: @register_jitable def ret(a, b, c): return c.reshape(c.size) return ret else: # at least one of (a, b) is a scalar if a_is_arr: @register_jitable def ret(a, b, c): return c.reshape(a.shape) return ret elif b_is_arr: @register_jitable def ret(a, b, c): return c.reshape(b.shape) return ret else: # both scalars @register_jitable def ret(a, b, c): return c[0] return ret @overload(np.kron) def kron_impl(a, b): _check_scalar_or_lt_2d_mat(a, "kron", la_prefix=False) _check_scalar_or_lt_2d_mat(b, "kron", la_prefix=False) fix_a = _kron_normaliser_impl(a) fix_b = _kron_normaliser_impl(b) ret_c = _kron_return(a, b) # this is fine because the ufunc for the Hadamard product # will reject differing dtypes in a and b. dt = getattr(a, 'dtype', a) def kron_impl(a, b): aa = fix_a(a) bb = fix_b(b) am = aa.shape[-2] an = aa.shape[-1] bm = bb.shape[-2] bn = bb.shape[-1] cm = am * bm cn = an * bn # allocate c C = np.empty((cm, cn), dtype=dt) # In practice this is runs quicker than the more obvious # `each element of A multiplied by B and assigned to # a block in C` like alg. # loop over rows of A for i in range(am): # compute the column offset into C rjmp = i * bm # loop over rows of B for k in range(bm): # compute row the offset into C irjmp = rjmp + k # slice a given row of B slc = bb[k, :] # loop over columns of A for j in range(an): # vectorized assignment of an element of A # multiplied by the current row of B into # a slice of a row of C cjmp = j * bn C[irjmp, cjmp:cjmp + bn] = aa[i, j] * slc return ret_c(a, b, C) return kron_impl
_LAPACK
python
PyCQA__pyflakes
pyflakes/test/test_is_literal.py
{ "start": 85, "end": 4573 }
class ____(TestCase): def test_is_str(self): self.flakes(""" x = 'foo' if x is 'foo': pass """, IsLiteral) def test_is_bytes(self): self.flakes(""" x = b'foo' if x is b'foo': pass """, IsLiteral) def test_is_unicode(self): self.flakes(""" x = u'foo' if x is u'foo': pass """, IsLiteral) def test_is_int(self): self.flakes(""" x = 10 if x is 10: pass """, IsLiteral) def test_is_true(self): self.flakes(""" x = True if x is True: pass """) def test_is_false(self): self.flakes(""" x = False if x is False: pass """) def test_is_not_str(self): self.flakes(""" x = 'foo' if x is not 'foo': pass """, IsLiteral) def test_is_not_bytes(self): self.flakes(""" x = b'foo' if x is not b'foo': pass """, IsLiteral) def test_is_not_unicode(self): self.flakes(""" x = u'foo' if x is not u'foo': pass """, IsLiteral) def test_is_not_int(self): self.flakes(""" x = 10 if x is not 10: pass """, IsLiteral) def test_is_not_true(self): self.flakes(""" x = True if x is not True: pass """) def test_is_not_false(self): self.flakes(""" x = False if x is not False: pass """) def test_left_is_str(self): self.flakes(""" x = 'foo' if 'foo' is x: pass """, IsLiteral) def test_left_is_bytes(self): self.flakes(""" x = b'foo' if b'foo' is x: pass """, IsLiteral) def test_left_is_unicode(self): self.flakes(""" x = u'foo' if u'foo' is x: pass """, IsLiteral) def test_left_is_int(self): self.flakes(""" x = 10 if 10 is x: pass """, IsLiteral) def test_left_is_true(self): self.flakes(""" x = True if True is x: pass """) def test_left_is_false(self): self.flakes(""" x = False if False is x: pass """) def test_left_is_not_str(self): self.flakes(""" x = 'foo' if 'foo' is not x: pass """, IsLiteral) def test_left_is_not_bytes(self): self.flakes(""" x = b'foo' if b'foo' is not x: pass """, IsLiteral) def test_left_is_not_unicode(self): self.flakes(""" x = u'foo' if u'foo' is not x: pass """, IsLiteral) def test_left_is_not_int(self): self.flakes(""" x = 10 if 10 is not x: pass """, IsLiteral) def test_left_is_not_true(self): self.flakes(""" x = True if True is not x: pass """) def test_left_is_not_false(self): self.flakes(""" x = False if False is not x: pass """) def test_chained_operators_is_true(self): self.flakes(""" x = 5 if x is True < 4: pass """) def test_chained_operators_is_str(self): self.flakes(""" x = 5 if x is 'foo' < 4: pass """, IsLiteral) def test_chained_operators_is_true_end(self): self.flakes(""" x = 5 if 4 < x is True: pass """) def test_chained_operators_is_str_end(self): self.flakes(""" x = 5 if 4 < x is 'foo': pass """, IsLiteral) def test_is_tuple_constant(self): self.flakes('''\ x = 5 if x is (): pass ''', IsLiteral) def test_is_tuple_constant_containing_constants(self): self.flakes('''\ x = 5 if x is (1, '2', True, (1.5, ())): pass ''', IsLiteral) def test_is_tuple_containing_variables_ok(self): # a bit nonsensical, but does not trigger a SyntaxWarning self.flakes('''\ x = 5 if x is (x,): pass ''')
Test
python
python-openxml__python-docx
src/docx/image/tiff.py
{ "start": 151, "end": 1008 }
class ____(BaseImageHeader): """Image header parser for TIFF images. Handles both big and little endian byte ordering. """ @property def content_type(self): """Return the MIME type of this TIFF image, unconditionally the string ``image/tiff``.""" return MIME_TYPE.TIFF @property def default_ext(self): """Default filename extension, always 'tiff' for TIFF images.""" return "tiff" @classmethod def from_stream(cls, stream): """Return a |Tiff| instance containing the properties of the TIFF image in `stream`.""" parser = _TiffParser.parse(stream) px_width = parser.px_width px_height = parser.px_height horz_dpi = parser.horz_dpi vert_dpi = parser.vert_dpi return cls(px_width, px_height, horz_dpi, vert_dpi)
Tiff
python
ansible__ansible
test/lib/ansible_test/_internal/docker_util.py
{ "start": 8443, "end": 8909 }
class ____(enum.Enum): """The state of the cgroup v1 systemd hierarchy on the container host.""" SUBSYSTEM_MISSING = 'The systemd cgroup subsystem was not found.' FILESYSTEM_NOT_MOUNTED = 'The "/sys/fs/cgroup/systemd" filesystem is not mounted.' MOUNT_TYPE_NOT_CORRECT = 'The "/sys/fs/cgroup/systemd" mount type is not correct.' VALID = 'The "/sys/fs/cgroup/systemd" mount is valid.' @dataclasses.dataclass(frozen=True)
SystemdControlGroupV1Status
python
keras-team__keras
keras/src/layers/pooling/max_pooling3d.py
{ "start": 181, "end": 3228 }
class ____(BasePooling): """Max pooling operation for 3D data (spatial or spatio-temporal). Downsamples the input along its spatial dimensions (depth, height, and width) by taking the maximum value over an input window (of size defined by `pool_size`) for each channel of the input. The window is shifted by `strides` along each dimension. Args: pool_size: int or tuple of 3 integers, factors by which to downscale (dim1, dim2, dim3). If only one integer is specified, the same window length will be used for all dimensions. strides: int or tuple of 3 integers, or None. Strides values. If None, it will default to `pool_size`. If only one int is specified, the same stride size will be used for all dimensions. padding: string, either `"valid"` or `"same"` (case-insensitive). `"valid"` means no padding. `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. data_format: string, either `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)` while `"channels_first"` corresponds to inputs with shape `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be `"channels_last"`. Input shape: - If `data_format="channels_last"`: 5D tensor with shape: `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)` - If `data_format="channels_first"`: 5D tensor with shape: `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)` Output shape: - If `data_format="channels_last"`: 5D tensor with shape: `(batch_size, pooled_dim1, pooled_dim2, pooled_dim3, channels)` - If `data_format="channels_first"`: 5D tensor with shape: `(batch_size, channels, pooled_dim1, pooled_dim2, pooled_dim3)` Example: ```python depth = 30 height = 30 width = 30 channels = 3 inputs = keras.layers.Input(shape=(depth, height, width, channels)) layer = keras.layers.MaxPooling3D(pool_size=3) outputs = layer(inputs) # Shape: (batch_size, 10, 10, 10, 3) ``` """ def __init__( self, pool_size=(2, 2, 2), strides=None, padding="valid", data_format=None, name=None, **kwargs, ): super().__init__( pool_size, strides, pool_dimensions=3, pool_mode="max", padding=padding, data_format=data_format, name=name, **kwargs, )
MaxPooling3D
python
plotly__plotly.py
plotly/graph_objs/waterfall/hoverlabel/_font.py
{ "start": 233, "end": 17153 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "waterfall.hoverlabel" _path_str = "waterfall.hoverlabel.font" _valid_props = { "color", "colorsrc", "family", "familysrc", "lineposition", "linepositionsrc", "shadow", "shadowsrc", "size", "sizesrc", "style", "stylesrc", "textcase", "textcasesrc", "variant", "variantsrc", "weight", "weightsrc", } @property def color(self): """ The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list - A list or array of any of the above Returns ------- str|numpy.ndarray """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def colorsrc(self): """ Sets the source reference on Chart Studio Cloud for `color`. The 'colorsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["colorsrc"] @colorsrc.setter def colorsrc(self, val): self["colorsrc"] = val @property def family(self): """ HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. The 'family' property is a string and must be specified as: - A non-empty string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["family"] @family.setter def family(self, val): self["family"] = val @property def familysrc(self): """ Sets the source reference on Chart Studio Cloud for `family`. The 'familysrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["familysrc"] @familysrc.setter def familysrc(self, val): self["familysrc"] = val @property def lineposition(self): """ Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. The 'lineposition' property is a flaglist and may be specified as a string containing: - Any combination of ['under', 'over', 'through'] joined with '+' characters (e.g. 'under+over') OR exactly one of ['none'] (e.g. 'none') - A list or array of the above Returns ------- Any|numpy.ndarray """ return self["lineposition"] @lineposition.setter def lineposition(self, val): self["lineposition"] = val @property def linepositionsrc(self): """ Sets the source reference on Chart Studio Cloud for `lineposition`. The 'linepositionsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["linepositionsrc"] @linepositionsrc.setter def linepositionsrc(self, val): self["linepositionsrc"] = val @property def shadow(self): """ Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow for additional options. The 'shadow' property is a string and must be specified as: - A string - A number that will be converted to a string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["shadow"] @shadow.setter def shadow(self, val): self["shadow"] = val @property def shadowsrc(self): """ Sets the source reference on Chart Studio Cloud for `shadow`. The 'shadowsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["shadowsrc"] @shadowsrc.setter def shadowsrc(self, val): self["shadowsrc"] = val @property def size(self): """ The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|float|numpy.ndarray """ return self["size"] @size.setter def size(self, val): self["size"] = val @property def sizesrc(self): """ Sets the source reference on Chart Studio Cloud for `size`. The 'sizesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["sizesrc"] @sizesrc.setter def sizesrc(self, val): self["sizesrc"] = val @property def style(self): """ Sets whether a font should be styled with a normal or italic face from its family. The 'style' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'italic'] - A tuple, list, or one-dimensional numpy array of the above Returns ------- Any|numpy.ndarray """ return self["style"] @style.setter def style(self, val): self["style"] = val @property def stylesrc(self): """ Sets the source reference on Chart Studio Cloud for `style`. The 'stylesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["stylesrc"] @stylesrc.setter def stylesrc(self, val): self["stylesrc"] = val @property def textcase(self): """ Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. The 'textcase' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'word caps', 'upper', 'lower'] - A tuple, list, or one-dimensional numpy array of the above Returns ------- Any|numpy.ndarray """ return self["textcase"] @textcase.setter def textcase(self, val): self["textcase"] = val @property def textcasesrc(self): """ Sets the source reference on Chart Studio Cloud for `textcase`. The 'textcasesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["textcasesrc"] @textcasesrc.setter def textcasesrc(self, val): self["textcasesrc"] = val @property def variant(self): """ Sets the variant of the font. The 'variant' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'small-caps', 'all-small-caps', 'all-petite-caps', 'petite-caps', 'unicase'] - A tuple, list, or one-dimensional numpy array of the above Returns ------- Any|numpy.ndarray """ return self["variant"] @variant.setter def variant(self, val): self["variant"] = val @property def variantsrc(self): """ Sets the source reference on Chart Studio Cloud for `variant`. The 'variantsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["variantsrc"] @variantsrc.setter def variantsrc(self, val): self["variantsrc"] = val @property def weight(self): """ Sets the weight (or boldness) of the font. The 'weight' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 1000] OR exactly one of ['normal', 'bold'] (e.g. 'bold') - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|numpy.ndarray """ return self["weight"] @weight.setter def weight(self, val): self["weight"] = val @property def weightsrc(self): """ Sets the source reference on Chart Studio Cloud for `weight`. The 'weightsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["weightsrc"] @weightsrc.setter def weightsrc(self, val): self["weightsrc"] = val @property def _prop_descriptions(self): return """\ color colorsrc Sets the source reference on Chart Studio Cloud for `color`. family HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. familysrc Sets the source reference on Chart Studio Cloud for `family`. lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. linepositionsrc Sets the source reference on Chart Studio Cloud for `lineposition`. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. shadowsrc Sets the source reference on Chart Studio Cloud for `shadow`. size sizesrc Sets the source reference on Chart Studio Cloud for `size`. style Sets whether a font should be styled with a normal or italic face from its family. stylesrc Sets the source reference on Chart Studio Cloud for `style`. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. textcasesrc Sets the source reference on Chart Studio Cloud for `textcase`. variant Sets the variant of the font. variantsrc Sets the source reference on Chart Studio Cloud for `variant`. weight Sets the weight (or boldness) of the font. weightsrc Sets the source reference on Chart Studio Cloud for `weight`. """ def __init__( self, arg=None, color=None, colorsrc=None, family=None, familysrc=None, lineposition=None, linepositionsrc=None, shadow=None, shadowsrc=None, size=None, sizesrc=None, style=None, stylesrc=None, textcase=None, textcasesrc=None, variant=None, variantsrc=None, weight=None, weightsrc=None, **kwargs, ): """ Construct a new Font object Sets the font used in hover labels. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.waterfall.hoverlabel.Font` color colorsrc Sets the source reference on Chart Studio Cloud for `color`. family HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. familysrc Sets the source reference on Chart Studio Cloud for `family`. lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. linepositionsrc Sets the source reference on Chart Studio Cloud for `lineposition`. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. shadowsrc Sets the source reference on Chart Studio Cloud for `shadow`. size sizesrc Sets the source reference on Chart Studio Cloud for `size`. style Sets whether a font should be styled with a normal or italic face from its family. stylesrc Sets the source reference on Chart Studio Cloud for `style`. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. textcasesrc Sets the source reference on Chart Studio Cloud for `textcase`. variant Sets the variant of the font. variantsrc Sets the source reference on Chart Studio Cloud for `variant`. weight Sets the weight (or boldness) of the font. weightsrc Sets the source reference on Chart Studio Cloud for `weight`. Returns ------- Font """ super().__init__("font") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.waterfall.hoverlabel.Font constructor must be a dict or an instance of :class:`plotly.graph_objs.waterfall.hoverlabel.Font`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._set_property("colorsrc", arg, colorsrc) self._set_property("family", arg, family) self._set_property("familysrc", arg, familysrc) self._set_property("lineposition", arg, lineposition) self._set_property("linepositionsrc", arg, linepositionsrc) self._set_property("shadow", arg, shadow) self._set_property("shadowsrc", arg, shadowsrc) self._set_property("size", arg, size) self._set_property("sizesrc", arg, sizesrc) self._set_property("style", arg, style) self._set_property("stylesrc", arg, stylesrc) self._set_property("textcase", arg, textcase) self._set_property("textcasesrc", arg, textcasesrc) self._set_property("variant", arg, variant) self._set_property("variantsrc", arg, variantsrc) self._set_property("weight", arg, weight) self._set_property("weightsrc", arg, weightsrc) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Font
python
numpy__numpy
numpy/lib/tests/test_recfunctions.py
{ "start": 17869, "end": 23191 }
class ____: # Test merge_arrays def _create_arrays(self): x = np.array([1, 2, ]) y = np.array([10, 20, 30]) z = np.array( [('A', 1.), ('B', 2.)], dtype=[('A', '|S3'), ('B', float)]) w = np.array( [(1, (2, 3.0, ())), (4, (5, 6.0, ()))], dtype=[('a', int), ('b', [('ba', float), ('bb', int), ('bc', [])])]) return w, x, y, z def test_solo(self): # Test merge_arrays on a single array. _, x, _, z = self._create_arrays() test = merge_arrays(x) control = np.array([(1,), (2,)], dtype=[('f0', int)]) assert_equal(test, control) test = merge_arrays((x,)) assert_equal(test, control) test = merge_arrays(z, flatten=False) assert_equal(test, z) test = merge_arrays(z, flatten=True) assert_equal(test, z) def test_solo_w_flatten(self): # Test merge_arrays on a single array w & w/o flattening w = self._create_arrays()[0] test = merge_arrays(w, flatten=False) assert_equal(test, w) test = merge_arrays(w, flatten=True) control = np.array([(1, 2, 3.0), (4, 5, 6.0)], dtype=[('a', int), ('ba', float), ('bb', int)]) assert_equal(test, control) def test_standard(self): # Test standard & standard # Test merge arrays _, x, y, _ = self._create_arrays() test = merge_arrays((x, y), usemask=False) control = np.array([(1, 10), (2, 20), (-1, 30)], dtype=[('f0', int), ('f1', int)]) assert_equal(test, control) test = merge_arrays((x, y), usemask=True) control = ma.array([(1, 10), (2, 20), (-1, 30)], mask=[(0, 0), (0, 0), (1, 0)], dtype=[('f0', int), ('f1', int)]) assert_equal(test, control) assert_equal(test.mask, control.mask) def test_flatten(self): # Test standard & flexible _, x, _, z = self._create_arrays() test = merge_arrays((x, z), flatten=True) control = np.array([(1, 'A', 1.), (2, 'B', 2.)], dtype=[('f0', int), ('A', '|S3'), ('B', float)]) assert_equal(test, control) test = merge_arrays((x, z), flatten=False) control = np.array([(1, ('A', 1.)), (2, ('B', 2.))], dtype=[('f0', int), ('f1', [('A', '|S3'), ('B', float)])]) assert_equal(test, control) def test_flatten_wflexible(self): # Test flatten standard & nested w, x, _, _ = self._create_arrays() test = merge_arrays((x, w), flatten=True) control = np.array([(1, 1, 2, 3.0), (2, 4, 5, 6.0)], dtype=[('f0', int), ('a', int), ('ba', float), ('bb', int)]) assert_equal(test, control) test = merge_arrays((x, w), flatten=False) f1_descr = [('a', int), ('b', [('ba', float), ('bb', int), ('bc', [])])] controldtype = [('f0', int), ('f1', f1_descr)] control = np.array([(1., (1, (2, 3.0, ()))), (2, (4, (5, 6.0, ())))], dtype=controldtype) assert_equal(test, control) def test_wmasked_arrays(self): # Test merge_arrays masked arrays x = self._create_arrays()[1] mx = ma.array([1, 2, 3], mask=[1, 0, 0]) test = merge_arrays((x, mx), usemask=True) control = ma.array([(1, 1), (2, 2), (-1, 3)], mask=[(0, 1), (0, 0), (1, 0)], dtype=[('f0', int), ('f1', int)]) assert_equal(test, control) test = merge_arrays((x, mx), usemask=True, asrecarray=True) assert_equal(test, control) assert_(isinstance(test, MaskedRecords)) def test_w_singlefield(self): # Test single field test = merge_arrays((np.array([1, 2]).view([('a', int)]), np.array([10., 20., 30.])),) control = ma.array([(1, 10.), (2, 20.), (-1, 30.)], mask=[(0, 0), (0, 0), (1, 0)], dtype=[('a', int), ('f1', float)]) assert_equal(test, control) def test_w_shorter_flex(self): # Test merge_arrays w/ a shorter flexndarray. z = self._create_arrays()[-1] # Fixme, this test looks incomplete and broken #test = merge_arrays((z, np.array([10, 20, 30]).view([('C', int)]))) #control = np.array([('A', 1., 10), ('B', 2., 20), ('-1', -1, 20)], # dtype=[('A', '|S3'), ('B', float), ('C', int)]) #assert_equal(test, control) merge_arrays((z, np.array([10, 20, 30]).view([('C', int)]))) np.array([('A', 1., 10), ('B', 2., 20), ('-1', -1, 20)], dtype=[('A', '|S3'), ('B', float), ('C', int)]) def test_singlerecord(self): _, x, y, z = self._create_arrays() test = merge_arrays((x[0], y[0], z[0]), usemask=False) control = np.array([(1, 10, ('A', 1))], dtype=[('f0', int), ('f1', int), ('f2', [('A', '|S3'), ('B', float)])]) assert_equal(test, control)
TestMergeArrays
python
airbytehq__airbyte
airbyte-integrations/connectors/source-webflow/source_webflow/source.py
{ "start": 10601, "end": 14604 }
class ____(AbstractSource): """This is the main class that defines the methods that will be called by Airbyte infrastructure""" @staticmethod def _get_collection_name_to_id_dict(authenticator: str = None, site_id: str = None) -> Mapping[str, str]: """ Most of the Webflow APIs require the collection id, but the streams that we are generating use the collection name. This function will return a dictionary containing collection_name: collection_id entries. """ collection_name_to_id_dict = {} collections_stream = CollectionsList(authenticator=authenticator, site_id=site_id) collections_records = collections_stream.read_records(sync_mode="full_refresh") # Loop over the list of records and create a dictionary with name as key, and _id as value for collection_obj in collections_records: collection_name_to_id_dict[collection_obj["name"]] = collection_obj["_id"] return collection_name_to_id_dict @staticmethod def get_authenticator(config): """ Verifies that the information for setting the header has been set, and returns a class which overloads that standard authentication to include additional headers that are required by Webflow. """ api_key = config.get("api_key", None) accept_version = config.get("accept_version", WEBFLOW_ACCEPT_VERSION) if not api_key: raise Exception("Config validation error: 'api_key' is a required property") auth = WebflowTokenAuthenticator(token=api_key, accept_version=accept_version) return auth def check_connection(self, logger: logging.Logger, config: Mapping[str, Any]) -> Tuple[bool, any]: """ A check to validate that the user-provided config can be used to connect to the underlying API :param config: the user-input config object conforming to the connector's spec.yaml :param logger: logger object :return Tuple[bool, any]: (True, None) if the input config can be used to connect to the API successfully, (False, error) otherwise. """ try: # Check that authenticator can be retrieved auth = self.get_authenticator(config) site_id = config.get("site_id") collections_stream = CollectionsList(authenticator=auth, site_id=site_id) collections_records = collections_stream.read_records(sync_mode="full_refresh") record = next(collections_records) logger.info(f"Successfully connected to CollectionsList stream. Pulled one record: {record}") return True, None except Exception as e: return False, e def generate_streams(self, authenticator: WebflowTokenAuthenticator, site_id: str) -> List[Stream]: """Generates a list of stream by their names.""" collection_name_to_id_dict = self._get_collection_name_to_id_dict(authenticator=authenticator, site_id=site_id) for collection_name, collection_id in collection_name_to_id_dict.items(): yield CollectionContents( authenticator=authenticator, site_id=site_id, collection_id=collection_id, collection_name=collection_name, ) def streams(self, config: Mapping[str, Any]) -> List[Stream]: """ :param config: A Mapping of the user input configuration as defined in the connector spec. :return List[Stream]: A list/generator of the streams that Airbyte can pull data from. """ auth = self.get_authenticator(config) site_id = config.get("site_id") # Return a list (iterator) of the streams that will be available for use. # We _dynamically_ generate streams that correspond to Webflow collections (eg. Blog Authors, Blog Posts, etc.) streams = self.generate_streams(authenticator=auth, site_id=site_id) return streams
SourceWebflow
python
python-pillow__Pillow
src/PIL/PngImagePlugin.py
{ "start": 37392, "end": 37748 }
class ____: # wrap encoder output in fdAT chunks def __init__(self, fp: IO[bytes], chunk: Callable[..., None], seq_num: int) -> None: self.fp = fp self.chunk = chunk self.seq_num = seq_num def write(self, data: bytes) -> None: self.chunk(self.fp, b"fdAT", o32(self.seq_num), data) self.seq_num += 1
_fdat
python
PrefectHQ__prefect
src/prefect/server/events/schemas/events.py
{ "start": 2247, "end": 3214 }
class ____(Resource): """A Resource with a specific role in an Event""" @model_validator(mode="after") def requires_resource_role(self) -> Self: if "prefect.resource.role" not in self.root: raise ValueError( "Related Resources must include the prefect.resource.role label" ) if not self.root["prefect.resource.role"]: raise ValueError("The prefect.resource.role label must be non-empty") return self @property def role(self) -> str: return self["prefect.resource.role"] def _validate_event_name_length(value: str) -> str: from prefect.settings import PREFECT_SERVER_EVENTS_MAXIMUM_EVENT_NAME_LENGTH if len(value) > PREFECT_SERVER_EVENTS_MAXIMUM_EVENT_NAME_LENGTH.value(): raise ValueError( f"Event name must be at most {PREFECT_SERVER_EVENTS_MAXIMUM_EVENT_NAME_LENGTH.value()} characters" ) return value
RelatedResource
python
django-mptt__django-mptt
tests/myapp/tests.py
{ "start": 58748, "end": 59382 }
class ____(TreeTestCase): def test_alters_data(self): node = Node() output = Template("{{ node.save }}").render( Context( { "node": node, } ) ) self.assertEqual(output, "") self.assertEqual(node.pk, None) node.save() self.assertNotEqual(node.pk, None) output = Template("{{ node.delete }}").render( Context( { "node": node, } ) ) self.assertEqual(node, Node.objects.get(pk=node.pk))
TestAltersData
python
lepture__authlib
authlib/integrations/sqla_oauth2/client_mixin.py
{ "start": 377, "end": 4371 }
class ____(ClientMixin): client_id = Column(String(48), index=True) client_secret = Column(String(120)) client_id_issued_at = Column(Integer, nullable=False, default=0) client_secret_expires_at = Column(Integer, nullable=False, default=0) _client_metadata = Column("client_metadata", Text) @property def client_info(self): """Implementation for Client Info in OAuth 2.0 Dynamic Client Registration Protocol via `Section 3.2.1`_. .. _`Section 3.2.1`: https://tools.ietf.org/html/rfc7591#section-3.2.1 """ return dict( client_id=self.client_id, client_secret=self.client_secret, client_id_issued_at=self.client_id_issued_at, client_secret_expires_at=self.client_secret_expires_at, ) @property def client_metadata(self): if "client_metadata" in self.__dict__: return self.__dict__["client_metadata"] if self._client_metadata: data = json_loads(self._client_metadata) self.__dict__["client_metadata"] = data return data return {} def set_client_metadata(self, value): self._client_metadata = json_dumps(value) if "client_metadata" in self.__dict__: del self.__dict__["client_metadata"] @property def redirect_uris(self): return self.client_metadata.get("redirect_uris", []) @property def token_endpoint_auth_method(self): return self.client_metadata.get( "token_endpoint_auth_method", "client_secret_basic" ) @property def grant_types(self): return self.client_metadata.get("grant_types", []) @property def response_types(self): return self.client_metadata.get("response_types", []) @property def client_name(self): return self.client_metadata.get("client_name") @property def client_uri(self): return self.client_metadata.get("client_uri") @property def logo_uri(self): return self.client_metadata.get("logo_uri") @property def scope(self): return self.client_metadata.get("scope", "") @property def contacts(self): return self.client_metadata.get("contacts", []) @property def tos_uri(self): return self.client_metadata.get("tos_uri") @property def policy_uri(self): return self.client_metadata.get("policy_uri") @property def jwks_uri(self): return self.client_metadata.get("jwks_uri") @property def jwks(self): return self.client_metadata.get("jwks", []) @property def software_id(self): return self.client_metadata.get("software_id") @property def software_version(self): return self.client_metadata.get("software_version") @property def id_token_signed_response_alg(self): return self.client_metadata.get("id_token_signed_response_alg") def get_client_id(self): return self.client_id def get_default_redirect_uri(self): if self.redirect_uris: return self.redirect_uris[0] def get_allowed_scope(self, scope): if not scope: return "" allowed = set(self.scope.split()) scopes = scope_to_list(scope) return list_to_scope([s for s in scopes if s in allowed]) def check_redirect_uri(self, redirect_uri): return redirect_uri in self.redirect_uris def check_client_secret(self, client_secret): return secrets.compare_digest(self.client_secret, client_secret) def check_endpoint_auth_method(self, method, endpoint): if endpoint == "token": return self.token_endpoint_auth_method == method # TODO return True def check_response_type(self, response_type): return response_type in self.response_types def check_grant_type(self, grant_type): return grant_type in self.grant_types
OAuth2ClientMixin
python
mlflow__mlflow
dev/clint/src/clint/rules/mock_patch_as_decorator.py
{ "start": 84, "end": 981 }
class ____(Rule): def _message(self) -> str: return ( "Do not use `unittest.mock.patch` as a decorator. " "Use it as a context manager to avoid patches being active longer than needed " "and to make it clear which code depends on them." ) @staticmethod def check(decorator_list: list[ast.expr], resolver: Resolver) -> ast.expr | None: """ Returns the decorator node if it is a `@mock.patch` or `@patch` decorator. """ for deco in decorator_list: if res := resolver.resolve(deco): match res: # Resolver returns ["unittest", "mock", "patch", ...] # The *_ captures variants like "object", "dict", etc. case ["unittest", "mock", "patch", *_]: return deco return None
MockPatchAsDecorator
python
apache__airflow
providers/ftp/tests/unit/ftp/operators/test_ftp.py
{ "start": 8095, "end": 15017 }
class ____: def setup_method(self): self.test_local_dir = "ftpstmp" self.test_remote_dir = "/ftpshome" self.test_remote_dir_int = "/ftpshome/interdir" self.test_local_filename = "test_local_file" self.test_remote_filename = "test_remote_file" self.test_local_filepath = f"{self.test_local_dir}/{self.test_local_filename}" self.test_remote_filepath = f"{self.test_remote_dir}/{self.test_remote_filename}" self.test_local_filepath_int_dir = f"{self.test_local_dir}/{self.test_local_filename}" self.test_remote_filepath_int_dir = f"{self.test_remote_dir_int}/{self.test_remote_filename}" @mock.patch("airflow.providers.ftp.operators.ftp.FTPSHook.store_file") @mock.patch("airflow.providers.ftp.operators.ftp.FTPSHook.create_directory") def test_file_transfer_put(self, mock_create_dir, mock_put): ftps_op = FTPSFileTransmitOperator( task_id="test_ftps_put", ftp_conn_id=DEFAULT_CONN_ID, local_filepath=self.test_local_filepath, remote_filepath=self.test_remote_filepath, operation=FTPOperation.PUT, ) ftps_op.execute(None) assert not mock_create_dir.called mock_put.assert_called_once_with(self.test_remote_filepath, self.test_local_filepath) @mock.patch("airflow.providers.ftp.operators.ftp.FTPSHook.store_file") @mock.patch("airflow.providers.ftp.operators.ftp.FTPSHook.create_directory") def test_file_transfer_with_intermediate_dir_put(self, mock_create_dir, mock_put): ftps_op = FTPSFileTransmitOperator( task_id="test_ftps_put_imm_dirs", ftp_conn_id=DEFAULT_CONN_ID, local_filepath=self.test_local_filepath, remote_filepath=self.test_remote_filepath_int_dir, operation=FTPOperation.PUT, create_intermediate_dirs=True, ) ftps_op.execute(None) mock_create_dir.assert_called_with(self.test_remote_dir_int) mock_put.assert_called_once_with(self.test_remote_filepath_int_dir, self.test_local_filepath) @mock.patch("airflow.providers.ftp.operators.ftp.FTPSHook.retrieve_file") def test_file_transfer_get(self, mock_get): ftps_op = FTPSFileTransmitOperator( task_id="test_ftps_get", ftp_conn_id=DEFAULT_CONN_ID, local_filepath=self.test_local_filepath, remote_filepath=self.test_remote_filepath, operation=FTPOperation.GET, ) ftps_op.execute(None) mock_get.assert_called_once_with(self.test_remote_filepath, self.test_local_filepath) @mock.patch("airflow.providers.ftp.operators.ftp.FTPHook.retrieve_file") def test_file_transfer_with_intermediate_dir_get(self, mock_get, tmp_path): ftp_op = FTPFileTransmitOperator( task_id="test_ftp_get_imm_dirs", ftp_conn_id=DEFAULT_CONN_ID, local_filepath=str(tmp_path / self.test_local_filepath_int_dir), remote_filepath=self.test_remote_filepath, operation=FTPOperation.GET, create_intermediate_dirs=True, ) ftp_op.execute(None) assert len(list(tmp_path.iterdir())) == 1 mock_get.assert_called_once_with( self.test_remote_filepath, str(tmp_path / self.test_local_filepath_int_dir) ) @mock.patch("airflow.providers.ftp.operators.ftp.FTPSHook.retrieve_file") def test_multiple_paths_get(self, mock_get): local_filepath = ["/tmp/ltest1", "/tmp/ltest2"] remote_filepath = ["/tmp/rtest1", "/tmp/rtest2"] ftps_op = FTPSFileTransmitOperator( task_id="test_multiple_paths_get", ftp_conn_id=DEFAULT_CONN_ID, local_filepath=local_filepath, remote_filepath=remote_filepath, operation=FTPOperation.GET, ) ftps_op.execute(None) assert mock_get.call_count == 2 for count, (args, _) in enumerate(mock_get.call_args_list): assert args == (remote_filepath[count], local_filepath[count]) @mock.patch("airflow.providers.ftp.operators.ftp.FTPSHook.store_file") def test_multiple_paths_put(self, mock_put): local_filepath = ["/tmp/ltest1", "/tmp/ltest2"] remote_filepath = ["/tmp/rtest1", "/tmp/rtest2"] ftps_op = FTPSFileTransmitOperator( task_id="test_multiple_paths_put", ftp_conn_id=DEFAULT_CONN_ID, local_filepath=local_filepath, remote_filepath=remote_filepath, operation=FTPOperation.PUT, ) ftps_op.execute(None) assert mock_put.call_count == 2 for count, (args, _) in enumerate(mock_put.call_args_list): assert args == (remote_filepath[count], local_filepath[count]) @mock.patch("airflow.providers.ftp.hooks.ftp.FTPHook.get_conn", spec=Connection) def test_extract_get(self, get_conn): get_conn.return_value = Connection( conn_id="ftp_conn_id", conn_type="ftp", host="remotehost", port=21, ) dag_id = "ftp_dag" task_id = "ftp_task" task = FTPFileTransmitOperator( task_id=task_id, ftp_conn_id="ftp_conn_id", dag=DAG(dag_id, schedule=None), start_date=timezone.utcnow(), local_filepath="/path/to/local", remote_filepath="/path/to/remote", operation=FTPOperation.GET, ) lineage = task.get_openlineage_facets_on_start() assert lineage.inputs == [Dataset(namespace="file://remotehost:21", name="/path/to/remote")] assert lineage.outputs == [ Dataset( namespace=f"file://{socket.gethostbyname(socket.gethostname())}:21", name="/path/to/local" ) ] @mock.patch("airflow.providers.ftp.hooks.ftp.FTPHook.get_conn", spec=Connection) def test_extract_put(self, get_conn): get_conn.return_value = Connection( conn_id="ftp_conn_id", conn_type="ftp", host="remotehost", port=21, ) dag_id = "ftp_dag" task_id = "ftp_task" task = FTPFileTransmitOperator( task_id=task_id, ftp_conn_id="ftp_conn_id", dag=DAG(dag_id, schedule=None), start_date=timezone.utcnow(), local_filepath="/path/to/local", remote_filepath="/path/to/remote", operation=FTPOperation.PUT, ) lineage = task.get_openlineage_facets_on_start() assert lineage.inputs == [ Dataset( namespace=f"file://{socket.gethostbyname(socket.gethostname())}:21", name="/path/to/local" ) ] assert lineage.outputs == [Dataset(namespace="file://remotehost:21", name="/path/to/remote")]
TestFTPSFileTransmitOperator
python
bokeh__bokeh
src/bokeh/models/widgets/buttons.py
{ "start": 3749, "end": 4461 }
class ____(AbstractButton): ''' A click button. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) label = Override(default="Button") def on_click(self, handler: EventCallback) -> None: ''' Set up a handler for button clicks. Args: handler (func) : handler function to call when button is clicked. Returns: None ''' self.on_event(ButtonClick, handler) def js_on_click(self, handler: Callback) -> None: ''' Set up a JavaScript handler for button clicks. ''' self.js_on_event(ButtonClick, handler)
Button
python
pydata__xarray
xarray/tests/test_parallelcompat.py
{ "start": 4388, "end": 6443 }
class ____: def test_get_chunkmanger(self, register_dummy_chunkmanager) -> None: chunkmanager = guess_chunkmanager("dummy") assert isinstance(chunkmanager, DummyChunkManager) def test_get_chunkmanger_via_set_options(self, register_dummy_chunkmanager) -> None: with set_options(chunk_manager="dummy"): chunkmanager = guess_chunkmanager(None) assert isinstance(chunkmanager, DummyChunkManager) def test_fail_on_known_but_missing_chunkmanager( self, register_dummy_chunkmanager, monkeypatch ) -> None: monkeypatch.setitem(KNOWN_CHUNKMANAGERS, "test", "test-package") with pytest.raises( ImportError, match=r"chunk manager 'test' is not available.+test-package" ): guess_chunkmanager("test") def test_fail_on_nonexistent_chunkmanager( self, register_dummy_chunkmanager ) -> None: with pytest.raises(ValueError, match="unrecognized chunk manager 'foo'"): guess_chunkmanager("foo") @requires_dask def test_get_dask_if_installed(self) -> None: chunkmanager = guess_chunkmanager(None) assert isinstance(chunkmanager, DaskManager) def test_no_chunk_manager_available(self, monkeypatch) -> None: monkeypatch.setattr("xarray.namedarray.parallelcompat.list_chunkmanagers", dict) with pytest.raises(ImportError, match="no chunk managers available"): guess_chunkmanager("foo") def test_no_chunk_manager_available_but_known_manager_requested( self, monkeypatch ) -> None: monkeypatch.setattr("xarray.namedarray.parallelcompat.list_chunkmanagers", dict) with pytest.raises(ImportError, match="chunk manager 'dask' is not available"): guess_chunkmanager("dask") @requires_dask def test_choose_dask_over_other_chunkmanagers( self, register_dummy_chunkmanager ) -> None: chunk_manager = guess_chunkmanager(None) assert isinstance(chunk_manager, DaskManager)
TestGetChunkManager
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py
{ "start": 140046, "end": 140581 }
class ____(nn.Module): def __init__(self, dim): super().__init__() self.dim = dim def forward(self, hidden_states, scale=1000): device = hidden_states.device half_dim = self.dim // 2 emb = math.log(10000) / (half_dim - 1) emb = torch.exp(torch.arange(half_dim, device=device).float() * -emb) emb = scale * hidden_states.unsqueeze(1) * emb.unsqueeze(0) emb = torch.cat((emb.sin(), emb.cos()), dim=-1) return emb.type_as(hidden_states)
SinusPositionEmbedding
python
pydata__xarray
xarray/tests/test_backends.py
{ "start": 13537, "end": 39300 }
class ____: engine: T_NetcdfEngine | None = None file_format: T_NetcdfTypes | None = None def create_store(self): raise NotImplementedError() @contextlib.contextmanager def roundtrip( self, data, save_kwargs=None, open_kwargs=None, allow_cleanup_failure=False ): if save_kwargs is None: save_kwargs = {} if open_kwargs is None: open_kwargs = {} with create_tmp_file(allow_cleanup_failure=allow_cleanup_failure) as path: self.save(data, path, **save_kwargs) with self.open(path, **open_kwargs) as ds: yield ds @contextlib.contextmanager def roundtrip_append( self, data, save_kwargs=None, open_kwargs=None, allow_cleanup_failure=False ): if save_kwargs is None: save_kwargs = {} if open_kwargs is None: open_kwargs = {} with create_tmp_file(allow_cleanup_failure=allow_cleanup_failure) as path: for i, key in enumerate(data.variables): mode = "a" if i > 0 else "w" self.save(data[[key]], path, mode=mode, **save_kwargs) with self.open(path, **open_kwargs) as ds: yield ds # The save/open methods may be overwritten below def save(self, dataset, path, **kwargs): return dataset.to_netcdf( path, engine=self.engine, format=self.file_format, **kwargs ) @contextlib.contextmanager def open(self, path, **kwargs): with open_dataset(path, engine=self.engine, **kwargs) as ds: yield ds def test_zero_dimensional_variable(self) -> None: expected = create_test_data() expected["float_var"] = ([], 1.0e9, {"units": "units of awesome"}) expected["bytes_var"] = ([], b"foobar") expected["string_var"] = ([], "foobar") with self.roundtrip(expected) as actual: assert_identical(expected, actual) def test_write_store(self) -> None: expected = create_test_data() with self.create_store() as store: expected.dump_to_store(store) # we need to cf decode the store because it has time and # non-dimension coordinates with xr.decode_cf(store) as actual: assert_allclose(expected, actual) def check_dtypes_roundtripped(self, expected, actual): for k in expected.variables: expected_dtype = expected.variables[k].dtype # For NetCDF3, the backend should perform dtype coercion if ( isinstance(self, NetCDF3Only) and str(expected_dtype) in _nc3_dtype_coercions ): expected_dtype = np.dtype(_nc3_dtype_coercions[str(expected_dtype)]) actual_dtype = actual.variables[k].dtype # TODO: check expected behavior for string dtypes more carefully string_kinds = {"O", "S", "U"} assert expected_dtype == actual_dtype or ( expected_dtype.kind in string_kinds and actual_dtype.kind in string_kinds ) def test_roundtrip_test_data(self) -> None: expected = create_test_data() with self.roundtrip(expected) as actual: self.check_dtypes_roundtripped(expected, actual) assert_identical(expected, actual) def test_load(self) -> None: # Note: please keep this in sync with test_load_async below as much as possible! expected = create_test_data() @contextlib.contextmanager def assert_loads(vars=None): if vars is None: vars = expected with self.roundtrip(expected) as actual: for k, v in actual.variables.items(): # IndexVariables are eagerly loaded into memory assert v._in_memory == (k in actual.dims) yield actual for k, v in actual.variables.items(): if k in vars: assert v._in_memory assert_identical(expected, actual) with pytest.raises(AssertionError): # make sure the contextmanager works! with assert_loads() as ds: pass with assert_loads() as ds: ds.load() with assert_loads(["var1", "dim1", "dim2"]) as ds: ds["var1"].load() # verify we can read data even after closing the file with self.roundtrip(expected) as ds: actual = ds.load() assert_identical(expected, actual) @pytest.mark.asyncio async def test_load_async(self) -> None: # Note: please keep this in sync with test_load above as much as possible! # Copied from `test_load` on the base test class, but won't work for netcdf expected = create_test_data() @contextlib.contextmanager def assert_loads(vars=None): if vars is None: vars = expected with self.roundtrip(expected) as actual: for k, v in actual.variables.items(): # IndexVariables are eagerly loaded into memory assert v._in_memory == (k in actual.dims) yield actual for k, v in actual.variables.items(): if k in vars: assert v._in_memory assert_identical(expected, actual) with pytest.raises(AssertionError): # make sure the contextmanager works! with assert_loads() as ds: pass with assert_loads() as ds: await ds.load_async() with assert_loads(["var1", "dim1", "dim2"]) as ds: await ds["var1"].load_async() # verify we can read data even after closing the file with self.roundtrip(expected) as ds: actual = await ds.load_async() assert_identical(expected, actual) def test_dataset_compute(self) -> None: expected = create_test_data() with self.roundtrip(expected) as actual: # Test Dataset.compute() for k, v in actual.variables.items(): # IndexVariables are eagerly cached assert v._in_memory == (k in actual.dims) computed = actual.compute() for k, v in actual.variables.items(): assert v._in_memory == (k in actual.dims) for v in computed.variables.values(): assert v._in_memory assert_identical(expected, actual) assert_identical(expected, computed) def test_pickle(self) -> None: expected = Dataset({"foo": ("x", [42])}) with self.roundtrip(expected, allow_cleanup_failure=ON_WINDOWS) as roundtripped: # Windows doesn't like reopening an already open file raw_pickle = pickle.dumps(roundtripped) with pickle.loads(raw_pickle) as unpickled_ds: assert_identical(expected, unpickled_ds) def test_pickle_dataarray(self) -> None: expected = Dataset({"foo": ("x", [42])}) with self.roundtrip(expected, allow_cleanup_failure=ON_WINDOWS) as roundtripped: raw_pickle = pickle.dumps(roundtripped["foo"]) with pickle.loads(raw_pickle) as unpickled: assert_identical(expected["foo"], unpickled) def test_dataset_caching(self) -> None: expected = Dataset({"foo": ("x", [5, 6, 7])}) with self.roundtrip(expected) as actual: assert isinstance(actual.foo.variable._data, indexing.MemoryCachedArray) assert not actual.foo.variable._in_memory _ = actual.foo.values # cache assert actual.foo.variable._in_memory with self.roundtrip(expected, open_kwargs={"cache": False}) as actual: assert isinstance(actual.foo.variable._data, indexing.CopyOnWriteArray) assert not actual.foo.variable._in_memory _ = actual.foo.values # no caching assert not actual.foo.variable._in_memory def test_roundtrip_None_variable(self) -> None: expected = Dataset({None: (("x", "y"), [[0, 1], [2, 3]])}) with self.roundtrip(expected) as actual: assert_identical(expected, actual) def test_roundtrip_object_dtype(self) -> None: floats = np.array([0.0, 0.0, 1.0, 2.0, 3.0], dtype=object) floats_nans = np.array([np.nan, np.nan, 1.0, 2.0, 3.0], dtype=object) bytes_ = np.array([b"ab", b"cdef", b"g"], dtype=object) bytes_nans = np.array([b"ab", b"cdef", np.nan], dtype=object) strings = np.array(["ab", "cdef", "g"], dtype=object) strings_nans = np.array(["ab", "cdef", np.nan], dtype=object) all_nans = np.array([np.nan, np.nan], dtype=object) original = Dataset( { "floats": ("a", floats), "floats_nans": ("a", floats_nans), "bytes": ("b", bytes_), "bytes_nans": ("b", bytes_nans), "strings": ("b", strings), "strings_nans": ("b", strings_nans), "all_nans": ("c", all_nans), "nan": ([], np.nan), } ) expected = original.copy(deep=True) with self.roundtrip(original) as actual: try: assert_identical(expected, actual) except AssertionError: # Most stores use '' for nans in strings, but some don't. # First try the ideal case (where the store returns exactly) # the original Dataset), then try a more realistic case. # This currently includes all netCDF files when encoding is not # explicitly set. # https://github.com/pydata/xarray/issues/1647 # Also Zarr expected["bytes_nans"][-1] = b"" expected["strings_nans"][-1] = "" assert_identical(expected, actual) def test_roundtrip_string_data(self) -> None: expected = Dataset({"x": ("t", ["ab", "cdef"])}) with self.roundtrip(expected) as actual: assert_identical(expected, actual) def test_roundtrip_string_encoded_characters(self) -> None: expected = Dataset({"x": ("t", ["ab", "cdef"])}) expected["x"].encoding["dtype"] = "S1" with self.roundtrip(expected) as actual: assert_identical(expected, actual) assert actual["x"].encoding["_Encoding"] == "utf-8" expected["x"].encoding["_Encoding"] = "ascii" with self.roundtrip(expected) as actual: assert_identical(expected, actual) assert actual["x"].encoding["_Encoding"] == "ascii" def test_roundtrip_numpy_datetime_data(self) -> None: times = pd.to_datetime(["2000-01-01", "2000-01-02", "NaT"], unit="ns") expected = Dataset({"t": ("t", times), "t0": times[0]}) kwargs = {"encoding": {"t0": {"units": "days since 1950-01-01"}}} with self.roundtrip(expected, save_kwargs=kwargs) as actual: assert_identical(expected, actual) assert actual.t0.encoding["units"] == "days since 1950-01-01" @requires_cftime def test_roundtrip_cftime_datetime_data(self) -> None: from xarray.tests.test_coding_times import _all_cftime_date_types date_types = _all_cftime_date_types() for date_type in date_types.values(): times = [date_type(1, 1, 1), date_type(1, 1, 2)] expected = Dataset({"t": ("t", times), "t0": times[0]}) kwargs = {"encoding": {"t0": {"units": "days since 0001-01-01"}}} expected_decoded_t = np.array(times) expected_decoded_t0 = np.array([date_type(1, 1, 1)]) expected_calendar = times[0].calendar with warnings.catch_warnings(): if expected_calendar in {"proleptic_gregorian", "standard"}: warnings.filterwarnings("ignore", "Unable to decode time axis") with self.roundtrip(expected, save_kwargs=kwargs) as actual: # proleptic gregorian will be decoded into numpy datetime64 # fixing to expectations if actual.t.dtype.kind == "M": dtype = actual.t.dtype expected_decoded_t = expected_decoded_t.astype(dtype) expected_decoded_t0 = expected_decoded_t0.astype(dtype) assert_array_equal(actual.t.values, expected_decoded_t) assert ( actual.t.encoding["units"] == "days since 0001-01-01 00:00:00.000000" ) assert actual.t.encoding["calendar"] == expected_calendar assert_array_equal(actual.t0.values, expected_decoded_t0) assert actual.t0.encoding["units"] == "days since 0001-01-01" assert actual.t.encoding["calendar"] == expected_calendar def test_roundtrip_timedelta_data(self) -> None: # todo: suggestion from review: # roundtrip large microsecond or coarser resolution timedeltas, # though we cannot test that until we fix the timedelta decoding # to support large ranges time_deltas = pd.to_timedelta(["1h", "2h", "NaT"]).as_unit("s") # type: ignore[arg-type, unused-ignore] encoding = {"units": "seconds"} expected = Dataset({"td": ("td", time_deltas), "td0": time_deltas[0]}) expected["td"].encoding = encoding expected["td0"].encoding = encoding with self.roundtrip( expected, open_kwargs={"decode_timedelta": CFTimedeltaCoder(time_unit="ns")} ) as actual: assert_identical(expected, actual) def test_roundtrip_timedelta_data_via_dtype( self, time_unit: PDDatetimeUnitOptions ) -> None: time_deltas = pd.to_timedelta(["1h", "2h", "NaT"]).as_unit(time_unit) # type: ignore[arg-type, unused-ignore] expected = Dataset( {"td": ("td", time_deltas), "td0": time_deltas[0].to_numpy()} ) with self.roundtrip(expected) as actual: assert_identical(expected, actual) def test_roundtrip_float64_data(self) -> None: expected = Dataset({"x": ("y", np.array([1.0, 2.0, np.pi], dtype="float64"))}) with self.roundtrip(expected) as actual: assert_identical(expected, actual) @requires_netcdf def test_roundtrip_example_1_netcdf(self) -> None: with open_example_dataset("example_1.nc") as expected: with self.roundtrip(expected) as actual: # we allow the attributes to differ since that # will depend on the encoding used. For example, # without CF encoding 'actual' will end up with # a dtype attribute. assert_equal(expected, actual) def test_roundtrip_coordinates(self) -> None: original = Dataset( {"foo": ("x", [0, 1])}, {"x": [2, 3], "y": ("a", [42]), "z": ("x", [4, 5])} ) with self.roundtrip(original) as actual: assert_identical(original, actual) original["foo"].encoding["coordinates"] = "y" with self.roundtrip(original, open_kwargs={"decode_coords": False}) as expected: # check roundtripping when decode_coords=False with self.roundtrip( expected, open_kwargs={"decode_coords": False} ) as actual: assert_identical(expected, actual) def test_roundtrip_global_coordinates(self) -> None: original = Dataset( {"foo": ("x", [0, 1])}, {"x": [2, 3], "y": ("a", [42]), "z": ("x", [4, 5])} ) with self.roundtrip(original) as actual: assert_identical(original, actual) # test that global "coordinates" is as expected _, attrs = encode_dataset_coordinates(original) assert attrs["coordinates"] == "y" # test warning when global "coordinates" is already set original.attrs["coordinates"] = "foo" with pytest.warns(SerializationWarning): _, attrs = encode_dataset_coordinates(original) assert attrs["coordinates"] == "foo" def test_roundtrip_coordinates_with_space(self) -> None: original = Dataset(coords={"x": 0, "y z": 1}) expected = Dataset({"y z": 1}, {"x": 0}) with pytest.warns(SerializationWarning): with self.roundtrip(original) as actual: assert_identical(expected, actual) def test_roundtrip_boolean_dtype(self) -> None: original = create_boolean_data() assert original["x"].dtype == "bool" with self.roundtrip(original) as actual: assert_identical(original, actual) assert actual["x"].dtype == "bool" # this checks for preserving dtype during second roundtrip # see https://github.com/pydata/xarray/issues/7652#issuecomment-1476956975 with self.roundtrip(actual) as actual2: assert_identical(original, actual2) assert actual2["x"].dtype == "bool" with self.roundtrip(actual) as actual3: # GH10536 assert_identical(original.transpose(), actual3.transpose()) def test_orthogonal_indexing(self) -> None: in_memory = create_test_data() with self.roundtrip(in_memory) as on_disk: indexers = {"dim1": [1, 2, 0], "dim2": [3, 2, 0, 3], "dim3": np.arange(5)} expected = in_memory.isel(indexers) actual = on_disk.isel(**indexers) # make sure the array is not yet loaded into memory assert not actual["var1"].variable._in_memory assert_identical(expected, actual) # do it twice, to make sure we're switched from orthogonal -> numpy # when we cached the values actual = on_disk.isel(**indexers) assert_identical(expected, actual) def test_vectorized_indexing(self) -> None: in_memory = create_test_data() with self.roundtrip(in_memory) as on_disk: indexers = { "dim1": DataArray([0, 2, 0], dims="a"), "dim2": DataArray([0, 2, 3], dims="a"), } expected = in_memory.isel(indexers) actual = on_disk.isel(**indexers) # make sure the array is not yet loaded into memory assert not actual["var1"].variable._in_memory assert_identical(expected, actual.load()) # do it twice, to make sure we're switched from # vectorized -> numpy when we cached the values actual = on_disk.isel(**indexers) assert_identical(expected, actual) def multiple_indexing(indexers): # make sure a sequence of lazy indexings certainly works. with self.roundtrip(in_memory) as on_disk: actual = on_disk["var3"] expected = in_memory["var3"] for ind in indexers: actual = actual.isel(ind) expected = expected.isel(ind) # make sure the array is not yet loaded into memory assert not actual.variable._in_memory assert_identical(expected, actual.load()) # two-staged vectorized-indexing indexers2 = [ { "dim1": DataArray([[0, 7], [2, 6], [3, 5]], dims=["a", "b"]), "dim3": DataArray([[0, 4], [1, 3], [2, 2]], dims=["a", "b"]), }, {"a": DataArray([0, 1], dims=["c"]), "b": DataArray([0, 1], dims=["c"])}, ] multiple_indexing(indexers2) # vectorized-slice mixed indexers3 = [ { "dim1": DataArray([[0, 7], [2, 6], [3, 5]], dims=["a", "b"]), "dim3": slice(None, 10), } ] multiple_indexing(indexers3) # vectorized-integer mixed indexers4 = [ {"dim3": 0}, {"dim1": DataArray([[0, 7], [2, 6], [3, 5]], dims=["a", "b"])}, {"a": slice(None, None, 2)}, ] multiple_indexing(indexers4) # vectorized-integer mixed indexers5 = [ {"dim3": 0}, {"dim1": DataArray([[0, 7], [2, 6], [3, 5]], dims=["a", "b"])}, {"a": 1, "b": 0}, ] multiple_indexing(indexers5) def test_vectorized_indexing_negative_step(self) -> None: # use dask explicitly when present open_kwargs: dict[str, Any] | None if has_dask: open_kwargs = {"chunks": {}} else: open_kwargs = None in_memory = create_test_data() def multiple_indexing(indexers): # make sure a sequence of lazy indexings certainly works. with self.roundtrip(in_memory, open_kwargs=open_kwargs) as on_disk: actual = on_disk["var3"] expected = in_memory["var3"] for ind in indexers: actual = actual.isel(ind) expected = expected.isel(ind) # make sure the array is not yet loaded into memory assert not actual.variable._in_memory assert_identical(expected, actual.load()) # with negative step slice. indexers = [ { "dim1": DataArray([[0, 7], [2, 6], [3, 5]], dims=["a", "b"]), "dim3": slice(-1, 1, -1), } ] multiple_indexing(indexers) # with negative step slice. indexers = [ { "dim1": DataArray([[0, 7], [2, 6], [3, 5]], dims=["a", "b"]), "dim3": slice(-1, 1, -2), } ] multiple_indexing(indexers) def test_outer_indexing_reversed(self) -> None: # regression test for GH6560 ds = xr.Dataset( {"z": (("t", "p", "y", "x"), np.ones((1, 1, 31, 40)))}, ) with self.roundtrip(ds) as on_disk: subset = on_disk.isel(t=[0], p=0).z[:, ::10, ::10][:, ::-1, :] assert subset.sizes == subset.load().sizes def test_isel_dataarray(self) -> None: # Make sure isel works lazily. GH:issue:1688 in_memory = create_test_data() with self.roundtrip(in_memory) as on_disk: expected = in_memory.isel(dim2=in_memory["dim2"] < 3) actual = on_disk.isel(dim2=on_disk["dim2"] < 3) assert_identical(expected, actual) def test_empty_isel(self) -> None: # Make sure isel works lazily with empty indexer. # GH:issue:10867 in_memory = xr.Dataset({"a": ("x", np.arange(4))}, coords={"x": np.arange(4)}) with self.roundtrip(in_memory) as on_disk: expected = in_memory.isel(x=[]) actual = on_disk.isel(x=[]) assert_identical(expected, actual) def validate_array_type(self, ds): # Make sure that only NumpyIndexingAdapter stores a bare np.ndarray. def find_and_validate_array(obj): # recursively called function. obj: array or array wrapper. if hasattr(obj, "array"): if isinstance(obj.array, indexing.ExplicitlyIndexed): find_and_validate_array(obj.array) elif isinstance(obj.array, np.ndarray): assert isinstance(obj, indexing.NumpyIndexingAdapter) elif isinstance(obj.array, dask_array_type): assert isinstance(obj, indexing.DaskIndexingAdapter) elif isinstance(obj.array, pd.Index): assert isinstance(obj, indexing.PandasIndexingAdapter) else: raise TypeError(f"{type(obj.array)} is wrapped by {type(obj)}") for v in ds.variables.values(): find_and_validate_array(v._data) def test_array_type_after_indexing(self) -> None: in_memory = create_test_data() with self.roundtrip(in_memory) as on_disk: self.validate_array_type(on_disk) indexers = {"dim1": [1, 2, 0], "dim2": [3, 2, 0, 3], "dim3": np.arange(5)} expected = in_memory.isel(indexers) actual = on_disk.isel(**indexers) assert_identical(expected, actual) self.validate_array_type(actual) # do it twice, to make sure we're switched from orthogonal -> numpy # when we cached the values actual = on_disk.isel(**indexers) assert_identical(expected, actual) self.validate_array_type(actual) def test_dropna(self) -> None: # regression test for GH:issue:1694 a = np.random.randn(4, 3) a[1, 1] = np.nan in_memory = xr.Dataset( {"a": (("y", "x"), a)}, coords={"y": np.arange(4), "x": np.arange(3)} ) assert_identical( in_memory.dropna(dim="x"), in_memory.isel(x=slice(None, None, 2)) ) with self.roundtrip(in_memory) as on_disk: self.validate_array_type(on_disk) expected = in_memory.dropna(dim="x") actual = on_disk.dropna(dim="x") assert_identical(expected, actual) def test_ondisk_after_print(self) -> None: """Make sure print does not load file into memory""" in_memory = create_test_data() with self.roundtrip(in_memory) as on_disk: repr(on_disk) assert not on_disk["var1"]._in_memory
DatasetIOBase
python
huggingface__transformers
src/transformers/models/granite/modeling_granite.py
{ "start": 17399, "end": 22050 }
class ____(GranitePreTrainedModel): def __init__(self, config: GraniteConfig): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.layers = nn.ModuleList( [GraniteDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.norm = GraniteRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.rotary_emb = GraniteRotaryEmbedding(config=config) self.gradient_checkpointing = False self.embedding_multiplier = config.embedding_multiplier # Initialize weights and apply final processing self.post_init() @check_model_inputs() @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> BaseModelOutputWithPast: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if self.gradient_checkpointing and self.training and use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`." ) use_cache = False if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) inputs_embeds = inputs_embeds * self.embedding_multiplier # main diff with Llama if use_cache and past_key_values is None: past_key_values = DynamicCache(config=self.config) if cache_position is None: past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 cache_position = torch.arange( past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device ) if position_ids is None: position_ids = cache_position.unsqueeze(0) causal_mask = create_causal_mask( config=self.config, input_embeds=inputs_embeds, attention_mask=attention_mask, cache_position=cache_position, past_key_values=past_key_values, position_ids=position_ids, ) hidden_states = inputs_embeds position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids) # decoder layers all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None for decoder_layer in self.layers[: self.config.num_hidden_layers]: if output_hidden_states: all_hidden_states += (hidden_states,) layer_outputs = decoder_layer( hidden_states, attention_mask=causal_mask, position_ids=position_ids, past_key_values=past_key_values, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, ) hidden_states = layer_outputs[0] if output_attentions: all_self_attns += (layer_outputs[1],) hidden_states = self.norm(hidden_states) # add hidden states from the last decoder layer if output_hidden_states: all_hidden_states += (hidden_states,) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=past_key_values if use_cache else None, hidden_states=all_hidden_states, attentions=all_self_attns, ) @auto_docstring
GraniteModel
python
doocs__leetcode
solution/2400-2499/2479.Maximum XOR of Two Non-Overlapping Subtrees/Solution.py
{ "start": 0, "end": 705 }
class ____: def __init__(self): self.children = [None] * 2 def insert(self, x): node = self for i in range(47, -1, -1): v = (x >> i) & 1 if node.children[v] is None: node.children[v] = Trie() node = node.children[v] def search(self, x): node = self res = 0 for i in range(47, -1, -1): v = (x >> i) & 1 if node is None: return res if node.children[v ^ 1]: res = res << 1 | 1 node = node.children[v ^ 1] else: res <<= 1 node = node.children[v] return res
Trie
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/super7.py
{ "start": 1886, "end": 2393 }
class ____(A[int], B[T]): pass c = C[str]() super_obj_c = super(C, c) reveal_type(super_obj_c, expected_text="A[int]") super_obj_a = super(A, c) reveal_type(super_obj_a, expected_text="B[str]") super_obj_b = super(B, c) reveal_type(super_obj_b, expected_text="object") super_cls_c = super(C, C) reveal_type(super_cls_c, expected_text="A[int]") super_cls_a = super(A, C) reveal_type(super_cls_a, expected_text="B[Unknown]") super_cls_b = super(B, C) reveal_type(super_cls_b, expected_text="object")
C
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_batch.py
{ "start": 1705, "end": 24313 }
class ____: MAX_RETRIES = 2 STATUS_RETRIES = 3 @mock.patch.dict("os.environ", AWS_DEFAULT_REGION=AWS_REGION) @mock.patch.dict("os.environ", AWS_ACCESS_KEY_ID=AWS_ACCESS_KEY_ID) @mock.patch.dict("os.environ", AWS_SECRET_ACCESS_KEY=AWS_SECRET_ACCESS_KEY) @mock.patch("airflow.providers.amazon.aws.hooks.batch_client.AwsBaseHook.get_client_type") def setup_method(self, _, get_client_type_mock): self.get_client_type_mock = get_client_type_mock self.batch = BatchOperator( task_id="task", job_name=JOB_NAME, job_queue="queue", job_definition="hello-world", max_retries=self.MAX_RETRIES, status_retries=self.STATUS_RETRIES, parameters=None, retry_strategy={"attempts": 1}, container_overrides={}, array_properties=None, aws_conn_id="airflow_test", region_name="eu-west-1", tags={}, submit_job_timeout=3600, ) self.client_mock = self.get_client_type_mock.return_value # We're mocking all actual AWS calls and don't need a connection. This # avoids an Airflow warning about connection cannot be found. self.batch.hook.get_connection = lambda _: None assert self.batch.hook.client == self.client_mock # setup client property # don't pause in unit tests self.mock_delay = mock.Mock(return_value=None) self.batch.delay = self.mock_delay self.mock_exponential_delay = mock.Mock(return_value=0) self.batch.exponential_delay = self.mock_exponential_delay # Assign a job ID for most tests, so they don't depend on a job submission. assert self.batch.job_id is None self.batch.job_id = JOB_ID self.mock_context = mock.MagicMock() def test_init(self): assert self.batch.job_id == JOB_ID assert self.batch.job_name == JOB_NAME assert self.batch.job_queue == "queue" assert self.batch.job_definition == "hello-world" assert self.batch.waiters is None assert self.batch.hook.max_retries == self.MAX_RETRIES assert self.batch.hook.status_retries == self.STATUS_RETRIES assert self.batch.parameters == {} assert self.batch.retry_strategy == {"attempts": 1} assert self.batch.container_overrides == {} assert self.batch.array_properties is None assert self.batch.node_overrides is None assert self.batch.share_identifier is None assert self.batch.scheduling_priority_override is None assert self.batch.hook.region_name == "eu-west-1" assert self.batch.hook.aws_conn_id == "airflow_test" assert self.batch.hook.client == self.client_mock assert self.batch.tags == {} assert self.batch.wait_for_completion is True assert self.batch.submit_job_timeout == 3600 self.get_client_type_mock.assert_called_once_with(region_name="eu-west-1") def test_init_defaults(self): """Test constructor default values""" batch_job = BatchOperator( task_id="task", job_name=JOB_NAME, job_queue="queue", job_definition="hello-world", ) assert batch_job.job_id is None assert batch_job.job_name == JOB_NAME assert batch_job.job_queue == "queue" assert batch_job.job_definition == "hello-world" assert batch_job.waiters is None assert batch_job.hook.max_retries == 4200 assert batch_job.hook.status_retries == 10 assert batch_job.parameters == {} assert batch_job.retry_strategy is None assert batch_job.container_overrides is None assert batch_job.array_properties is None assert batch_job.ecs_properties_override is None assert batch_job.eks_properties_override is None assert batch_job.node_overrides is None assert batch_job.share_identifier is None assert batch_job.scheduling_priority_override is None assert batch_job.hook.region_name is None assert issubclass(type(batch_job.hook.client), botocore.client.BaseClient) assert batch_job.tags == {} assert batch_job.wait_for_completion is True assert batch_job.submit_job_timeout is None def test_template_fields_overrides(self): validate_template_fields(self.batch) @mock.patch.object(BatchClientHook, "get_job_description") @mock.patch.object(BatchClientHook, "wait_for_job") @mock.patch.object(BatchClientHook, "check_job_success") def test_execute_without_failures(self, check_mock, wait_mock, job_description_mock): # JOB_ID is in RESPONSE_WITHOUT_FAILURES self.client_mock.submit_job.return_value = RESPONSE_WITHOUT_FAILURES self.batch.job_id = None self.batch.waiters = None # use default wait self.batch.execute(self.mock_context) self.client_mock.submit_job.assert_called_once_with( jobQueue="queue", jobName=JOB_NAME, containerOverrides={}, jobDefinition="hello-world", parameters={}, retryStrategy={"attempts": 1}, tags={}, timeout={"attemptDurationSeconds": 3600}, ) assert self.batch.job_id == JOB_ID wait_mock.assert_called_once_with(JOB_ID) check_mock.assert_called_once_with(JOB_ID) # First Call: Retrieve Batch Queue and Job Definition # Second Call: Retrieve CloudWatch information assert job_description_mock.call_count == 2 def test_execute_with_failures(self): self.client_mock.submit_job.side_effect = Exception() with pytest.raises(AirflowException): self.batch.execute(self.mock_context) self.client_mock.submit_job.assert_called_once_with( jobQueue="queue", jobName=JOB_NAME, containerOverrides={}, jobDefinition="hello-world", parameters={}, retryStrategy={"attempts": 1}, tags={}, timeout={"attemptDurationSeconds": 3600}, ) @mock.patch.object(BatchClientHook, "get_job_description") @mock.patch.object(BatchClientHook, "wait_for_job") @mock.patch.object(BatchClientHook, "check_job_success") def test_execute_with_ecs_overrides(self, check_mock, wait_mock, job_description_mock): self.batch.container_overrides = None self.batch.ecs_properties_override = { "taskProperties": [ { "containers": [ { "command": [ "string", ], "environment": [ {"name": "string", "value": "string"}, ], "name": "string", "resourceRequirements": [ {"value": "string", "type": "'GPU'|'VCPU'|'MEMORY'"}, ], }, ] }, ] } self.batch.execute(self.mock_context) self.client_mock.submit_job.assert_called_once_with( jobQueue="queue", jobName=JOB_NAME, jobDefinition="hello-world", ecsPropertiesOverride={ "taskProperties": [ { "containers": [ { "command": [ "string", ], "environment": [ {"name": "string", "value": "string"}, ], "name": "string", "resourceRequirements": [ {"value": "string", "type": "'GPU'|'VCPU'|'MEMORY'"}, ], }, ] }, ] }, parameters={}, retryStrategy={"attempts": 1}, tags={}, timeout={"attemptDurationSeconds": 3600}, ) @mock.patch.object(BatchClientHook, "get_job_description") @mock.patch.object(BatchClientHook, "wait_for_job") @mock.patch.object(BatchClientHook, "check_job_success") def test_execute_with_eks_overrides(self, check_mock, wait_mock, job_description_mock): self.batch.container_overrides = None self.batch.eks_properties_override = { "podProperties": [ { "containers": [ { "image": "string", "command": [ "string", ], "args": [ "string", ], "env": [ {"name": "string", "value": "string"}, ], "resources": [{"limits": {"string": "string"}, "requests": {"string": "string"}}], }, ], "initContainers": [ { "image": "string", "command": [ "string", ], "args": [ "string", ], "env": [ {"name": "string", "value": "string"}, ], "resources": [{"limits": {"string": "string"}, "requests": {"string": "string"}}], }, ], "metadata": { "labels": {"string": "string"}, }, }, ] } self.batch.execute(self.mock_context) self.client_mock.submit_job.assert_called_once_with( jobQueue="queue", jobName=JOB_NAME, jobDefinition="hello-world", eksPropertiesOverride={ "podProperties": [ { "containers": [ { "image": "string", "command": [ "string", ], "args": [ "string", ], "env": [ {"name": "string", "value": "string"}, ], "resources": [ {"limits": {"string": "string"}, "requests": {"string": "string"}} ], }, ], "initContainers": [ { "image": "string", "command": [ "string", ], "args": [ "string", ], "env": [ {"name": "string", "value": "string"}, ], "resources": [ {"limits": {"string": "string"}, "requests": {"string": "string"}} ], }, ], "metadata": { "labels": {"string": "string"}, }, }, ] }, parameters={}, retryStrategy={"attempts": 1}, tags={}, timeout={"attemptDurationSeconds": 3600}, ) @mock.patch.object(BatchClientHook, "check_job_success") def test_wait_job_complete_using_waiters(self, check_mock): mock_waiters = mock.Mock() self.batch.waiters = mock_waiters self.client_mock.submit_job.return_value = RESPONSE_WITHOUT_FAILURES self.client_mock.describe_jobs.return_value = { "jobs": [ { "jobId": JOB_ID, "status": "SUCCEEDED", "logStreamName": "logStreamName", "container": {"logConfiguration": {}}, } ] } self.batch.execute(self.mock_context) mock_waiters.wait_for_job.assert_called_once_with(JOB_ID) check_mock.assert_called_once_with(JOB_ID) @mock.patch.object(BatchClientHook, "check_job_success") def test_do_not_wait_job_complete(self, check_mock): self.batch.wait_for_completion = False self.client_mock.submit_job.return_value = RESPONSE_WITHOUT_FAILURES self.batch.execute(self.mock_context) check_mock.assert_not_called() def test_kill_job(self): self.client_mock.terminate_job.return_value = {} self.batch.on_kill() self.client_mock.terminate_job.assert_called_once_with(jobId=JOB_ID, reason="Task killed by the user") @pytest.mark.parametrize( "override", ["node_overrides", "ecs_properties_override", "eks_properties_override"] ) @patch( "airflow.providers.amazon.aws.hooks.batch_client.BatchClientHook.client", new_callable=mock.PropertyMock, ) def test_override_not_sent_if_not_set(self, client_mock, override): """ check that when setting container override or node override, the other key is not sent in the API call (which would create a validation error from boto) """ override_arg = {override: {"a": "a"}} batch = BatchOperator( task_id="task", job_name=JOB_NAME, job_queue="queue", job_definition="hello-world", **override_arg, # setting those to bypass code that is not relevant here do_xcom_push=False, wait_for_completion=False, ) batch.execute(None) expected_args = { "jobQueue": "queue", "jobName": JOB_NAME, "jobDefinition": "hello-world", "parameters": {}, "tags": {}, } py2api = { "overrides": "containerOverrides", "node_overrides": "nodeOverrides", "ecs_properties_override": "ecsPropertiesOverride", "eks_properties_override": "eksPropertiesOverride", } expected_args[py2api[override]] = {"a": "a"} client_mock().submit_job.assert_called_once_with(**expected_args) def test_cant_set_old_and_new_override_param(self): with pytest.raises((TypeError, AirflowException), match="Invalid arguments were passed"): _ = BatchOperator( task_id="task", job_name=JOB_NAME, job_queue="queue", job_definition="hello-world", # can't set both of those, as one is a replacement for the other overrides={"a": "b"}, container_overrides={"a": "b"}, ) @mock.patch.object(BatchClientHook, "get_job_description") @mock.patch("airflow.providers.amazon.aws.hooks.batch_client.AwsBaseHook.get_client_type") def test_defer_if_deferrable_param_set(self, mock_client, mock_get_job_description): mock_get_job_description.return_value = {"status": "SUBMITTED"} batch = BatchOperator( task_id="task", job_name=JOB_NAME, job_queue="queue", job_definition="hello-world", do_xcom_push=False, deferrable=True, ) with pytest.raises(TaskDeferred) as exc: batch.execute(self.mock_context) assert isinstance(exc.value.trigger, BatchJobTrigger) @mock.patch("airflow.providers.amazon.aws.hooks.batch_client.AwsBaseHook.get_client_type") def test_defer_but_failed_due_to_job_id_not_found(self, mock_client): """Test that an AirflowException is raised if job_id is not set before deferral.""" mock_client.return_value.submit_job.return_value = { "jobName": JOB_NAME, "jobId": None, } batch = BatchOperator( task_id="task", job_name=JOB_NAME, job_queue="queue", job_definition="hello-world", do_xcom_push=False, deferrable=True, ) with pytest.raises(AirflowException) as exc: batch.execute(self.mock_context) assert "AWS Batch job - job_id was not found" in str(exc.value) @mock.patch.object(BatchClientHook, "get_job_description") @mock.patch("airflow.providers.amazon.aws.hooks.batch_client.AwsBaseHook.get_client_type") def test_defer_but_success_before_deferred(self, mock_client, mock_get_job_description): """Test that an AirflowException is raised if job_id is not set before deferral.""" mock_client.return_value.submit_job.return_value = RESPONSE_WITHOUT_FAILURES mock_get_job_description.return_value = {"status": "SUCCEEDED"} batch = BatchOperator( task_id="task", job_name=JOB_NAME, job_queue="queue", job_definition="hello-world", do_xcom_push=False, deferrable=True, ) assert batch.execute(self.mock_context) == JOB_ID @mock.patch.object(BatchClientHook, "get_job_description") @mock.patch("airflow.providers.amazon.aws.hooks.batch_client.AwsBaseHook.get_client_type") def test_defer_but_fail_before_deferred(self, mock_client, mock_get_job_description): """Test that an AirflowException is raised if job_id is not set before deferral.""" mock_client.return_value.submit_job.return_value = RESPONSE_WITHOUT_FAILURES mock_get_job_description.return_value = {"status": "FAILED"} batch = BatchOperator( task_id="task", job_name=JOB_NAME, job_queue="queue", job_definition="hello-world", do_xcom_push=False, deferrable=True, ) with pytest.raises(AirflowException) as exc: batch.execute(self.mock_context) assert f"Error while running job: {JOB_ID} is in FAILED state" in str(exc.value) @mock.patch.object(BatchClientHook, "get_job_description") @mock.patch.object(BatchClientHook, "wait_for_job") @mock.patch.object(BatchClientHook, "check_job_success") @mock.patch("airflow.providers.amazon.aws.links.batch.BatchJobQueueLink.persist") @mock.patch("airflow.providers.amazon.aws.links.batch.BatchJobDefinitionLink.persist") def test_monitor_job_with_logs( self, job_definition_persist_mock, job_queue_persist_mock, check_mock, wait_mock, job_description_mock ): batch = BatchOperator( task_id="task", job_name=JOB_NAME, job_queue="queue", job_definition="hello-world", awslogs_enabled=True, ) batch.job_id = JOB_ID batch.monitor_job(context=None) job_description_mock.assert_called_with(job_id=JOB_ID) job_definition_persist_mock.assert_called_once() job_queue_persist_mock.assert_called_once() wait_mock.assert_called_once() assert len(wait_mock.call_args) == 2 @patch.object(BatchOperator, "log", new_callable=MagicMock) @patch("airflow.providers.amazon.aws.operators.batch.validate_execute_complete_event") @patch.object(BatchOperator, "monitor_job") def test_execute_complete_success_with_logs(self, mock_monitor_job, mock_validate, mock_log): # Setup mock_validate.return_value = {"status": "success", "job_id": "12345"} batch = BatchOperator( task_id="test_task", job_name=JOB_NAME, job_queue="dummy_queue", job_definition="dummy_definition", deferrable=True, awslogs_enabled=True, ) result = batch.execute_complete(context={}, event={"dummy": "event"}) # Assertion assert result == "12345" mock_monitor_job.assert_called_once_with({}) mock_log.info.assert_called_with("Job completed successfully for job_id: %s", "12345") @patch.object(BatchOperator, "log", new_callable=MagicMock) @patch("airflow.providers.amazon.aws.operators.batch.validate_execute_complete_event") @patch.object(BatchOperator, "monitor_job") def test_execute_complete_success_without_logs(self, mock_monitor_job, mock_validate, mock_log): # Setup mock_validate.return_value = {"status": "success", "job_id": "12345"} batch = BatchOperator( task_id="test_task", job_name=JOB_NAME, job_queue="dummy_queue", job_definition="dummy_definition", deferrable=True, awslogs_enabled=False, ) result = batch.execute_complete(context={}, event={"dummy": "event"}) # Assertions assert result == "12345" mock_monitor_job.assert_not_called() mock_log.info.assert_called_with("Job completed successfully for job_id: %s", "12345") @patch("airflow.providers.amazon.aws.operators.batch.validate_execute_complete_event") def test_execute_complete_failure(self, mock_validate): # Setup mock_validate.return_value = {"status": "failed", "job_id": "12345"} batch = BatchOperator( task_id="test_task", job_name=JOB_NAME, job_queue="dummy_queue", job_definition="dummy_definition", deferrable=True, awslogs_enabled=True, ) # Assertions with pytest.raises(AirflowException, match="Error while running job"): batch.execute_complete(context={}, event={"dummy": "event"})
TestBatchOperator
python
keras-team__keras
keras/src/ops/nn.py
{ "start": 6323, "end": 7178 }
class ____(Operation): def call(self, x): return backend.nn.sparse_plus(x) def compute_output_spec(self, x): return KerasTensor(x.shape, dtype=x.dtype) @keras_export(["keras.ops.sparse_plus", "keras.ops.nn.sparse_plus"]) def sparse_plus(x): """SparsePlus activation function. It is defined as `f(x) = 0` for `x <= -1`. `f(x) = (1/4) * (x + 1)^2` for `-1 < x < 1`. `f(x) = x` for `x >= 1`. Args: x: Input tensor. Returns: A tensor with the same shape as `x`. Example: >>> x = np.array([-1.0, 0.0, 1.0]) >>> x_sparse_plus = keras.ops.sparse_plus(x) >>> print(x_sparse_plus) Array([0. 0.25 1. ], shape=(3,), dtype=float32) """ if any_symbolic_tensors((x,)): return SparsePlus().symbolic_call(x) return backend.nn.sparse_plus(x)
SparsePlus
python
Netflix__metaflow
test/unit/inheritance/flows/comprehensive_multi_hierarchy_base.py
{ "start": 2355, "end": 2898 }
class ____(BaseX): """Second hierarchy extension with parameter and config""" param_y = Parameter("param_y", help="Parameter Y", default=40) config_y = Config("config_y", default_value={"enabled": True, "threshold": 50}) @step def process(self): """Process step that can be overridden""" print("BaseY.process - default implementation") multiplier = self.config_x.get("multiplier", 1) self.processed_value = self.hierarchy_a_result * multiplier self.next(self.end) # Merge point
BaseY
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/instigation.py
{ "start": 19155, "end": 20829 }
class ____(graphene.ObjectType): runKey = graphene.String() tags = non_null_list(GraphenePipelineTag) runConfigYaml = graphene.NonNull(graphene.String) assetSelection = graphene.List(graphene.NonNull(GrapheneAssetKey)) assetChecks = graphene.List(graphene.NonNull(GrapheneAssetCheckHandle)) jobName = graphene.String() _run_request: RunRequest class Meta: name = "RunRequest" def __init__(self, run_request): super().__init__(runKey=run_request.run_key) self._run_request = check.inst_param(run_request, "run_request", RunRequest) def resolve_tags(self, _graphene_info: ResolveInfo): return [ GraphenePipelineTag(key=key, value=value) for key, value in self._run_request.tags.items() if get_tag_type(key) != TagType.HIDDEN ] def resolve_runConfigYaml(self, _graphene_info: ResolveInfo): return dump_run_config_yaml(self._run_request.run_config) def resolve_assetSelection(self, _graphene_info: ResolveInfo): if self._run_request.asset_selection: return [ GrapheneAssetKey(path=asset_key.path) for asset_key in self._run_request.asset_selection ] return None def resolve_jobName(self, _graphene_info: ResolveInfo): return self._run_request.job_name def resolve_assetChecks(self, _graphene_info: ResolveInfo): if self._run_request.asset_check_keys: return [ GrapheneAssetCheckHandle(check_key) for check_key in self._run_request.asset_check_keys ] return None
GrapheneRunRequest
python
sqlalchemy__sqlalchemy
test/dialect/sqlite/test_compiler.py
{ "start": 9868, "end": 14636 }
class ____(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = sqlite.dialect() def test_on_conflict_clause_column_not_null(self): c = Column( "test", Integer, nullable=False, sqlite_on_conflict_not_null="FAIL" ) self.assert_compile( schema.CreateColumn(c), "test INTEGER NOT NULL ON CONFLICT FAIL", dialect=sqlite.dialect(), ) def test_on_conflict_clause_column_many_clause(self): meta = MetaData() t = Table( "n", meta, Column( "test", Integer, nullable=False, primary_key=True, sqlite_on_conflict_not_null="FAIL", sqlite_on_conflict_primary_key="IGNORE", ), ) self.assert_compile( CreateTable(t), "CREATE TABLE n (" "test INTEGER NOT NULL ON CONFLICT FAIL, " "PRIMARY KEY (test) ON CONFLICT IGNORE)", dialect=sqlite.dialect(), ) def test_on_conflict_clause_unique_constraint_from_column(self): meta = MetaData() t = Table( "n", meta, Column( "x", String(30), unique=True, sqlite_on_conflict_unique="FAIL" ), ) self.assert_compile( CreateTable(t), "CREATE TABLE n (x VARCHAR(30), UNIQUE (x) ON CONFLICT FAIL)", dialect=sqlite.dialect(), ) def test_on_conflict_clause_unique_constraint(self): meta = MetaData() t = Table( "n", meta, Column("id", Integer), Column("x", String(30)), UniqueConstraint("id", "x", sqlite_on_conflict="FAIL"), ) self.assert_compile( CreateTable(t), "CREATE TABLE n (id INTEGER, x VARCHAR(30), " "UNIQUE (id, x) ON CONFLICT FAIL)", dialect=sqlite.dialect(), ) def test_on_conflict_clause_primary_key(self): meta = MetaData() t = Table( "n", meta, Column( "id", Integer, primary_key=True, sqlite_on_conflict_primary_key="FAIL", ), sqlite_autoincrement=True, ) self.assert_compile( CreateTable(t), "CREATE TABLE n (id INTEGER NOT NULL " "PRIMARY KEY ON CONFLICT FAIL AUTOINCREMENT)", dialect=sqlite.dialect(), ) def test_on_conflict_clause_primary_key_constraint_from_column(self): meta = MetaData() t = Table( "n", meta, Column( "x", String(30), sqlite_on_conflict_primary_key="FAIL", primary_key=True, ), ) self.assert_compile( CreateTable(t), "CREATE TABLE n (x VARCHAR(30) NOT NULL, " "PRIMARY KEY (x) ON CONFLICT FAIL)", dialect=sqlite.dialect(), ) def test_on_conflict_clause_check_constraint(self): meta = MetaData() t = Table( "n", meta, Column("id", Integer), Column("x", Integer), CheckConstraint("id > x", sqlite_on_conflict="FAIL"), ) self.assert_compile( CreateTable(t), "CREATE TABLE n (id INTEGER, x INTEGER, " "CHECK (id > x) ON CONFLICT FAIL)", dialect=sqlite.dialect(), ) def test_on_conflict_clause_check_constraint_from_column(self): meta = MetaData() t = Table( "n", meta, Column( "x", Integer, CheckConstraint("x > 1", sqlite_on_conflict="FAIL"), ), ) assert_raises_message( exc.CompileError, "SQLite does not support on conflict " "clause for column check constraint", CreateTable(t).compile, dialect=sqlite.dialect(), ) def test_on_conflict_clause_primary_key_constraint(self): meta = MetaData() t = Table( "n", meta, Column("id", Integer), Column("x", String(30)), PrimaryKeyConstraint("id", "x", sqlite_on_conflict="FAIL"), ) self.assert_compile( CreateTable(t), "CREATE TABLE n (" "id INTEGER NOT NULL, " "x VARCHAR(30) NOT NULL, " "PRIMARY KEY (id, x) ON CONFLICT FAIL)", dialect=sqlite.dialect(), )
OnConflictDDLTest
python
scikit-learn__scikit-learn
sklearn/externals/array_api_extra/_lib/_at.py
{ "start": 1143, "end": 1243 }
class ____(Enum): """Sentinel for undefined values.""" UNDEF = 0 _undef = Undef.UNDEF
Undef
python
numba__numba
numba/tests/npyufunc/test_ufuncbuilding.py
{ "start": 4923, "end": 5164 }
class ____(TestGUfuncBuilding): def setUp(self): self.old_disable_jit = config.DISABLE_JIT config.DISABLE_JIT = False def tearDown(self): config.DISABLE_JIT = self.old_disable_jit
TestGUfuncBuildingJitDisabled
python
sympy__sympy
sympy/printing/rust.py
{ "start": 8055, "end": 20919 }
class ____(CodePrinter): """A printer to convert SymPy expressions to strings of Rust code""" printmethod = "_rust_code" language = "Rust" type_aliases = { integer: int32, real: float64, } type_mappings = { int32: 'i32', float32: 'f32', float64: 'f64', bool_: 'bool' } _default_settings: dict[str, Any] = dict(CodePrinter._default_settings, **{ 'precision': 17, 'user_functions': {}, 'contract': True, 'dereference': set(), }) def __init__(self, settings={}): CodePrinter.__init__(self, settings) self.known_functions = dict(known_functions) userfuncs = settings.get('user_functions', {}) self.known_functions.update(userfuncs) self._dereference = set(settings.get('dereference', [])) self.reserved_words = set(reserved_words) self.function_overrides = function_overrides def _rate_index_position(self, p): return p*5 def _get_statement(self, codestring): return "%s;" % codestring def _get_comment(self, text): return "// %s" % text def _declare_number_const(self, name, value): type_ = self.type_mappings[self.type_aliases[real]] return "const %s: %s = %s;" % (name, type_, value) def _format_code(self, lines): return self.indent_code(lines) def _traverse_matrix_indices(self, mat): rows, cols = mat.shape return ((i, j) for i in range(rows) for j in range(cols)) def _get_loop_opening_ending(self, indices): open_lines = [] close_lines = [] loopstart = "for %(var)s in %(start)s..%(end)s {" for i in indices: # Rust arrays start at 0 and end at dimension-1 open_lines.append(loopstart % { 'var': self._print(i), 'start': self._print(i.lower), 'end': self._print(i.upper + 1)}) close_lines.append("}") return open_lines, close_lines def _print_caller_var(self, expr): if len(expr.args) > 1: # for something like `sin(x + y + z)`, # make sure we can get '(x + y + z).sin()' # instead of 'x + y + z.sin()' return '(' + self._print(expr) + ')' elif expr.is_number: return self._print(expr, _type=True) else: return self._print(expr) def _print_Function(self, expr): """ basic function for printing `Function` Function Style : 1. args[0].func(args[1:]), method with arguments 2. args[0].func(), method without arguments 3. args[1].func(), method without arguments (e.g. (e, x) => x.exp()) 4. func(args), function with arguments """ if expr.func.__name__ in self.known_functions: cond_func = self.known_functions[expr.func.__name__] func = None style = 1 if isinstance(cond_func, str): func = cond_func else: for cond, func, style in cond_func: if cond(*expr.args): break if func is not None: if style == 1: ret = "%(var)s.%(method)s(%(args)s)" % { 'var': self._print_caller_var(expr.args[0]), 'method': func, 'args': self.stringify(expr.args[1:], ", ") if len(expr.args) > 1 else '' } elif style == 2: ret = "%(var)s.%(method)s()" % { 'var': self._print_caller_var(expr.args[0]), 'method': func, } elif style == 3: ret = "%(var)s.%(method)s()" % { 'var': self._print_caller_var(expr.args[1]), 'method': func, } else: ret = "%(func)s(%(args)s)" % { 'func': func, 'args': self.stringify(expr.args, ", "), } return ret elif hasattr(expr, '_imp_') and isinstance(expr._imp_, Lambda): # inlined function return self._print(expr._imp_(*expr.args)) else: return self._print_not_supported(expr) def _print_Mul(self, expr): contains_floats = any(arg.is_real and not arg.is_integer for arg in expr.args) if contains_floats: expr = reduce(operator.mul,(self._cast_to_float(arg) if arg != -1 else arg for arg in expr.args)) return super()._print_Mul(expr) def _print_Add(self, expr, order=None): contains_floats = any(arg.is_real and not arg.is_integer for arg in expr.args) if contains_floats: expr = reduce(operator.add, (self._cast_to_float(arg) for arg in expr.args)) return super()._print_Add(expr, order) def _print_Pow(self, expr): if expr.base.is_integer and not expr.exp.is_integer: expr = type(expr)(Float(expr.base), expr.exp) return self._print(expr) return self._print_Function(expr) def _print_TypeCast(self, expr): if not expr.explicit: return self._print(expr.expr) else: return self._print(expr.expr) + ' as %s' % self.type_mappings[self.type_aliases[expr.type_]] def _print_Float(self, expr, _type=False): ret = super()._print_Float(expr) if _type: return ret + '_%s' % self.type_mappings[self.type_aliases[real]] else: return ret def _print_Integer(self, expr, _type=False): ret = super()._print_Integer(expr) if _type: return ret + '_%s' % self.type_mappings[self.type_aliases[integer]] else: return ret def _print_Rational(self, expr): p, q = int(expr.p), int(expr.q) float_suffix = self.type_mappings[self.type_aliases[real]] return '%d_%s/%d.0' % (p, float_suffix, q) def _print_Relational(self, expr): if (expr.lhs.is_integer and not expr.rhs.is_integer) or (expr.rhs.is_integer and not expr.lhs.is_integer): lhs = self._cast_to_float(expr.lhs) rhs = self._cast_to_float(expr.rhs) else: lhs = expr.lhs rhs = expr.rhs lhs_code = self._print(lhs) rhs_code = self._print(rhs) op = expr.rel_op return "{} {} {}".format(lhs_code, op, rhs_code) def _print_Indexed(self, expr): # calculate index for 1d array dims = expr.shape elem = S.Zero offset = S.One for i in reversed(range(expr.rank)): elem += expr.indices[i]*offset offset *= dims[i] return "%s[%s]" % (self._print(expr.base.label), self._print(elem)) def _print_Idx(self, expr): return expr.label.name def _print_Dummy(self, expr): return expr.name def _print_Exp1(self, expr, _type=False): return "E" def _print_Pi(self, expr, _type=False): return 'PI' def _print_Infinity(self, expr, _type=False): return 'INFINITY' def _print_NegativeInfinity(self, expr, _type=False): return 'NEG_INFINITY' def _print_BooleanTrue(self, expr, _type=False): return "true" def _print_BooleanFalse(self, expr, _type=False): return "false" def _print_bool(self, expr, _type=False): return str(expr).lower() def _print_NaN(self, expr, _type=False): return "NAN" def _print_Piecewise(self, expr): if expr.args[-1].cond != True: # We need the last conditional to be a True, otherwise the resulting # function may not return a result. raise ValueError("All Piecewise expressions must contain an " "(expr, True) statement to be used as a default " "condition. Without one, the generated " "expression may not evaluate to anything under " "some condition.") lines = [] for i, (e, c) in enumerate(expr.args): if i == 0: lines.append("if (%s) {" % self._print(c)) elif i == len(expr.args) - 1 and c == True: lines[-1] += " else {" else: lines[-1] += " else if (%s) {" % self._print(c) code0 = self._print(e) lines.append(code0) lines.append("}") if self._settings['inline']: return " ".join(lines) else: return "\n".join(lines) def _print_ITE(self, expr): from sympy.functions import Piecewise return self._print(expr.rewrite(Piecewise, deep=False)) def _print_MatrixBase(self, A): if A.cols == 1: return "[%s]" % ", ".join(self._print(a) for a in A) else: raise ValueError("Full Matrix Support in Rust need Crates (https://crates.io/keywords/matrix).") def _print_SparseRepMatrix(self, mat): # do not allow sparse matrices to be made dense return self._print_not_supported(mat) def _print_MatrixElement(self, expr): return "%s[%s]" % (expr.parent, expr.j + expr.i*expr.parent.shape[1]) def _print_Symbol(self, expr): name = super()._print_Symbol(expr) if expr in self._dereference: return '(*%s)' % name else: return name def _print_Assignment(self, expr): from sympy.tensor.indexed import IndexedBase lhs = expr.lhs rhs = expr.rhs if self._settings["contract"] and (lhs.has(IndexedBase) or rhs.has(IndexedBase)): # Here we check if there is looping to be done, and if so # print the required loops. return self._doprint_loops(rhs, lhs) else: lhs_code = self._print(lhs) rhs_code = self._print(rhs) return self._get_statement("%s = %s" % (lhs_code, rhs_code)) def _print_sign(self, expr): arg = self._print(expr.args[0]) return "(if (%s == 0.0) { 0.0 } else { (%s).signum() })" % (arg, arg) def _cast_to_float(self, expr): if not expr.is_number: return TypeCast(expr, real) elif expr.is_integer: return Float(expr) return expr def _can_print(self, name): """ Check if function ``name`` is either a known function or has its own printing method. Used to check if rewriting is possible.""" # since the whole point of function_overrides is to enable proper printing, # we presume they all are printable return name in self.known_functions or name in function_overrides or getattr(self, '_print_{}'.format(name), False) def _collect_functions(self, expr): functions = set() if isinstance(expr, Expr): if expr.is_Function: functions.add(expr.func) for arg in expr.args: functions = functions.union(self._collect_functions(arg)) return functions def _rewrite_known_functions(self, expr): if not isinstance(expr, Expr): return expr expression_functions = self._collect_functions(expr) rewriteable_functions = { name: (target_f, required_fs) for name, (target_f, required_fs) in self._rewriteable_functions.items() if self._can_print(target_f) and all(self._can_print(f) for f in required_fs) } for func in expression_functions: target_f, _ = rewriteable_functions.get(func.__name__, (None, None)) if target_f: expr = expr.rewrite(target_f) return expr def indent_code(self, code): """Accepts a string of code or a list of code lines""" if isinstance(code, str): code_lines = self.indent_code(code.splitlines(True)) return ''.join(code_lines) tab = " " inc_token = ('{', '(', '{\n', '(\n') dec_token = ('}', ')') code = [ line.lstrip(' \t') for line in code ] increase = [ int(any(map(line.endswith, inc_token))) for line in code ] decrease = [ int(any(map(line.startswith, dec_token))) for line in code ] pretty = [] level = 0 for n, line in enumerate(code): if line in ('', '\n'): pretty.append(line) continue level -= decrease[n] pretty.append("%s%s" % (tab*level, line)) level += increase[n] return pretty
RustCodePrinter
python
django__django
django/contrib/gis/feeds.py
{ "start": 129, "end": 3931 }
class ____: """ This mixin provides the necessary routines for SyndicationFeed subclasses to produce simple GeoRSS or W3C Geo elements. """ def georss_coords(self, coords): """ In GeoRSS coordinate pairs are ordered by lat/lon and separated by a single white space. Given a tuple of coordinates, return a string GeoRSS representation. """ return " ".join("%f %f" % (coord[1], coord[0]) for coord in coords) def add_georss_point(self, handler, coords, w3c_geo=False): """ Adds a GeoRSS point with the given coords using the given handler. Handles the differences between simple GeoRSS and the more popular W3C Geo specification. """ if w3c_geo: lon, lat = coords[:2] handler.addQuickElement("geo:lat", "%f" % lat) handler.addQuickElement("geo:lon", "%f" % lon) else: handler.addQuickElement("georss:point", self.georss_coords((coords,))) def add_georss_element(self, handler, item, w3c_geo=False): """Add a GeoRSS XML element using the given item and handler.""" # Getting the Geometry object. geom = item.get("geometry") if geom is not None: if isinstance(geom, (list, tuple)): # Special case if a tuple/list was passed in. The tuple may be # a point or a box box_coords = None if isinstance(geom[0], (list, tuple)): # Box: ( (X0, Y0), (X1, Y1) ) if len(geom) == 2: box_coords = geom else: raise ValueError("Only should be two sets of coordinates.") else: if len(geom) == 2: # Point: (X, Y) self.add_georss_point(handler, geom, w3c_geo=w3c_geo) elif len(geom) == 4: # Box: (X0, Y0, X1, Y1) box_coords = (geom[:2], geom[2:]) else: raise ValueError("Only should be 2 or 4 numeric elements.") # If a GeoRSS box was given via tuple. if box_coords is not None: if w3c_geo: raise ValueError( "Cannot use simple GeoRSS box in W3C Geo feeds." ) handler.addQuickElement( "georss:box", self.georss_coords(box_coords) ) else: # Getting the lowercase geometry type. gtype = str(geom.geom_type).lower() if gtype == "point": self.add_georss_point(handler, geom.coords, w3c_geo=w3c_geo) else: if w3c_geo: raise ValueError("W3C Geo only supports Point geometries.") # For formatting consistent w/the GeoRSS simple standard: # http://georss.org/1.0#simple if gtype in ("linestring", "linearring"): handler.addQuickElement( "georss:line", self.georss_coords(geom.coords) ) elif gtype in ("polygon",): # Only support the exterior ring. handler.addQuickElement( "georss:polygon", self.georss_coords(geom[0].coords) ) else: raise ValueError( 'Geometry type "%s" not supported.' % geom.geom_type ) # ### SyndicationFeed subclasses ###
GeoFeedMixin
python
huggingface__transformers
src/transformers/models/clvp/modeling_clvp.py
{ "start": 11759, "end": 17102 }
class ____(nn.Module): """ Multi-headed attention to combine Absolute and Rotary Positional Embeddings into a single Attention module. """ def __init__(self, config, layer_idx=None): super().__init__() self.config = config self.embed_dim = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = self.embed_dim // self.num_heads if self.head_dim * self.num_heads != self.embed_dim: raise ValueError( f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:" f" {self.num_heads})." ) self.scale = self.head_dim**-0.5 self.dropout = config.attention_dropout self.layer_idx = layer_idx if hasattr(config, "max_position_embeddings"): max_positions = config.max_position_embeddings bias = torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)) bias = bias.view(1, 1, max_positions, max_positions) self.register_buffer("bias", bias, persistent=False) self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_attention_bias) self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_attention_bias) self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=config.use_attention_bias) self.out_proj = nn.Linear(self.embed_dim, self.embed_dim) def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() def forward( self, hidden_states: torch.FloatTensor, rotary_pos_emb: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, use_cache: Optional[bool] = False, output_attentions: Optional[bool] = False, cache_position: Optional[torch.Tensor] = None, ) -> tuple[torch.FloatTensor, Optional[torch.FloatTensor], Optional[tuple[torch.FloatTensor]]]: # Raise error when position_ids is None but rotary_pos_emb is provided, because we need that when applying # rotary_pos_emb to query and key states. if rotary_pos_emb is not None and position_ids is None: raise ValueError("`position_ids` must be provided when `rotary_pos_emb` is not None.") bsz, _, embed_dim = hidden_states.size() # get query proj query_states = self._shape(self.q_proj(hidden_states), -1, bsz) * self.scale key_states = self._shape(self.k_proj(hidden_states), -1, bsz) value_states = self._shape(self.v_proj(hidden_states), -1, bsz) if past_key_values is not None: key_states, value_states = past_key_values.update( key_states, value_states, self.layer_idx, {"cache_position": cache_position} ) if rotary_pos_emb is not None: rotary_emb_dim = rotary_pos_emb.shape[-1] # Partial rotary embedding query_rot, query_pass = ( query_states[..., :rotary_emb_dim], query_states[..., rotary_emb_dim:], ) key_rot, key_pass = ( key_states[..., :rotary_emb_dim], key_states[..., rotary_emb_dim:], ) value_rot, value_pass = ( value_states[..., :rotary_emb_dim], value_states[..., rotary_emb_dim:], ) cos, sin = rotary_pos_emb.cos().squeeze(0), rotary_pos_emb.sin().squeeze(0) query_rot, key_rot, value_rot = apply_rotary_pos_emb(query_rot, key_rot, value_rot, cos, sin, position_ids) # [batch_size, num_heads, seq_length, head_dim] query_states = torch.cat((query_rot, query_pass), dim=-1) key_states = torch.cat((key_rot, key_pass), dim=-1) value_states = torch.cat((value_rot, value_pass), dim=-1) tgt_len = query_states.shape[2] src_len = key_states.shape[2] attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) if attention_mask is not None: if attention_mask.size() != (bsz, 1, tgt_len, src_len): raise ValueError( f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}" ) attn_weights = attn_weights + attention_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1) attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training) attn_output = torch.matmul(attn_probs, value_states) if attn_output.size() != (bsz, self.num_heads, tgt_len, self.head_dim): raise ValueError( f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is" f" {attn_output.size()}" ) attn_output = attn_output.transpose(1, 2).contiguous() attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim) attn_output = self.out_proj(attn_output) return attn_output, attn_weights
ClvpSelfAttention
python
astropy__astropy
astropy/time/formats.py
{ "start": 63121, "end": 64958 }
class ____(TimeString): """ ISO 8601 compliant date-time format "YYYY-MM-DD HH:MM:SS.sss...". For example, 2000-01-01 00:00:00.000 is midnight on January 1, 2000. The allowed subformats are: - 'date_hms': date + hours, mins, secs (and optional fractional secs) - 'date_hm': date + hours, mins - 'date': date """ name = "iso" subfmts = ( ( "date_hms", "%Y-%m-%d %H:%M:%S", # XXX To Do - use strftime for output ?? "{year:d}-{mon:02d}-{day:02d} {hour:02d}:{min:02d}:{sec:02d}", ), ( "date_hm", "%Y-%m-%d %H:%M", "{year:d}-{mon:02d}-{day:02d} {hour:02d}:{min:02d}", ), ("date", "%Y-%m-%d", "{year:d}-{mon:02d}-{day:02d}"), ) # Define positions and starting delimiter for year, month, day, hour, # minute, seconds components of an ISO time. This is used by the fast # C-parser parse_ymdhms_times() # # "2000-01-12 13:14:15.678" # 01234567890123456789012 # yyyy-mm-dd hh:mm:ss.fff # Parsed as ('yyyy', '-mm', '-dd', ' hh', ':mm', ':ss', '.fff') fast_parser_pars = dict( delims=(0, ord("-"), ord("-"), ord(" "), ord(":"), ord(":"), ord(".")), starts=(0, 4, 7, 10, 13, 16, 19), stops=(3, 6, 9, 12, 15, 18, -1), # Break allowed *before* # y m d h m s f break_allowed=(0, 0, 0, 1, 0, 1, 1), has_day_of_year=0, ) def parse_string(self, timestr, subfmts): # Handle trailing 'Z' for UTC time if timestr.endswith("Z"): if self.scale != "utc": raise ValueError("Time input terminating in 'Z' must have scale='UTC'") timestr = timestr[:-1] return super().parse_string(timestr, subfmts)
TimeISO
python
python__mypy
mypy/server/update.py
{ "start": 6702, "end": 22345 }
class ____: def __init__(self, result: BuildResult) -> None: """Initialize fine-grained build based on a batch build. Args: result: Result from the initialized build. The manager and graph will be taken over by this class. manager: State of the build (mutated by this class) graph: Additional state of the build (mutated by this class) """ manager = result.manager self.manager = manager self.graph = result.graph self.previous_modules = get_module_to_path_map(self.graph) self.deps = manager.fg_deps # Merge in any root dependencies that may not have been loaded merge_dependencies(manager.load_fine_grained_deps(FAKE_ROOT_MODULE), self.deps) self.previous_targets_with_errors = manager.errors.targets() self.previous_messages: list[str] = result.errors.copy() # Module, if any, that had blocking errors in the last run as (id, path) tuple. self.blocking_error: tuple[str, str] | None = None # Module that we haven't processed yet but that are known to be stale. self.stale: list[tuple[str, str]] = [] # Disable the cache so that load_graph doesn't try going back to disk # for the cache. self.manager.cache_enabled = False # Some hints to the test suite about what is going on: # Active triggers during the last update self.triggered: list[str] = [] # Modules passed to update during the last update self.changed_modules: list[tuple[str, str]] = [] # Modules processed during the last update self.updated_modules: list[str] = [] # Targets processed during last update (for testing only). self.processed_targets: list[str] = [] def update( self, changed_modules: list[tuple[str, str]], removed_modules: list[tuple[str, str]], followed: bool = False, ) -> list[str]: """Update previous build result by processing changed modules. Also propagate changes to other modules as needed, but only process those parts of other modules that are affected by the changes. Retain the existing ASTs and symbol tables of unaffected modules. Reuses original BuildManager and Graph. Args: changed_modules: Modules changed since the previous update/build; each is a (module id, path) tuple. Includes modified and added modules. Assume this is correct; it's not validated here. removed_modules: Modules that have been deleted since the previous update or removed from the build. followed: If True, the modules were found through following imports Returns: A list of errors. """ self.processed_targets.clear() changed_modules = changed_modules + removed_modules removed_set = {module for module, _ in removed_modules} self.changed_modules = changed_modules if not changed_modules: return self.previous_messages # Reset find_module's caches for the new build. self.manager.find_module_cache.clear() self.triggered = [] self.updated_modules = [] changed_modules = dedupe_modules(changed_modules + self.stale) initial_set = {id for id, _ in changed_modules} self.manager.log_fine_grained( "==== update %s ====" % ", ".join(repr(id) for id, _ in changed_modules) ) if self.previous_targets_with_errors and is_verbose(self.manager): self.manager.log_fine_grained( "previous targets with errors: %s" % sorted(self.previous_targets_with_errors) ) blocking_error = None if self.blocking_error: # Handle blocking errors first. We'll exit as soon as we find a # module that still has blocking errors. self.manager.log_fine_grained(f"existing blocker: {self.blocking_error[0]}") changed_modules = dedupe_modules([self.blocking_error] + changed_modules) blocking_error = self.blocking_error[0] self.blocking_error = None while True: result = self.update_one( changed_modules, initial_set, removed_set, blocking_error, followed ) changed_modules, (next_id, next_path), blocker_messages = result if blocker_messages is not None: self.blocking_error = (next_id, next_path) self.stale = changed_modules messages = blocker_messages break # It looks like we are done processing everything, so now # reprocess all targets with errors. We are careful to # support the possibility that reprocessing an errored module # might trigger loading of a module, but I am not sure # if this can really happen. if not changed_modules: # N.B: We just checked next_id, so manager.errors contains # the errors from it. Thus we consider next_id up to date # when propagating changes from the errored targets, # which prevents us from reprocessing errors in it. changed_modules = propagate_changes_using_dependencies( self.manager, self.graph, self.deps, set(), {next_id}, self.previous_targets_with_errors, self.processed_targets, ) changed_modules = dedupe_modules(changed_modules) if not changed_modules: # Preserve state needed for the next update. self.previous_targets_with_errors = self.manager.errors.targets() messages = self.manager.errors.new_messages() break messages = sort_messages_preserving_file_order(messages, self.previous_messages) self.previous_messages = messages.copy() return messages def trigger(self, target: str) -> list[str]: """Trigger a specific target explicitly. This is intended for use by the suggestions engine. """ self.manager.errors.reset() changed_modules = propagate_changes_using_dependencies( self.manager, self.graph, self.deps, set(), set(), self.previous_targets_with_errors | {target}, [], ) # Preserve state needed for the next update. self.previous_targets_with_errors = self.manager.errors.targets() self.previous_messages = self.manager.errors.new_messages().copy() return self.update(changed_modules, []) def flush_cache(self) -> None: """Flush AST cache. This needs to be called after each increment, or file changes won't be detected reliably. """ self.manager.ast_cache.clear() def update_one( self, changed_modules: list[tuple[str, str]], initial_set: set[str], removed_set: set[str], blocking_error: str | None, followed: bool, ) -> tuple[list[tuple[str, str]], tuple[str, str], list[str] | None]: """Process a module from the list of changed modules. Returns: Tuple with these items: - Updated list of pending changed modules as (module id, path) tuples - Module which was actually processed as (id, path) tuple - If there was a blocking error, the error messages from it """ t0 = time.time() next_id, next_path = changed_modules.pop(0) # If we have a module with a blocking error that is no longer # in the import graph, we must skip it as otherwise we'll be # stuck with the blocking error. if ( next_id == blocking_error and next_id not in self.previous_modules and next_id not in initial_set ): self.manager.log_fine_grained( f"skip {next_id!r} (module with blocking error not in import graph)" ) return changed_modules, (next_id, next_path), None result = self.update_module(next_id, next_path, next_id in removed_set, followed) remaining, (next_id, next_path), blocker_messages = result changed_modules = [(id, path) for id, path in changed_modules if id != next_id] changed_modules = dedupe_modules(remaining + changed_modules) t1 = time.time() self.manager.log_fine_grained( f"update once: {next_id} in {t1 - t0:.3f}s - {len(changed_modules)} left" ) return changed_modules, (next_id, next_path), blocker_messages def update_module( self, module: str, path: str, force_removed: bool, followed: bool ) -> tuple[list[tuple[str, str]], tuple[str, str], list[str] | None]: """Update a single modified module. If the module contains imports of previously unseen modules, only process one of the new modules and return the remaining work to be done. Args: module: Id of the module path: File system path of the module force_removed: If True, consider module removed from the build even if path exists (used for removing an existing file from the build) followed: Was this found via import following? Returns: Tuple with these items: - Remaining modules to process as (module id, path) tuples - Module which was actually processed as (id, path) tuple - If there was a blocking error, the error messages from it """ self.manager.log_fine_grained(f"--- update single {module!r} ---") self.updated_modules.append(module) # builtins and friends could potentially get triggered because # of protocol stuff, but nothing good could possibly come from # actually updating them. if ( is_stdlib_file(self.manager.options.abs_custom_typeshed_dir, path) or module in SENSITIVE_INTERNAL_MODULES ): return [], (module, path), None manager = self.manager previous_modules = self.previous_modules graph = self.graph ensure_deps_loaded(module, self.deps, graph) # If this is an already existing module, make sure that we have # its tree loaded so that we can snapshot it for comparison. ensure_trees_loaded(manager, graph, [module]) t0 = time.time() # Record symbol table snapshot of old version the changed module. old_snapshots: dict[str, dict[str, SymbolSnapshot]] = {} if module in manager.modules: snapshot = snapshot_symbol_table(module, manager.modules[module].names) old_snapshots[module] = snapshot manager.errors.reset() self.processed_targets.append(module) result = update_module_isolated( module, path, manager, previous_modules, graph, force_removed, followed ) if isinstance(result, BlockedUpdate): # Blocking error -- just give up module, path, remaining, errors = result self.previous_modules = get_module_to_path_map(graph) return remaining, (module, path), errors assert isinstance(result, NormalUpdate) # Work around #4124 module, path, remaining, tree = result # TODO: What to do with stale dependencies? t1 = time.time() triggered = calculate_active_triggers(manager, old_snapshots, {module: tree}) if is_verbose(self.manager): filtered = [trigger for trigger in triggered if not trigger.endswith("__>")] self.manager.log_fine_grained(f"triggered: {sorted(filtered)!r}") self.triggered.extend(triggered | self.previous_targets_with_errors) if module in graph: graph[module].update_fine_grained_deps(self.deps) graph[module].free_state() remaining += propagate_changes_using_dependencies( manager, graph, self.deps, triggered, {module}, targets_with_errors=set(), processed_targets=self.processed_targets, ) t2 = time.time() manager.add_stats(update_isolated_time=t1 - t0, propagate_time=t2 - t1) # Preserve state needed for the next update. self.previous_targets_with_errors.update(manager.errors.targets()) self.previous_modules = get_module_to_path_map(graph) return remaining, (module, path), None def find_unloaded_deps( manager: BuildManager, graph: dict[str, State], initial: Sequence[str] ) -> list[str]: """Find all the deps of the nodes in initial that haven't had their tree loaded. The key invariant here is that if a module is loaded, so are all of their dependencies. This means that when we encounter a loaded module, we don't need to explore its dependencies. (This invariant is slightly violated when dependencies are added, which can be handled by calling find_unloaded_deps directly on the new dependencies.) """ worklist = list(initial) seen: set[str] = set() unloaded = [] while worklist: node = worklist.pop() if node in seen or node not in graph: continue seen.add(node) if node not in manager.modules: ancestors = graph[node].ancestors or [] worklist.extend(graph[node].dependencies + ancestors) unloaded.append(node) return unloaded def ensure_deps_loaded(module: str, deps: dict[str, set[str]], graph: dict[str, State]) -> None: """Ensure that the dependencies on a module are loaded. Dependencies are loaded into the 'deps' dictionary. This also requires loading dependencies from any parent modules, since dependencies will get stored with parent modules when a module doesn't exist. """ if module in graph and graph[module].fine_grained_deps_loaded: return parts = module.split(".") for i in range(len(parts)): base = ".".join(parts[: i + 1]) if base in graph and not graph[base].fine_grained_deps_loaded: merge_dependencies(graph[base].load_fine_grained_deps(), deps) graph[base].fine_grained_deps_loaded = True def ensure_trees_loaded( manager: BuildManager, graph: dict[str, State], initial: Sequence[str] ) -> None: """Ensure that the modules in initial and their deps have loaded trees.""" to_process = find_unloaded_deps(manager, graph, initial) if to_process: if is_verbose(manager): manager.log_fine_grained( "Calling process_fresh_modules on set of size {} ({})".format( len(to_process), sorted(to_process) ) ) process_fresh_modules(graph, to_process, manager) # The result of update_module_isolated when no blockers, with these items: # # - Id of the changed module (can be different from the module argument) # - Path of the changed module # - New AST for the changed module (None if module was deleted) # - Remaining changed modules that are not processed yet as (module id, path) # tuples (non-empty if the original changed module imported other new # modules)
FineGrainedBuildManager
python
dask__distributed
distributed/deploy/tests/test_adaptive_core.py
{ "start": 140, "end": 2208 }
class ____(AdaptiveCore): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._observed = set() self._plan = set() self._requested = set() self._target = 0 self._log = [] @property def observed(self): return self._observed @property def plan(self): return self._plan @property def requested(self): return self._requested async def target(self): return self._target async def scale_up(self, n=0): self._plan = self._requested = set(range(n)) async def scale_down(self, workers=()): for collection in [self.plan, self.requested, self.observed]: for w in workers: collection.discard(w) @gen_test() async def test_safe_target(): adapt = MyAdaptiveCore(minimum=1, maximum=4) assert await adapt.safe_target() == 1 adapt._target = 10 assert await adapt.safe_target() == 4 @gen_test() async def test_scale_up(): adapt = MyAdaptiveCore(minimum=1, maximum=4) await adapt.adapt() assert adapt.log[-1][1] == {"status": "up", "n": 1} assert adapt.plan == {0} adapt._target = 10 await adapt.adapt() assert adapt.log[-1][1] == {"status": "up", "n": 4} assert adapt.plan == {0, 1, 2, 3} @gen_test() async def test_scale_down(): adapt = MyAdaptiveCore(minimum=1, maximum=4, wait_count=2) adapt._target = 10 await adapt.adapt() assert len(adapt.log) == 1 adapt._observed = {0, 1, 3} # all but 2 have arrived adapt._target = 2 await adapt.adapt() assert len(adapt.log) == 1 # no change after only one call await adapt.adapt() assert len(adapt.log) == 2 # no change after only one call assert adapt.log[-1][1]["status"] == "down" assert 2 in adapt.log[-1][1]["workers"] assert len(adapt.log[-1][1]["workers"]) == 2 old = list(adapt.log) await adapt.adapt() await adapt.adapt() await adapt.adapt() await adapt.adapt() assert list(adapt.log) == old
MyAdaptiveCore
python
google__jax
jax/_src/pallas/mosaic/interpret/shared_memory.py
{ "start": 6376, "end": 6796 }
class ____: content: np.ndarray _: dataclasses.KW_ONLY ref_count: int = 1 def decrease_ref_count(self): # We should never decrease the `ref_count` to below zero. assert self.ref_count > 0 self.ref_count -= 1 def has_zero_ref_count(self) -> bool: return self.ref_count == 0 def size(self) -> int: return self.content.itemsize * self.content.size @dataclasses.dataclass(frozen=True)
Buffer
python
ray-project__ray
release/ray_release/reporter/artifacts.py
{ "start": 473, "end": 1810 }
class ____(Reporter): """This is called on on buildkite runners.""" def __init__(self, artifacts_dir: str = DEFAULT_ARTIFACTS_DIR): self.artifacts_dir = artifacts_dir def report_result(self, test: Test, result: Result): if not os.path.exists(self.artifacts_dir): os.makedirs(self.artifacts_dir, 0o755) test_config_file = os.path.join(self.artifacts_dir, ARTIFACT_TEST_CONFIG_FILE) with open(test_config_file, "wt") as fp: json.dump(test, fp, sort_keys=True, indent=4) result_file = os.path.join(self.artifacts_dir, ARTIFACT_RESULT_FILE) result_dict = result.__dict__ metrics_dict = result_dict.pop("prometheus_metrics") with open(result_file, "wt") as fp: json.dump(result_dict, fp, sort_keys=True, indent=4) logger.info( f"Wrote test config and result to artifacts directory: {self.artifacts_dir}" ) if metrics_dict: metrics_file = os.path.join(self.artifacts_dir, METRICS_RESULT_FILE) with gzip.open(metrics_file, "wt", encoding="UTF-8") as fp: json.dump(metrics_dict, fp, sort_keys=True, indent=4) logger.info( f"Wrote prometheus metrics to artifacts directory: {self.artifacts_dir}" )
ArtifactsReporter
python
django__django
tests/postgres_tests/test_operations.py
{ "start": 6910, "end": 9261 }
class ____(OperationTestBase): app_label = "test_rm_concurrently" def test_requires_atomic_false(self): project_state = self.set_up_test_model(self.app_label, index=True) new_state = project_state.clone() operation = RemoveIndexConcurrently("Pony", "pony_pink_idx") msg = ( "The RemoveIndexConcurrently operation cannot be executed inside " "a transaction (set atomic = False on the migration)." ) with self.assertRaisesMessage(NotSupportedError, msg): with connection.schema_editor(atomic=True) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) def test_remove(self): project_state = self.set_up_test_model(self.app_label, index=True) table_name = "%s_pony" % self.app_label self.assertTableExists(table_name) new_state = project_state.clone() operation = RemoveIndexConcurrently("Pony", "pony_pink_idx") self.assertEqual( operation.describe(), "Concurrently remove index pony_pink_idx from Pony", ) self.assertEqual( operation.formatted_description(), "- Concurrently remove index pony_pink_idx from Pony", ) operation.state_forwards(self.app_label, new_state) self.assertEqual( len(new_state.models[self.app_label, "pony"].options["indexes"]), 0 ) self.assertIndexExists(table_name, ["pink"]) # Remove index. with connection.schema_editor(atomic=False) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) self.assertIndexNotExists(table_name, ["pink"]) # Reversal. with connection.schema_editor(atomic=False) as editor: operation.database_backwards( self.app_label, editor, new_state, project_state ) self.assertIndexExists(table_name, ["pink"]) # Deconstruction. name, args, kwargs = operation.deconstruct() self.assertEqual(name, "RemoveIndexConcurrently") self.assertEqual(args, []) self.assertEqual(kwargs, {"model_name": "Pony", "name": "pony_pink_idx"})
RemoveIndexConcurrentlyTests
python
doocs__leetcode
lcci/17.09.Get Kth Magic Number/Solution2.py
{ "start": 0, "end": 420 }
class ____: def getKthMagicNumber(self, k: int) -> int: dp = [1] * (k + 1) p3 = p5 = p7 = 1 for i in range(2, k + 1): a, b, c = dp[p3] * 3, dp[p5] * 5, dp[p7] * 7 v = min(a, b, c) dp[i] = v if v == a: p3 += 1 if v == b: p5 += 1 if v == c: p7 += 1 return dp[k]
Solution
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/errors.py
{ "start": 1018, "end": 1403 }
class ____(HypothesisException): """The condition we have been asked to satisfy appears to be always false. This does not guarantee that no example exists, only that we were unable to find one. """ def __init__(self, condition_string: str, extra: str = "") -> None: super().__init__(f"No examples found of condition {condition_string}{extra}")
NoSuchExample
python
sqlalchemy__sqlalchemy
test/orm/test_lazy_relations.py
{ "start": 48605, "end": 50854 }
class ____(fixtures.MappedTest, testing.AssertsExecutionResults): """ORM-level test for [ticket:3531]""" __sparse_driver_backend__ = True class StringAsInt(TypeDecorator): impl = String(50) cache_ok = True def get_dbapi_type(self, dbapi): return dbapi.NUMBER def column_expression(self, col): return sa.cast(col, Integer) def bind_expression(self, col): return sa.cast(sa.type_coerce(col, Integer), String(50)) @classmethod def define_tables(cls, metadata): Table( "person", metadata, Column("id", cls.StringAsInt, primary_key=True) ) Table( "pets", metadata, Column("id", Integer, primary_key=True), Column("person_id", Integer), ) @classmethod def setup_classes(cls): class Person(cls.Basic): pass class Pet(cls.Basic): pass @classmethod def setup_mappers(cls): cls.mapper_registry.map_imperatively( cls.classes.Person, cls.tables.person, properties=dict( pets=relationship( cls.classes.Pet, primaryjoin=( orm.foreign(cls.tables.pets.c.person_id) == sa.cast( sa.type_coerce(cls.tables.person.c.id, Integer), Integer, ) ), ) ), ) cls.mapper_registry.map_imperatively(cls.classes.Pet, cls.tables.pets) def test_lazyload_singlecast(self): Person = self.classes.Person Pet = self.classes.Pet s = fixture_session() s.add_all([Person(id=5), Pet(id=1, person_id=5)]) s.commit() p1 = s.query(Person).first() with self.sql_execution_asserter() as asserter: p1.pets asserter.assert_( CompiledSQL( "SELECT pets.id, pets.person_id " "FROM pets WHERE pets.person_id = " "CAST(:param_1 AS INTEGER)", [{"param_1": 5}], ) )
TypeCoerceTest
python
wandb__wandb
wandb/apis/paginator.py
{ "start": 4197, "end": 5247 }
class ____(Paginator[_WandbT], Generic[_NodeT, _WandbT], ABC): """A Paginator for GQL relay-style nodes parsed via Pydantic. <!-- lazydoc-ignore-class: internal --> """ last_response: Connection[_NodeT] | None @property def more(self) -> bool: return (conn := self.last_response) is None or conn.has_next @property def cursor(self) -> str | None: return conn.next_cursor if (conn := self.last_response) else None @abstractmethod def _convert(self, node: _NodeT) -> _WandbT | Any: """Convert a parsed GraphQL node into the iterated object. If a falsey value is returned, it will be skipped during iteration. """ raise NotImplementedError def convert_objects(self) -> Iterable[_WandbT]: # Default implementation. Subclasses can override this if if more complex # logic is needed, but ideally most shouldn't need to. if conn := self.last_response: yield from filter(None, map(self._convert, conn.nodes()))
RelayPaginator
python
walkccc__LeetCode
solutions/2810. Faulty Keyboard/2810.py
{ "start": 0, "end": 316 }
class ____: def finalString(self, s: str) -> str: dq = collections.deque() inversed = False for c in s: if c == 'i': inversed = not inversed elif inversed: dq.appendleft(c) else: dq.append(c) return ''.join(reversed(dq)) if inversed else ''.join(dq)
Solution
python
tensorflow__tensorflow
tensorflow/python/ops/init_ops_v2.py
{ "start": 26343, "end": 28209 }
class ____(Initializer): """Initializer that generates the identity matrix. Initializers allow you to pre-specify an initialization strategy, encoded in the Initializer object, without knowing the shape and dtype of the variable being initialized. Only usable for generating 2D matrices. Examples: >>> def make_variable(k, initializer): ... return tf.Variable(initializer(shape=[k, k], dtype=tf.float32)) >>> make_variable(2, tf.initializers.Identity()) <tf.Variable ... shape=(2, 2) dtype=float32, numpy= array([[1., 0.], [0., 1.]], dtype=float32)> >>> make_variable(3, tf.initializers.Identity(gain=0.5)) <tf.Variable ... shape=(3, 3) dtype=float32, numpy= array([[0.5, 0. , 0. ], [0. , 0.5, 0. ], [0. , 0. , 0.5]], dtype=float32)> Args: gain: Multiplicative factor to apply to the identity matrix. """ def __init__(self, gain=1.0): self.gain = gain def __call__(self, shape, dtype=dtypes.float32, **kwargs): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only floating point types are supported. **kwargs: Additional keyword arguments. Raises: ValueError: If the dtype is not floating point ValueError: If the requested shape does not have exactly two axes. """ self._validate_kwargs(kwargs, support_partition=False) dtype = _assert_float_dtype(dtype) if len(shape) != 2: raise ValueError("The tensor to initialize, specified by argument `shape`" " must be at least two-dimensional. Received shape=" f"{shape}") initializer = linalg_ops_impl.eye(*shape, dtype=dtype) return self.gain * initializer def get_config(self): return {"gain": self.gain}
Identity
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 84855, "end": 85051 }
class ____(BaseModel, extra="forbid"): points: List["ExtendedPointId"] = Field(..., description="") shard_key: Optional["ShardKeySelector"] = Field(default=None, description="")
PointIdsList
python
plotly__plotly.py
plotly/graph_objs/waterfall/totals/_marker.py
{ "start": 233, "end": 3358 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "waterfall.totals" _path_str = "waterfall.totals.marker" _valid_props = {"color", "line"} @property def color(self): """ Sets the marker color of all intermediate sums and total values. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def line(self): """ The 'line' property is an instance of Line that may be specified as: - An instance of :class:`plotly.graph_objs.waterfall.totals.marker.Line` - A dict of string/value properties that will be passed to the Line constructor Returns ------- plotly.graph_objs.waterfall.totals.marker.Line """ return self["line"] @line.setter def line(self, val): self["line"] = val @property def _prop_descriptions(self): return """\ color Sets the marker color of all intermediate sums and total values. line :class:`plotly.graph_objects.waterfall.totals.marker.Li ne` instance or dict with compatible properties """ def __init__(self, arg=None, color=None, line=None, **kwargs): """ Construct a new Marker object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.waterfall.totals.Marker` color Sets the marker color of all intermediate sums and total values. line :class:`plotly.graph_objects.waterfall.totals.marker.Li ne` instance or dict with compatible properties Returns ------- Marker """ super().__init__("marker") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.waterfall.totals.Marker constructor must be a dict or an instance of :class:`plotly.graph_objs.waterfall.totals.Marker`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._set_property("line", arg, line) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Marker
python
keras-team__keras
keras/src/ops/nn_test.py
{ "start": 91682, "end": 111863 }
class ____(testing.TestCase): """Test the floating dtype to verify that the behavior matches JAX.""" FLOAT_DTYPES = [x for x in dtypes.FLOAT_TYPES if x not in ("float64",)] @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_elu(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((), dtype=dtype) x_jax = jnp.ones((), dtype=dtype) expected_dtype = standardize_dtype(jnn.elu(x_jax).dtype) self.assertEqual( standardize_dtype(knn.elu(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.Elu().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_gelu(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((), dtype=dtype) x_jax = jnp.ones((), dtype=dtype) # approximate = True expected_dtype = standardize_dtype(jnn.gelu(x_jax).dtype) self.assertEqual( standardize_dtype(knn.gelu(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.Gelu().symbolic_call(x).dtype), expected_dtype, ) # approximate = False expected_dtype = standardize_dtype(jnn.gelu(x_jax, False).dtype) self.assertEqual( standardize_dtype(knn.gelu(x, False).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.Gelu(False).symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_celu(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((), dtype=dtype) x_jax = jnp.ones((), dtype=dtype) expected_dtype = standardize_dtype(jnn.celu(x_jax).dtype) self.assertEqual( standardize_dtype(knn.celu(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.Celu().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_tanh_shrink(self, dtype): import torch import torch.nn.functional as tnn x = knp.ones((1), dtype=dtype) x_torch = torch.ones(1, dtype=getattr(torch, dtype)) expected_dtype = standardize_dtype(tnn.tanhshrink(x_torch).dtype) self.assertEqual( standardize_dtype(knn.tanh_shrink(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.TanhShrink().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_hard_tanh(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((), dtype=dtype) x_jax = jnp.ones((), dtype=dtype) expected_dtype = standardize_dtype(jnn.hard_tanh(x_jax).dtype) self.assertEqual( standardize_dtype(knn.hard_tanh(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.HardTanh().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_hard_shrink(self, dtype): import torch import torch.nn.functional as tnn x = knp.ones((1), dtype=dtype) x_torch = torch.ones(1, dtype=getattr(torch, dtype)) expected_dtype = standardize_dtype(tnn.hardshrink(x_torch).dtype) self.assertEqual( standardize_dtype(knn.hard_shrink(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.HardShrink().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_threshold(self, dtype): import torch import torch.nn.functional as tnn x = knp.ones((1), dtype=dtype) x_torch = torch.ones(1, dtype=getattr(torch, dtype)) expected_dtype = standardize_dtype(tnn.threshold(x_torch, 0, 0).dtype) self.assertEqual( standardize_dtype(knn.threshold(x, 0, 0).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.Threshold(0, 0).symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_soft_shrink(self, dtype): import torch import torch.nn.functional as tnn x = knp.ones((1), dtype=dtype) x_torch = torch.ones(1, dtype=getattr(torch, dtype)) expected_dtype = standardize_dtype(tnn.softshrink(x_torch).dtype) self.assertEqual( standardize_dtype(knn.soft_shrink(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.SoftShrink().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_sparse_plus(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((), dtype=dtype) x_jax = jnp.ones((), dtype=dtype) expected_dtype = standardize_dtype(jnn.sparse_plus(x_jax).dtype) self.assertEqual( standardize_dtype(knn.sparse_plus(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.SparsePlus().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_glu(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((2), dtype=dtype) x_jax = jnp.ones((2), dtype=dtype) expected_dtype = standardize_dtype(jnn.glu(x_jax).dtype) self.assertEqual( standardize_dtype(knn.glu(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.Glu().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_squareplus(self, dtype): import jax.nn as jnn import jax.numpy as jnp if dtype == "bfloat16": self.skipTest("Weirdness with numpy") x = knp.ones((2), dtype=dtype) x_jax = jnp.ones((2), dtype=dtype) expected_dtype = standardize_dtype(jnn.squareplus(x_jax).dtype) self.assertEqual( standardize_dtype(knn.squareplus(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.Squareplus().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_hard_sigmoid(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((), dtype=dtype) x_jax = jnp.ones((), dtype=dtype) expected_dtype = standardize_dtype(jnn.hard_sigmoid(x_jax).dtype) self.assertEqual( standardize_dtype(knn.hard_sigmoid(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.HardSigmoid().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_hard_silu(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((), dtype=dtype) x_jax = jnp.ones((), dtype=dtype) expected_dtype = standardize_dtype(jnn.hard_silu(x_jax).dtype) self.assertEqual( standardize_dtype(knn.hard_silu(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.HardSilu().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_leaky_relu(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((), dtype=dtype) x_jax = jnp.ones((), dtype=dtype) expected_dtype = standardize_dtype(jnn.leaky_relu(x_jax).dtype) self.assertEqual( standardize_dtype(knn.leaky_relu(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.LeakyRelu().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_log_sigmoid(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((), dtype=dtype) x_jax = jnp.ones((), dtype=dtype) expected_dtype = standardize_dtype(jnn.log_sigmoid(x_jax).dtype) self.assertEqual( standardize_dtype(knn.log_sigmoid(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.LogSigmoid().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_log_softmax(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((10,), dtype=dtype) x_jax = jnp.ones((10,), dtype=dtype) expected_dtype = standardize_dtype(jnn.log_softmax(x_jax).dtype) self.assertEqual( standardize_dtype(knn.log_softmax(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.LogSoftmax().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_relu(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((), dtype=dtype) x_jax = jnp.ones((), dtype=dtype) expected_dtype = standardize_dtype(jnn.relu(x_jax).dtype) self.assertEqual( standardize_dtype(knn.relu(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.Relu().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_relu6(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((), dtype=dtype) x_jax = jnp.ones((), dtype=dtype) expected_dtype = standardize_dtype(jnn.relu6(x_jax).dtype) self.assertEqual( standardize_dtype(knn.relu6(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.Relu6().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_selu(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((), dtype=dtype) x_jax = jnp.ones((), dtype=dtype) expected_dtype = standardize_dtype(jnn.selu(x_jax).dtype) self.assertEqual( standardize_dtype(knn.selu(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.Selu().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_sigmoid(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((), dtype=dtype) x_jax = jnp.ones((), dtype=dtype) expected_dtype = standardize_dtype(jnn.sigmoid(x_jax).dtype) self.assertEqual( standardize_dtype(knn.sigmoid(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.Sigmoid().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_sparse_sigmoid(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((), dtype=dtype) x_jax = jnp.ones((), dtype=dtype) expected_dtype = standardize_dtype(jnn.sparse_sigmoid(x_jax).dtype) self.assertEqual( standardize_dtype(knn.sparse_sigmoid(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.SparseSigmoid().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_silu(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((), dtype=dtype) x_jax = jnp.ones((), dtype=dtype) expected_dtype = standardize_dtype(jnn.silu(x_jax).dtype) self.assertEqual( standardize_dtype(knn.silu(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.Silu().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_softplus(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((), dtype=dtype) x_jax = jnp.ones((), dtype=dtype) expected_dtype = standardize_dtype(jnn.softplus(x_jax).dtype) self.assertEqual( standardize_dtype(knn.softplus(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.Softplus().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_softmax(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((10,), dtype=dtype) x_jax = jnp.ones((10,), dtype=dtype) expected_dtype = standardize_dtype(jnn.softmax(x_jax).dtype) self.assertEqual( standardize_dtype(knn.softmax(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.Softmax().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_softsign(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((), dtype=dtype) x_jax = jnp.ones((), dtype=dtype) expected_dtype = standardize_dtype(jnn.soft_sign(x_jax).dtype) self.assertEqual( standardize_dtype(knn.softsign(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.Softsign().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_polar(self, dtype): import jax.nn as jnn import jax.numpy as jnp x = knp.ones((), dtype=dtype) x_jax = jnp.ones((), dtype=dtype) expected_dtype = standardize_dtype(jnn.hard_tanh(x_jax).dtype) self.assertEqual( standardize_dtype(knn.hard_tanh(x).dtype), expected_dtype, ) self.assertEqual( standardize_dtype(knn.HardTanh().symbolic_call(x).dtype), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_ctc_loss(self, dtype): labels = knp.array([[1, 2, 1]], dtype="int32") outputs = knp.array( [[[0.4, 0.8, 0.4], [0.2, 0.8, 0.3], [0.9, 0.4, 0.5]]], dtype=dtype ) label_length = knp.array([3]) output_length = knp.array([3]) expected_dtype = ( "float32" if dtype in ("float16", "bfloat16") else dtype ) self.assertEqual( standardize_dtype( knn.ctc_loss(labels, outputs, label_length, output_length).dtype ), expected_dtype, ) self.assertEqual( standardize_dtype( knn.CTCLoss() .symbolic_call(labels, outputs, label_length, output_length) .dtype ), expected_dtype, ) @parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES)) def test_ctc_decode(self, dtype): inputs = knp.array( [[[0.4, 0.8, 0.4], [0.2, 0.8, 0.3], [0.9, 0.4, 0.5]]], dtype=dtype ) sequence_length = knp.array([3]) expected_dtype = backend.result_type(dtype, "float32") # Test strategy="greedy" decoded, scores = knn.ctc_decode( inputs, sequence_length, strategy="greedy" ) self.assertEqual(standardize_dtype(decoded.dtype), "int32") self.assertEqual(standardize_dtype(scores.dtype), expected_dtype) decoded, scores = knn.CTCDecode(strategy="greedy").symbolic_call( inputs, sequence_length ) self.assertEqual(standardize_dtype(decoded.dtype), "int32") self.assertEqual(standardize_dtype(scores.dtype), expected_dtype) if backend.backend() == "torch": self.skipTest("torch doesn't support 'beam_search' strategy") # Test strategy="beam_search" decoded, scores = knn.ctc_decode( inputs, sequence_length, strategy="beam_search" ) self.assertEqual(standardize_dtype(decoded.dtype), "int32") self.assertEqual(standardize_dtype(scores.dtype), expected_dtype) decoded, scores = knn.CTCDecode(strategy="beam_search").symbolic_call( inputs, sequence_length ) self.assertEqual(standardize_dtype(decoded.dtype), "int32") self.assertEqual(standardize_dtype(scores.dtype), expected_dtype) @parameterized.named_parameters( named_product( dtypes=list(combinations(FLOAT_DTYPES, 2)) + [(dtype, dtype) for dtype in FLOAT_DTYPES] ) ) def test_dot_product_attention(self, dtypes): # TODO: Get expected output from jax if `jax.nn.dot_product_attention` # is available. query_dtype, key_value_dtype = dtypes query = knp.ones((2, 3, 3, 8), dtype=query_dtype) key = knp.ones((2, 3, 3, 8), dtype=key_value_dtype) value = knp.ones((2, 3, 3, 8), dtype=key_value_dtype) expected_dtype = backend.result_type(*dtypes) self.assertDType( knn.dot_product_attention(query, key, value), expected_dtype ) self.assertDType( knn.DotProductAttention().symbolic_call(query, key, value), expected_dtype, ) @parameterized.named_parameters( named_product(dtypes=combinations(FLOAT_DTYPES, 2)) ) def test_rms_normalization(self, dtypes): input_dtype, weight_dtype = dtypes inputs = knp.ones((2, 8), dtype=input_dtype) scale = backend.Variable(knp.ones((8,), dtype=weight_dtype)) expected_dtype = input_dtype self.assertDType(knn.rms_normalization(inputs, scale), expected_dtype) self.assertDType( knn.RMSNorm().symbolic_call(inputs, scale), expected_dtype ) @parameterized.named_parameters( named_product(dtypes=combinations(FLOAT_DTYPES, 2)) ) def test_layer_normalization(self, dtypes): input_dtype, weight_dtype = dtypes inputs = knp.ones((2, 8), dtype=input_dtype) gamma = backend.Variable(knp.ones((8,), dtype=weight_dtype)) beta = backend.Variable(knp.ones((8,), dtype=weight_dtype)) expected_dtype = input_dtype self.assertDType( knn.layer_normalization(inputs, gamma, beta), expected_dtype ) self.assertDType( knn.LayerNorm().symbolic_call(inputs, gamma, beta), expected_dtype )
NNOpsDtypeTest
python
getsentry__sentry
tests/sentry/dynamic_sampling/tasks/test_common.py
{ "start": 2274, "end": 5131 }
class ____(BaseMetricsLayerTestCase, TestCase, SnubaTestCase): def setUp(self) -> None: self.orgs = [] # create 12 orgs each and some transactions with a 2/1 drop/keep rate for i in range(12): org = self.create_organization(f"org-{i}") self.orgs.append(org) project = self.create_project(organization=org) for decision, value in [("drop", 2), ("keep", 1)]: self.store_performance_metric( name=TransactionMRI.COUNT_PER_ROOT_PROJECT.value, tags={"transaction": "foo_transaction", "decision": decision}, minutes_before_now=1, value=value, project_id=project.id, org_id=org.id, ) @property def now(self): return MOCK_DATETIME def test_get_active_orgs_volumes_exact_batch_match(self) -> None: """ gets active org volumes, with a batch size multiple of number of elements """ total_orgs = 0 for orgs in GetActiveOrgsVolumes(max_orgs=3): num_orgs = len(orgs) total_orgs += num_orgs assert num_orgs == 3 # first batch should be full for org in orgs: assert org.total == 3 assert org.indexed == 1 assert total_orgs == 12 def test_get_active_orgs_volumes(self) -> None: """ gets active org volumes, with a batch size that is not a multiple of the number of elements in the DB """ total_orgs = 0 for idx, orgs in enumerate(GetActiveOrgsVolumes(max_orgs=5)): num_orgs = len(orgs) total_orgs += num_orgs if idx in [0, 1]: assert num_orgs == 5 # first two batches should be full elif idx == 2: assert num_orgs == 2 # last batch not full else: pytest.fail(f"Unexpected index {idx} only 3 iterations expected.") for org in orgs: assert org.total == 3 assert org.indexed == 1 assert total_orgs == 12 def test_get_organization_volume_existing_org(self) -> None: """ gets the volume of one existing organization """ org = self.orgs[0] org_volume = get_organization_volume(org.id) assert org_volume == OrganizationDataVolume(org_id=org.id, total=3, indexed=1) def test_get_organization_volume_missing_org(self) -> None: """ calls get_organization_volume for a missing org (should return None) """ org_id = 99999999 # can we do better, an id we know for sure is not in the DB? org_volume = get_organization_volume(org_id) assert org_volume is None
TestGetActiveOrgsVolumes
python
pytest-dev__pytest
src/_pytest/warning_types.py
{ "start": 1270, "end": 1436 }
class ____(PytestDeprecationWarning): """Warning class for features that will be removed in pytest 10.""" __module__ = "pytest" @final
PytestRemovedIn10Warning
python
getsentry__sentry
tests/sentry/core/endpoints/test_project_details.py
{ "start": 67152, "end": 71321 }
class ____(APITestCase): endpoint = "sentry-api-0-project-details" method = "delete" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) @mock.patch("sentry.db.pending_deletion.uuid4") def _delete_project_and_assert_deleted(self, mock_uuid4_mixin): mock_uuid4_mixin.return_value = self.get_mock_uuid() with self.settings(SENTRY_PROJECT=0): self.get_success_response( self.project.organization.slug, self.project.slug, status_code=204 ) assert RegionScheduledDeletion.objects.filter( model_name="Project", object_id=self.project.id ).exists() project = Project.objects.get(id=self.project.id) assert project.status == ObjectStatus.PENDING_DELETION assert project.slug == "abc123" assert OrganizationOption.objects.filter( organization_id=project.organization_id, key=build_pending_deletion_key(project), ).exists() deleted_project = DeletedProject.objects.get(slug=self.project.slug) self.assert_valid_deleted_log(deleted_project, self.project) def test_simple(self) -> None: self._delete_project_and_assert_deleted() def test_superuser(self) -> None: superuser = self.create_user(is_superuser=True) self.login_as(user=superuser, superuser=True) self._delete_project_and_assert_deleted() def test_staff(self) -> None: staff_user = self.create_user(is_staff=True) self.login_as(user=staff_user, staff=True) self._delete_project_and_assert_deleted() def test_internal_project(self) -> None: with self.settings(SENTRY_PROJECT=self.project.id): self.get_error_response( self.project.organization.slug, self.project.slug, status_code=403 ) assert not RegionScheduledDeletion.objects.filter( model_name="Project", object_id=self.project.id ).exists() @mock.patch( "sentry.tasks.delete_seer_grouping_records.call_seer_delete_project_grouping_records.apply_async" ) def test_delete_project_and_delete_grouping_records( self, mock_call_seer_delete_project_grouping_records ): self.project.update_option("sentry:similarity_backfill_completed", int(time())) self._delete_project_and_assert_deleted() mock_call_seer_delete_project_grouping_records.assert_called_with(args=[self.project.id]) def test_delete_without_events_does_not_require_sudo(self) -> None: # Ensure project has no recorded events self.project.update(first_event=None) # By default, tests run with has_sudo_privileges=True so we need to disable that with mock.patch( "sentry.testutils.middleware.SudoMiddleware.has_sudo_privileges", return_value=False ): with self.settings(SENTRY_PROJECT=0): self.get_success_response( self.project.organization.slug, self.project.slug, status_code=204 ) # Should go ahead with deletion assert RegionScheduledDeletion.objects.filter( model_name="Project", object_id=self.project.id ).exists() def test_delete_with_events_requires_sudo(self) -> None: # Simulate a project that has received events self.project.update(first_event=datetime.now(tz=timezone.utc)) # By default, tests run with has_sudo_privileges=True so we need to disable that with mock.patch( "sentry.testutils.middleware.SudoMiddleware.has_sudo_privileges", return_value=False ): with self.settings(SENTRY_PROJECT=0): resp = self.get_error_response( self.project.organization.slug, self.project.slug, status_code=401 ) # Should raise sudo-required and not schedule deletion assert resp.data["detail"]["code"] == "sudo-required" assert not RegionScheduledDeletion.objects.filter( model_name="Project", object_id=self.project.id ).exists()
ProjectDeleteTest
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/service/auto_shard_test.py
{ "start": 2281, "end": 24241 }
class ____(data_service_test_base.TestBase, tf_record_test_base.TFRecordTestBase, parameterized.TestCase): """Tests auto-sharding datasets with tf.data service.""" def setUp(self): super(AutoShardTest, self).setUp() self._num_files = 10 self._num_records = 10 self._filenames = self._createFiles() @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine(sharding_policy=[ data_service_ops.ShardingPolicy.DATA, data_service_ops.ShardingPolicy.FILE_OR_DATA ]))) def testRangeDataset_AutoShard(self, sharding_policy): cluster = _make_service_cluster(num_workers=5, local_shard_index=1) dataset = dataset_ops.Dataset.range(20) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=sharding_policy) self.assertDatasetProduces(dataset, [1, 6, 11, 16]) @combinations.generate(test_base.default_test_combinations()) def testRangeDataset_FileShard(self): cluster = _make_service_cluster(num_workers=5, local_shard_index=1) dataset = dataset_ops.Dataset.range(20) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.FILE) with self.assertRaisesRegex(errors.NotFoundError, "Found an unshardable source dataset"): self.getDatasetOutput(dataset) @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine(worker_index=[distribute.SHARD_HINT, 0, 5]))) def testRangeDataset_ShardHint(self, worker_index): cluster = _make_service_cluster(num_workers=5, local_shard_index=1) dataset = dataset_ops.Dataset.range(20) # With HINT sharding, `num_shards` should be `SHARD_HINT`; `index` can be # any value. dataset = dataset.shard( num_shards=distribute.SHARD_HINT, index=worker_index) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.HINT) self.assertDatasetProduces(dataset, [1, 6, 11, 16]) @combinations.generate(test_base.default_test_combinations()) def testRangeDataset_InvalidWorkerIndexUsingShardHint(self): cluster = _make_service_cluster(num_workers=5, local_shard_index=1) dataset = dataset_ops.Dataset.range(20) # With HINT sharding, `SHARD_HINT` should be passed to `num_shards`, not # `index`. with self.assertRaisesRegex( errors.InvalidArgumentError, r"Index must be between 0 and 4 \(currently index = -1\)."): dataset = dataset.shard(num_shards=5, index=distribute.SHARD_HINT) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.HINT) self.getDatasetOutput(dataset) @combinations.generate(test_base.default_test_combinations()) def testRangeDataset_NoShardHint(self): cluster = _make_service_cluster(num_workers=5, local_shard_index=1) dataset = dataset_ops.Dataset.range(20) # No SHARD_HINT is provided. The given sharding arguments will be used. dataset = dataset.shard(num_shards=1, index=0) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.HINT) self.assertDatasetProduces(dataset, list(range(20))) @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine(sharding_policy=[ data_service_ops.ShardingPolicy.OFF, data_service_ops.ShardingPolicy.FILE_OR_DATA ]))) def testRangeDataset_ShardHintUsedInWrongShardingPolicy( self, sharding_policy): cluster = _make_service_cluster(num_workers=5, local_shard_index=1) dataset = dataset_ops.Dataset.range(20) dataset = dataset.shard(distribute.SHARD_HINT, distribute.SHARD_HINT) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=sharding_policy) with self.assertRaisesRegex( errors.FailedPreconditionError, "tf.data service with " "`tf.data.experimental.service.ShardingPolicy.HINT` processing mode."): self.getDatasetOutput(dataset) @combinations.generate(test_base.default_test_combinations()) def testRangeDataset_NoShard(self): cluster = _make_service_cluster(num_workers=5, local_shard_index=1) dataset = dataset_ops.Dataset.range(20) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.OFF, target_workers="LOCAL") self.assertDatasetProduces(dataset, list(range(20))) @combinations.generate(test_base.default_test_combinations()) def testRangeDataset_OneWorker(self): """Makes sure shards from all workers form the complete dataset.""" cluster = _make_service_cluster(num_workers=1, local_shard_index=0) dataset = dataset_ops.Dataset.range(20) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.FILE_OR_DATA) self.assertDatasetProduces(dataset, list(range(20))) @combinations.generate(test_base.default_test_combinations()) def testRangeDataset_ReadFromAnyWorker(self): # When deployment mode is unspecified, the client will read from any worker. cluster = _make_service_cluster( num_workers=5, local_shard_index=1, deployment_mode=None) dataset = dataset_ops.Dataset.range(20) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.FILE_OR_DATA) self.assertDatasetProduces( dataset, list(range(20)), assert_items_equal=True) @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine(sharding_policy=[ data_service_ops.ShardingPolicy.FILE_OR_DATA, data_service_ops.ShardingPolicy.FILE ]))) def testTFRecordDataset_AutoShard(self, sharding_policy): cluster = _make_service_cluster(num_workers=5, local_shard_index=3) dataset = dataset_ops.Dataset.list_files(self._filenames, shuffle=False) dataset = dataset.flat_map(readers.TFRecordDataset) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=sharding_policy, target_workers="LOCAL") expected = [ b"Record %d of file %d" % (record, file) for file in (3, 8) for record in range(0, 10) ] self.assertDatasetProduces(dataset, expected) @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine(sharding_policy=[ data_service_ops.ShardingPolicy.FILE_OR_DATA, data_service_ops.ShardingPolicy.FILE ]))) def testTFRecordDataset_ShuffleFileList(self, sharding_policy): cluster = _make_service_cluster(num_workers=5, local_shard_index=3) dataset = dataset_ops.Dataset.list_files(self._filenames, shuffle=True) dataset = dataset.flat_map(readers.TFRecordDataset) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=sharding_policy) expected = [ b"Record %d of file %d" % (record, file) for file in (3, 8) for record in range(0, 10) ] self.assertDatasetProduces(dataset, expected, assert_items_equal=True) @combinations.generate(test_base.default_test_combinations()) def testTFRecordDataset_DataShard(self): cluster = _make_service_cluster(num_workers=5, local_shard_index=3) dataset = dataset_ops.Dataset.list_files(self._filenames, shuffle=False) dataset = dataset.flat_map(readers.TFRecordDataset) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.DATA) expected = [ b"Record %d of file %d" % (record, file) for file in range(0, 10) for record in (3, 8) ] self.assertDatasetProduces(dataset, expected) @combinations.generate(test_base.default_test_combinations()) def testTFRecordDataset_HintDataShard(self): cluster = _make_service_cluster(num_workers=5, local_shard_index=3) dataset = dataset_ops.Dataset.list_files(self._filenames, shuffle=False) dataset = dataset.flat_map(readers.TFRecordDataset) dataset = dataset.shard(distribute.SHARD_HINT, distribute.SHARD_HINT) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.HINT) expected = [ b"Record %d of file %d" % (record, file) for file in range(0, 10) for record in (3, 8) ] self.assertDatasetProduces(dataset, expected) @combinations.generate(test_base.default_test_combinations()) def testTFRecordDataset_HintFileShard(self): cluster = _make_service_cluster(num_workers=5, local_shard_index=3) dataset = dataset_ops.Dataset.list_files(self._filenames, shuffle=False) dataset = dataset.shard(distribute.SHARD_HINT, distribute.SHARD_HINT) dataset = dataset.flat_map(readers.TFRecordDataset) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.HINT) expected = [ b"Record %d of file %d" % (record, file) for file in (3, 8) for record in range(0, 10) ] self.assertDatasetProduces(dataset, expected) @combinations.generate(test_base.default_test_combinations()) def testTFRecordDataset_NoShard(self): cluster = _make_service_cluster(num_workers=5, local_shard_index=3) dataset = dataset_ops.Dataset.list_files(self._filenames, shuffle=False) dataset = dataset.flat_map(readers.TFRecordDataset) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.OFF, target_workers="LOCAL") expected = [ b"Record %d of file %d" % (record, file) for file in range(0, 10) for record in range(0, 10) ] self.assertDatasetProduces(dataset, expected) @combinations.generate(test_base.default_test_combinations()) def testTFRecordDataset_ReadFromAnyWorker(self): # When deployment mode is unspecified, the client will read from any worker. cluster = _make_service_cluster( num_workers=5, local_shard_index=3, deployment_mode=None) dataset = dataset_ops.Dataset.list_files(self._filenames, shuffle=False) dataset = dataset.flat_map(readers.TFRecordDataset) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.FILE_OR_DATA) expected = [ b"Record %d of file %d" % (record, file) for file in range(0, 10) for record in range(0, 10) ] self.assertDatasetProduces(dataset, expected, assert_items_equal=True) @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine(sharding_policy=[ data_service_ops.ShardingPolicy.FILE_OR_DATA, data_service_ops.ShardingPolicy.FILE ]))) def testTFRecordDataset_FewerFilesThanWorkers(self, sharding_policy): cluster = _make_service_cluster(num_workers=5, local_shard_index=3) dataset = dataset_ops.Dataset.list_files(self._filenames[:4], shuffle=False) dataset = dataset.flat_map(readers.TFRecordDataset) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=sharding_policy) with self.assertRaisesRegex( errors.InvalidArgumentError, "not enough for the required 5 shards/workers."): self.getDatasetOutput(dataset) @combinations.generate(test_base.default_test_combinations()) def testTFRecordDataset_FewerFilesThanWorkers_HintShard(self): cluster = _make_service_cluster(num_workers=5, local_shard_index=3) dataset = dataset_ops.Dataset.list_files(self._filenames[:4], shuffle=False) dataset = dataset.shard(distribute.SHARD_HINT, distribute.SHARD_HINT) dataset = dataset.flat_map(readers.TFRecordDataset) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.HINT) with self.assertRaisesRegex( errors.InvalidArgumentError, "not enough for the required 5 shards/workers."): self.getDatasetOutput(dataset) @combinations.generate(test_base.default_test_combinations()) def testTFRecordDataset_FewerFilesThanWorkers_DataShard(self): cluster = _make_service_cluster(num_workers=5, local_shard_index=3) dataset = dataset_ops.Dataset.list_files(self._filenames[:4], shuffle=False) dataset = dataset.flat_map(readers.TFRecordDataset) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.DATA) expected = [ b"Record %d of file %d" % (record, file) for file in range(0, 4) for record in (3, 8) ] self.assertDatasetProduces(dataset, expected, assert_items_equal=True) @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine(sharding_policy=[ data_service_ops.ShardingPolicy.FILE_OR_DATA, data_service_ops.ShardingPolicy.DATA ]))) def testBatchDataset(self, sharding_policy): cluster = _make_service_cluster(num_workers=5, local_shard_index=1) dataset = dataset_ops.Dataset.range(20) dataset = dataset.batch(batch_size=3, drop_remainder=False) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=sharding_policy) self.assertDatasetProduces(dataset, [[3, 4, 5], [18, 19]]) @combinations.generate(test_base.default_test_combinations()) def testInterleaveDataset(self): cluster = _make_service_cluster(num_workers=5, local_shard_index=3) dataset = dataset_ops.Dataset.list_files(self._filenames, shuffle=False) dataset = dataset.interleave( readers.TFRecordDataset, cycle_length=10, num_parallel_calls=dataset_ops.AUTOTUNE) dataset = dataset.prefetch(buffer_size=dataset_ops.AUTOTUNE) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.FILE_OR_DATA) dataset = dataset.prefetch(buffer_size=dataset_ops.AUTOTUNE) expected = [ b"Record %d of file %d" % (record, file) for record in range(0, 10) for file in (3, 8) ] self.assertDatasetProduces(dataset, expected) @combinations.generate(test_base.default_test_combinations()) def testZipDataset(self): cluster = _make_service_cluster(num_workers=5, local_shard_index=3) dataset1 = dataset_ops.Dataset.list_files(self._filenames, shuffle=False) dataset1 = dataset1.interleave( readers.TFRecordDataset, cycle_length=10, num_parallel_calls=dataset_ops.AUTOTUNE) dataset2 = dataset_ops.Dataset.list_files(self._filenames, shuffle=False) dataset2 = dataset2.interleave( readers.TFRecordDataset, cycle_length=10, num_parallel_calls=dataset_ops.AUTOTUNE) dataset = dataset_ops.Dataset.zip((dataset1, dataset2)) dataset = dataset.prefetch(buffer_size=dataset_ops.AUTOTUNE) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.FILE_OR_DATA) expected = [(b"Record %d of file %d" % (record, file), b"Record %d of file %d" % (record, file)) for record in range(0, 10) for file in (3, 8)] self.assertDatasetProduces(dataset, expected) @combinations.generate(test_base.default_test_combinations()) def testConcatenateDataset(self): cluster = _make_service_cluster(num_workers=5, local_shard_index=3) dataset1 = dataset_ops.Dataset.list_files(self._filenames, shuffle=False) dataset1 = dataset1.interleave( readers.TFRecordDataset, cycle_length=10, num_parallel_calls=dataset_ops.AUTOTUNE) dataset2 = dataset_ops.Dataset.list_files(self._filenames, shuffle=False) dataset2 = dataset2.interleave( readers.TFRecordDataset, cycle_length=10, num_parallel_calls=dataset_ops.AUTOTUNE) dataset = dataset1.concatenate(dataset2) dataset = dataset.prefetch(buffer_size=dataset_ops.AUTOTUNE) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.FILE_OR_DATA) expected = [ b"Record %d of file %d" % (record, file) for record in range(0, 10) for file in (3, 8) ] expected += expected self.assertDatasetProduces(dataset, expected) @combinations.generate(test_base.default_test_combinations()) def testEmptyDataset(self): cluster = _make_service_cluster(num_workers=5, local_shard_index=3) dataset = dataset_ops.Dataset.range(0) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.FILE_OR_DATA) self.assertDatasetProduces(dataset, []) @combinations.generate(test_base.default_test_combinations()) def testAnonymousPorts(self): cluster = _make_service_cluster( num_workers=5, local_shard_index=3, worker_addresses=["localhost:%port%" for _ in range(5)]) dataset = dataset_ops.Dataset.range(20) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.FILE_OR_DATA) self.assertDatasetProduces(dataset, [3, 8, 13, 18]) @combinations.generate(test_base.default_test_combinations()) def testNamedPorts(self): cluster = _make_service_cluster( num_workers=5, local_shard_index=3, worker_addresses=["localhost:%port_worker%" for _ in range(5)]) dataset = dataset_ops.Dataset.range(20) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.FILE_OR_DATA) self.assertDatasetProduces(dataset, [3, 8, 13, 18]) @combinations.generate(test_base.default_test_combinations()) def testInvalidPorts(self): with self.assertRaisesRegex(RuntimeError, "The worker's address is not configured"): _ = _make_service_cluster( num_workers=5, local_shard_index=0, worker_addresses=["localhost:worker" for _ in range(5)]) @combinations.generate(test_base.default_test_combinations()) def testEmptyWorkerList(self): cluster = _make_service_cluster( num_workers=5, local_shard_index=1, worker_addresses=[]) dataset = dataset_ops.Dataset.range(20) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.FILE_OR_DATA) with self.assertRaisesRegex(errors.NotFoundError, "Worker .* is not in the workers list."): self.getDatasetOutput(dataset) @combinations.generate(test_base.default_test_combinations()) def testWorkerNotFound(self): worker_addresses = [f"fake_worker_{i}" for i in range(5)] with self.assertRaisesRegex(RuntimeError, "The worker's address is not configured"): _ = _make_service_cluster( num_workers=5, local_shard_index=0, worker_addresses=worker_addresses) @combinations.generate(test_base.default_test_combinations()) def testMoreWorkersThanConfigured(self): worker_addresses = ["localhost:%port%"] with self.assertRaisesRegex( RuntimeError, "other workers are already running at the configured host"): _ = _make_service_cluster( num_workers=5, local_shard_index=1, worker_addresses=worker_addresses) @combinations.generate(test_base.default_test_combinations()) def testNoLocalWorkers(self): cluster = multi_process_cluster.MultiProcessCluster( num_local_workers=0, num_remote_workers=3) dataset = dataset_ops.Dataset.list_files(self._filenames, shuffle=False) dataset = dataset.flat_map(readers.TFRecordDataset) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=data_service_ops.ShardingPolicy.FILE_OR_DATA) with self.assertRaisesRegex( errors.InvalidArgumentError, "Static sharding policy <FILE_OR_DATA> requires local tf.data workers"): self.getDatasetOutput(dataset) @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine( sharding_policy=list(data_service_ops.ShardingPolicy)))) def testEnumerateShardingPolicies(self, sharding_policy): """Verifies tf.data service handles every sharding policy with no errors.""" cluster = _make_service_cluster(num_workers=5, local_shard_index=3) dataset = dataset_ops.Dataset.list_files(self._filenames, shuffle=False) dataset = dataset.flat_map(readers.TFRecordDataset) dataset = self.make_distributed_dataset( dataset, cluster=cluster, processing_mode=sharding_policy) self.getDatasetOutput(dataset) if __name__ == "__main__": multi_process_cluster.test_main()
AutoShardTest
python
networkx__networkx
networkx/drawing/tests/test_layout.py
{ "start": 143, "end": 23709 }
class ____: @classmethod def setup_class(cls): cls.Gi = nx.grid_2d_graph(5, 5) cls.Gs = nx.Graph() nx.add_path(cls.Gs, "abcdef") cls.bigG = nx.grid_2d_graph(25, 25) # > 500 nodes for sparse def test_spring_fixed_without_pos(self): G = nx.path_graph(4) # No pos dict at all with pytest.raises(ValueError, match="nodes are fixed without positions"): nx.spring_layout(G, fixed=[0]) pos = {0: (1, 1), 2: (0, 0)} # Node 1 not in pos dict with pytest.raises(ValueError, match="nodes are fixed without positions"): nx.spring_layout(G, fixed=[0, 1], pos=pos) # All fixed nodes in pos dict out = nx.spring_layout(G, fixed=[0, 2], pos=pos) # No ValueError assert all(np.array_equal(out[n], pos[n]) for n in (0, 2)) def test_spring_init_pos(self): # Tests GH #2448 import math G = nx.Graph() G.add_edges_from([(0, 1), (1, 2), (2, 0), (2, 3)]) init_pos = {0: (0.0, 0.0)} fixed_pos = [0] pos = nx.fruchterman_reingold_layout(G, pos=init_pos, fixed=fixed_pos) has_nan = any(math.isnan(c) for coords in pos.values() for c in coords) assert not has_nan, "values should not be nan" def test_smoke_empty_graph(self): G = [] nx.random_layout(G) nx.circular_layout(G) nx.planar_layout(G) nx.spring_layout(G) nx.fruchterman_reingold_layout(G) nx.spectral_layout(G) nx.shell_layout(G) nx.bipartite_layout(G, G) nx.spiral_layout(G) nx.multipartite_layout(G) nx.kamada_kawai_layout(G) def test_smoke_int(self): G = self.Gi nx.random_layout(G) nx.circular_layout(G) nx.planar_layout(G) nx.spring_layout(G) nx.forceatlas2_layout(G) nx.fruchterman_reingold_layout(G) nx.fruchterman_reingold_layout(self.bigG) nx.spectral_layout(G) nx.spectral_layout(G.to_directed()) nx.spectral_layout(self.bigG) nx.spectral_layout(self.bigG.to_directed()) nx.shell_layout(G) nx.spiral_layout(G) nx.kamada_kawai_layout(G) nx.kamada_kawai_layout(G, dim=1) nx.kamada_kawai_layout(G, dim=3) nx.arf_layout(G) def test_smoke_string(self): G = self.Gs nx.random_layout(G) nx.circular_layout(G) nx.planar_layout(G) nx.spring_layout(G) nx.forceatlas2_layout(G) nx.fruchterman_reingold_layout(G) nx.spectral_layout(G) nx.shell_layout(G) nx.spiral_layout(G) nx.kamada_kawai_layout(G) nx.kamada_kawai_layout(G, dim=1) nx.kamada_kawai_layout(G, dim=3) nx.arf_layout(G) def check_scale_and_center(self, pos, scale, center): center = np.array(center) low = center - scale hi = center + scale vpos = np.array(list(pos.values())) length = vpos.max(0) - vpos.min(0) assert (length <= 2 * scale).all() assert (vpos >= low).all() assert (vpos <= hi).all() def test_scale_and_center_arg(self): sc = self.check_scale_and_center c = (4, 5) G = nx.complete_graph(9) G.add_node(9) sc(nx.random_layout(G, center=c), scale=0.5, center=(4.5, 5.5)) # rest can have 2*scale length: [-scale, scale] sc(nx.spring_layout(G, scale=2, center=c), scale=2, center=c) sc(nx.spectral_layout(G, scale=2, center=c), scale=2, center=c) sc(nx.circular_layout(G, scale=2, center=c), scale=2, center=c) sc(nx.shell_layout(G, scale=2, center=c), scale=2, center=c) sc(nx.spiral_layout(G, scale=2, center=c), scale=2, center=c) sc(nx.kamada_kawai_layout(G, scale=2, center=c), scale=2, center=c) c = (2, 3, 5) sc(nx.kamada_kawai_layout(G, dim=3, scale=2, center=c), scale=2, center=c) def test_planar_layout_non_planar_input(self): G = nx.complete_graph(9) pytest.raises(nx.NetworkXException, nx.planar_layout, G) def test_smoke_planar_layout_embedding_input(self): embedding = nx.PlanarEmbedding() embedding.set_data({0: [1, 2], 1: [0, 2], 2: [0, 1]}) nx.planar_layout(embedding) def test_default_scale_and_center(self): sc = self.check_scale_and_center c = (0, 0) G = nx.complete_graph(9) G.add_node(9) sc(nx.random_layout(G), scale=0.5, center=(0.5, 0.5)) sc(nx.spring_layout(G), scale=1, center=c) sc(nx.spectral_layout(G), scale=1, center=c) sc(nx.circular_layout(G), scale=1, center=c) sc(nx.shell_layout(G), scale=1, center=c) sc(nx.spiral_layout(G), scale=1, center=c) sc(nx.kamada_kawai_layout(G), scale=1, center=c) c = (0, 0, 0) sc(nx.kamada_kawai_layout(G, dim=3), scale=1, center=c) def test_circular_planar_and_shell_dim_error(self): G = nx.path_graph(4) pytest.raises(ValueError, nx.circular_layout, G, dim=1) pytest.raises(ValueError, nx.shell_layout, G, dim=1) pytest.raises(ValueError, nx.shell_layout, G, dim=3) pytest.raises(ValueError, nx.planar_layout, G, dim=1) pytest.raises(ValueError, nx.planar_layout, G, dim=3) def test_adjacency_interface_numpy(self): A = nx.to_numpy_array(self.Gs) pos = nx.drawing.layout._fruchterman_reingold(A) assert pos.shape == (6, 2) pos = nx.drawing.layout._fruchterman_reingold(A, dim=3) assert pos.shape == (6, 3) pos = nx.drawing.layout._sparse_fruchterman_reingold(A) assert pos.shape == (6, 2) def test_adjacency_interface_scipy(self): A = nx.to_scipy_sparse_array(self.Gs, dtype="d") pos = nx.drawing.layout._sparse_fruchterman_reingold(A) assert pos.shape == (6, 2) pos = nx.drawing.layout._sparse_spectral(A) assert pos.shape == (6, 2) pos = nx.drawing.layout._sparse_fruchterman_reingold(A, dim=3) assert pos.shape == (6, 3) def test_single_nodes(self): G = nx.path_graph(1) vpos = nx.shell_layout(G) assert not vpos[0].any() G = nx.path_graph(4) vpos = nx.shell_layout(G, [[0], [1, 2], [3]]) assert not vpos[0].any() assert vpos[3].any() # ensure node 3 not at origin (#3188) assert np.linalg.norm(vpos[3]) <= 1 # ensure node 3 fits (#3753) vpos = nx.shell_layout(G, [[0], [1, 2], [3]], rotate=0) assert np.linalg.norm(vpos[3]) <= 1 # ensure node 3 fits (#3753) def test_smoke_initial_pos_forceatlas2(self): pos = nx.circular_layout(self.Gi) npos = nx.forceatlas2_layout(self.Gi, pos=pos) def test_smoke_initial_pos_fruchterman_reingold(self): pos = nx.circular_layout(self.Gi) npos = nx.fruchterman_reingold_layout(self.Gi, pos=pos) def test_smoke_initial_pos_arf(self): pos = nx.circular_layout(self.Gi) npos = nx.arf_layout(self.Gi, pos=pos) def test_fixed_node_fruchterman_reingold(self): # Dense version (numpy based) pos = nx.circular_layout(self.Gi) npos = nx.spring_layout(self.Gi, pos=pos, fixed=[(0, 0)]) assert tuple(pos[(0, 0)]) == tuple(npos[(0, 0)]) # Sparse version (scipy based) pos = nx.circular_layout(self.bigG) npos = nx.spring_layout(self.bigG, pos=pos, fixed=[(0, 0)]) for axis in range(2): assert pos[(0, 0)][axis] == pytest.approx(npos[(0, 0)][axis], abs=1e-7) def test_center_parameter(self): G = nx.path_graph(1) nx.random_layout(G, center=(1, 1)) vpos = nx.circular_layout(G, center=(1, 1)) assert tuple(vpos[0]) == (1, 1) vpos = nx.planar_layout(G, center=(1, 1)) assert tuple(vpos[0]) == (1, 1) vpos = nx.spring_layout(G, center=(1, 1)) assert tuple(vpos[0]) == (1, 1) vpos = nx.fruchterman_reingold_layout(G, center=(1, 1)) assert tuple(vpos[0]) == (1, 1) vpos = nx.spectral_layout(G, center=(1, 1)) assert tuple(vpos[0]) == (1, 1) vpos = nx.shell_layout(G, center=(1, 1)) assert tuple(vpos[0]) == (1, 1) vpos = nx.spiral_layout(G, center=(1, 1)) assert tuple(vpos[0]) == (1, 1) def test_center_wrong_dimensions(self): G = nx.path_graph(1) assert id(nx.spring_layout) == id(nx.fruchterman_reingold_layout) pytest.raises(ValueError, nx.random_layout, G, center=(1, 1, 1)) pytest.raises(ValueError, nx.circular_layout, G, center=(1, 1, 1)) pytest.raises(ValueError, nx.planar_layout, G, center=(1, 1, 1)) pytest.raises(ValueError, nx.spring_layout, G, center=(1, 1, 1)) pytest.raises(ValueError, nx.spring_layout, G, dim=3, center=(1, 1)) pytest.raises(ValueError, nx.spectral_layout, G, center=(1, 1, 1)) pytest.raises(ValueError, nx.spectral_layout, G, dim=3, center=(1, 1)) pytest.raises(ValueError, nx.shell_layout, G, center=(1, 1, 1)) pytest.raises(ValueError, nx.spiral_layout, G, center=(1, 1, 1)) pytest.raises(ValueError, nx.kamada_kawai_layout, G, center=(1, 1, 1)) def test_empty_graph(self): G = nx.empty_graph() vpos = nx.random_layout(G, center=(1, 1)) assert vpos == {} vpos = nx.circular_layout(G, center=(1, 1)) assert vpos == {} vpos = nx.planar_layout(G, center=(1, 1)) assert vpos == {} vpos = nx.bipartite_layout(G, G) assert vpos == {} vpos = nx.spring_layout(G, center=(1, 1)) assert vpos == {} vpos = nx.fruchterman_reingold_layout(G, center=(1, 1)) assert vpos == {} vpos = nx.spectral_layout(G, center=(1, 1)) assert vpos == {} vpos = nx.shell_layout(G, center=(1, 1)) assert vpos == {} vpos = nx.spiral_layout(G, center=(1, 1)) assert vpos == {} vpos = nx.multipartite_layout(G, center=(1, 1)) assert vpos == {} vpos = nx.kamada_kawai_layout(G, center=(1, 1)) assert vpos == {} vpos = nx.forceatlas2_layout(G) assert vpos == {} vpos = nx.arf_layout(G) assert vpos == {} def test_bipartite_layout(self): G = nx.complete_bipartite_graph(3, 5) top, bottom = nx.bipartite.sets(G) vpos = nx.bipartite_layout(G, top) assert len(vpos) == len(G) top_x = vpos[list(top)[0]][0] bottom_x = vpos[list(bottom)[0]][0] for node in top: assert vpos[node][0] == top_x for node in bottom: assert vpos[node][0] == bottom_x vpos = nx.bipartite_layout( G, top, align="horizontal", center=(2, 2), scale=2, aspect_ratio=1 ) assert len(vpos) == len(G) top_y = vpos[list(top)[0]][1] bottom_y = vpos[list(bottom)[0]][1] for node in top: assert vpos[node][1] == top_y for node in bottom: assert vpos[node][1] == bottom_y pytest.raises(ValueError, nx.bipartite_layout, G, top, align="foo") def test_multipartite_layout(self): sizes = (0, 5, 7, 2, 8) G = nx.complete_multipartite_graph(*sizes) vpos = nx.multipartite_layout(G) assert len(vpos) == len(G) start = 0 for n in sizes: end = start + n assert all(vpos[start][0] == vpos[i][0] for i in range(start + 1, end)) start += n vpos = nx.multipartite_layout(G, align="horizontal", scale=2, center=(2, 2)) assert len(vpos) == len(G) start = 0 for n in sizes: end = start + n assert all(vpos[start][1] == vpos[i][1] for i in range(start + 1, end)) start += n pytest.raises(ValueError, nx.multipartite_layout, G, align="foo") def test_kamada_kawai_costfn_1d(self): costfn = nx.drawing.layout._kamada_kawai_costfn pos = np.array([4.0, 7.0]) invdist = 1 / np.array([[0.1, 2.0], [2.0, 0.3]]) cost, grad = costfn(pos, np, invdist, meanweight=0, dim=1) assert cost == pytest.approx(((3 / 2.0 - 1) ** 2), abs=1e-7) assert grad[0] == pytest.approx((-0.5), abs=1e-7) assert grad[1] == pytest.approx(0.5, abs=1e-7) def check_kamada_kawai_costfn(self, pos, invdist, meanwt, dim): costfn = nx.drawing.layout._kamada_kawai_costfn cost, grad = costfn(pos.ravel(), np, invdist, meanweight=meanwt, dim=dim) expected_cost = 0.5 * meanwt * np.sum(np.sum(pos, axis=0) ** 2) for i in range(pos.shape[0]): for j in range(i + 1, pos.shape[0]): diff = np.linalg.norm(pos[i] - pos[j]) expected_cost += (diff * invdist[i][j] - 1.0) ** 2 assert cost == pytest.approx(expected_cost, abs=1e-7) dx = 1e-4 for nd in range(pos.shape[0]): for dm in range(pos.shape[1]): idx = nd * pos.shape[1] + dm ps = pos.flatten() ps[idx] += dx cplus = costfn(ps, np, invdist, meanweight=meanwt, dim=pos.shape[1])[0] ps[idx] -= 2 * dx cminus = costfn(ps, np, invdist, meanweight=meanwt, dim=pos.shape[1])[0] assert grad[idx] == pytest.approx((cplus - cminus) / (2 * dx), abs=1e-5) def test_kamada_kawai_costfn(self): invdist = 1 / np.array([[0.1, 2.1, 1.7], [2.1, 0.2, 0.6], [1.7, 0.6, 0.3]]) meanwt = 0.3 # 2d pos = np.array([[1.3, -3.2], [2.7, -0.3], [5.1, 2.5]]) self.check_kamada_kawai_costfn(pos, invdist, meanwt, 2) # 3d pos = np.array([[0.9, 8.6, -8.7], [-10, -0.5, -7.1], [9.1, -8.1, 1.6]]) self.check_kamada_kawai_costfn(pos, invdist, meanwt, 3) def test_spiral_layout(self): G = self.Gs # a lower value of resolution should result in a more compact layout # intuitively, the total distance from the start and end nodes # via each node in between (transiting through each) will be less, # assuming rescaling does not occur on the computed node positions pos_standard = np.array(list(nx.spiral_layout(G, resolution=0.35).values())) pos_tighter = np.array(list(nx.spiral_layout(G, resolution=0.34).values())) distances = np.linalg.norm(pos_standard[:-1] - pos_standard[1:], axis=1) distances_tighter = np.linalg.norm(pos_tighter[:-1] - pos_tighter[1:], axis=1) assert sum(distances) > sum(distances_tighter) # return near-equidistant points after the first value if set to true pos_equidistant = np.array(list(nx.spiral_layout(G, equidistant=True).values())) distances_equidistant = np.linalg.norm( pos_equidistant[:-1] - pos_equidistant[1:], axis=1 ) assert np.allclose( distances_equidistant[1:], distances_equidistant[-1], atol=0.01 ) def test_spiral_layout_equidistant(self): G = nx.path_graph(10) nx.spiral_layout(G, equidistant=True, store_pos_as="pos") pos = nx.get_node_attributes(G, "pos") # Extract individual node positions as an array p = np.array(list(pos.values())) # Elementwise-distance between node positions dist = np.linalg.norm(p[1:] - p[:-1], axis=1) assert np.allclose(np.diff(dist), 0, atol=1e-3) def test_forceatlas2_layout_partial_input_test(self): # check whether partial pos input still returns a full proper position G = self.Gs node = nx.utils.arbitrary_element(G) pos = nx.circular_layout(G) del pos[node] pos = nx.forceatlas2_layout(G, pos=pos) assert len(pos) == len(G) def test_rescale_layout_dict(self): G = nx.empty_graph() vpos = nx.random_layout(G, center=(1, 1)) assert nx.rescale_layout_dict(vpos) == {} G = nx.empty_graph(2) vpos = {0: (0.0, 0.0), 1: (1.0, 1.0)} s_vpos = nx.rescale_layout_dict(vpos) assert np.linalg.norm([sum(x) for x in zip(*s_vpos.values())]) < 1e-6 G = nx.empty_graph(3) vpos = {0: (0, 0), 1: (1, 1), 2: (0.5, 0.5)} s_vpos = nx.rescale_layout_dict(vpos) expectation = { 0: np.array((-1, -1)), 1: np.array((1, 1)), 2: np.array((0, 0)), } for k, v in expectation.items(): assert (s_vpos[k] == v).all() s_vpos = nx.rescale_layout_dict(vpos, scale=2) expectation = { 0: np.array((-2, -2)), 1: np.array((2, 2)), 2: np.array((0, 0)), } for k, v in expectation.items(): assert (s_vpos[k] == v).all() def test_arf_layout_partial_input_test(self): # Checks whether partial pos input still returns a proper position. G = self.Gs node = nx.utils.arbitrary_element(G) pos = nx.circular_layout(G) del pos[node] pos = nx.arf_layout(G, pos=pos) assert len(pos) == len(G) def test_arf_layout_negative_a_check(self): """ Checks input parameters correctly raises errors. For example, `a` should be larger than 1 """ G = self.Gs pytest.raises(ValueError, nx.arf_layout, G=G, a=-1) def test_smoke_seed_input(self): G = self.Gs nx.random_layout(G, seed=42) nx.spring_layout(G, seed=42) nx.arf_layout(G, seed=42) nx.forceatlas2_layout(G, seed=42) def test_node_at_center(self): # see gh-7791 avoid divide by zero G = nx.path_graph(3) orig_pos = {i: [i - 1, 0.0] for i in range(3)} new_pos = nx.forceatlas2_layout(G, pos=orig_pos) def test_initial_only_some_pos(self): G = nx.path_graph(3) orig_pos = {i: [i - 1, 0.0] for i in range(2)} new_pos = nx.forceatlas2_layout(G, pos=orig_pos, seed=42) def test_multipartite_layout_nonnumeric_partition_labels(): """See gh-5123.""" G = nx.Graph() G.add_node(0, subset="s0") G.add_node(1, subset="s0") G.add_node(2, subset="s1") G.add_node(3, subset="s1") G.add_edges_from([(0, 2), (0, 3), (1, 2)]) pos = nx.multipartite_layout(G) assert len(pos) == len(G) def test_multipartite_layout_layer_order(): """Return the layers in sorted order if the layers of the multipartite graph are sortable. See gh-5691""" G = nx.Graph() node_group = dict(zip(("a", "b", "c", "d", "e"), (2, 3, 1, 2, 4))) for node, layer in node_group.items(): G.add_node(node, subset=layer) # Horizontal alignment, therefore y-coord determines layers pos = nx.multipartite_layout(G, align="horizontal") layers = nx.utils.groups(node_group) pos_from_layers = nx.multipartite_layout(G, align="horizontal", subset_key=layers) for (n1, p1), (n2, p2) in zip(pos.items(), pos_from_layers.items()): assert n1 == n2 and (p1 == p2).all() # Nodes "a" and "d" are in the same layer assert pos["a"][-1] == pos["d"][-1] # positions should be sorted according to layer assert pos["c"][-1] < pos["a"][-1] < pos["b"][-1] < pos["e"][-1] # Make sure that multipartite_layout still works when layers are not sortable G.nodes["a"]["subset"] = "layer_0" # Can't sort mixed strs/ints pos_nosort = nx.multipartite_layout(G) # smoke test: this should not raise assert pos_nosort.keys() == pos.keys() def _num_nodes_per_bfs_layer(pos): """Helper function to extract the number of nodes in each layer of bfs_layout""" x = np.array(list(pos.values()))[:, 0] # node positions in layered dimension _, layer_count = np.unique(x, return_counts=True) return layer_count @pytest.mark.parametrize("n", range(2, 7)) def test_bfs_layout_complete_graph(n): """The complete graph should result in two layers: the starting node and a second layer containing all neighbors.""" G = nx.complete_graph(n) nx.bfs_layout(G, start=0, store_pos_as="pos") pos = nx.get_node_attributes(G, "pos") assert np.array_equal(_num_nodes_per_bfs_layer(pos), [1, n - 1]) def test_bfs_layout_barbell(): G = nx.barbell_graph(5, 3) # Start in one of the "bells" pos = nx.bfs_layout(G, start=0) # start, bell-1, [1] * len(bar)+1, bell-1 expected_nodes_per_layer = [1, 4, 1, 1, 1, 1, 4] assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer) # Start in the other "bell" - expect same layer pattern pos = nx.bfs_layout(G, start=12) assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer) # Starting in the center of the bar, expect layers to be symmetric pos = nx.bfs_layout(G, start=6) # Expected layers: {6 (start)}, {5, 7}, {4, 8}, {8 nodes from remainder of bells} expected_nodes_per_layer = [1, 2, 2, 8] assert np.array_equal(_num_nodes_per_bfs_layer(pos), expected_nodes_per_layer) def test_bfs_layout_disconnected(): G = nx.complete_graph(5) G.add_edges_from([(10, 11), (11, 12)]) with pytest.raises(nx.NetworkXError, match="bfs_layout didn't include all nodes"): nx.bfs_layout(G, start=0) def test_bipartite_layout_default_nodes_raises_non_bipartite_input(): G = nx.complete_graph(5) with pytest.raises(nx.NetworkXError, match="Graph is not bipartite"): nx.bipartite_layout(G) # No exception if nodes are explicitly specified pos = nx.bipartite_layout(G, nodes=[2, 3]) def test_bipartite_layout_default_nodes(): G = nx.complete_bipartite_graph(3, 3) pos = nx.bipartite_layout(G) # no nodes specified # X coords of nodes should be the same within the bipartite sets for nodeset in nx.bipartite.sets(G): xs = [pos[k][0] for k in nodeset] assert all(x == pytest.approx(xs[0]) for x in xs) @pytest.mark.parametrize( "layout", [ nx.random_layout, nx.circular_layout, nx.shell_layout, nx.spring_layout, nx.kamada_kawai_layout, nx.spectral_layout, nx.planar_layout, nx.spiral_layout, nx.forceatlas2_layout, ], ) def test_layouts_negative_dim(layout): """Test all layouts that support dim kwarg handle invalid inputs.""" G = nx.path_graph(4) valid_err_msgs = "|".join( [ "negative dimensions.*not allowed", "can only handle 2", "cannot handle.*2", ] ) with pytest.raises(ValueError, match=valid_err_msgs): layout(G, dim=-1) @pytest.mark.parametrize( ("num_nodes", "expected_method"), [(100, "force"), (501, "energy")] ) @pytest.mark.parametrize( "extra_layout_kwargs", [ {}, # No extra kwargs {"pos": {0: (0, 0)}, "fixed": [0]}, # Fixed node position {"dim": 3}, # 3D layout ], ) def test_spring_layout_graph_size_heuristic( num_nodes, expected_method, extra_layout_kwargs ): """Expect 'force' layout for n < 500 and 'energy' for n >= 500""" G = nx.cycle_graph(num_nodes) # Seeded layout to compare explicit method to one determined by "auto" seed = 163674319 # Compare explicit method to auto method expected = nx.spring_layout( G, method=expected_method, seed=seed, **extra_layout_kwargs ) actual = nx.spring_layout(G, method="auto", seed=seed, **extra_layout_kwargs) assert np.allclose(list(expected.values()), list(actual.values()), atol=1e-5)
TestLayout
python
pytorch__pytorch
test/distributed/tensor/test_redistribute.py
{ "start": 1317, "end": 27305 }
class ____(DTensorTestBase): @property def world_size(self): return 4 @with_comms @parametrize("dtype", [torch.float32, torch.cfloat]) def test_shard_to_replicate_forward_backward(self, dtype): # 1) test shard -> replicate forward device_mesh = self.build_device_mesh() replica_spec = [Replicate()] input_sizes_and_shard_dim = [ ((self.world_size * 3, 3), 0), ((self.world_size * 3 + 1, 3), 0), ((self.world_size * 3 + 2, 3), 0), ((3, self.world_size * 3), 1), ((3, self.world_size * 3 + 1), 1), ((3, self.world_size * 3 + 2), 1), ] comm_mode = CommDebugMode() for input_size, shard_dim in input_sizes_and_shard_dim: shard_spec = [Shard(shard_dim)] expected_tensor = torch.randn( input_size, device=self.device_type, requires_grad=True, dtype=dtype ) dtensor = distribute_tensor(expected_tensor, device_mesh, shard_spec) with comm_mode: reshard_dtensor = dtensor.redistribute(device_mesh, replica_spec) self.assertEqual(reshard_dtensor.size(), torch.Size(input_size)) self.assertEqual(expected_tensor, reshard_dtensor.to_local()) self.assertEqual( comm_mode.get_comm_counts()[funcol.all_gather_into_tensor], 1 ) # 2) test shard -> replicate backward: # should give gradient as shard grad_output = torch.ones_like(reshard_dtensor) with comm_mode: reshard_dtensor.backward(grad_output) grad_input = dtensor.grad self.assertEqual(grad_input.placements, shard_spec) self.assertEqual( grad_input.to_local(), torch.ones(dtensor.to_local().size(), dtype=dtype), ) self.assertEqual(comm_mode.get_total_counts(), 0) @with_comms def test_replicate_to_replicate_forward_backward(self): device_mesh = self.build_device_mesh() replica_spec = [Replicate()] local_tensor = torch.randn(12, 3, device=self.device_type, requires_grad=True) comm_mode = CommDebugMode() # 1) test replicate -> replicate forward replica_tensor = distribute_tensor(local_tensor, device_mesh, replica_spec) with comm_mode: reshard_replica_tensor = replica_tensor.redistribute( device_mesh, replica_spec ) self.assertEqual(replica_tensor.size(), local_tensor.size()) self.assertEqual(replica_tensor, reshard_replica_tensor) self.assertEqual(comm_mode.get_total_counts(), 0) # 2) test replicate -> replicate backward: # should give gradient as replicate grad_output = torch.ones_like(reshard_replica_tensor) with comm_mode: reshard_replica_tensor.backward(grad_output) grad_input = replica_tensor.grad self.assertEqual(grad_input.placements, replica_spec) self.assertEqual(grad_input.to_local(), torch.ones(12, 3)) self.assertEqual(comm_mode.get_total_counts(), 0) @with_comms @parametrize("dtype", [torch.float32, torch.cfloat]) def test_replicate_to_local_partial_grad(self, dtype): device_mesh = self.build_device_mesh() replica_spec = [Replicate()] local_tensor = torch.randn( 12, 3, device=self.device_type, requires_grad=True, dtype=dtype ) replica_tensor = distribute_tensor(local_tensor, device_mesh, replica_spec) comm_mode = CommDebugMode() with comm_mode: out = replica_tensor.redistribute(placements=[Replicate()]).to_local( grad_placements=[Partial()] ) out.backward(torch.ones_like(out)) self.assertEqual(comm_mode.get_total_counts(), 1) self.assertEqual(comm_mode.get_comm_counts()[funcol.all_reduce], 1) @with_comms def test_replicate_to_shard_forward_backward(self): device_mesh = self.build_device_mesh() replica_spec = [Replicate()] input_sizes_and_shard_dim = [ ((self.world_size * 3, 3), 0), ((self.world_size * 3 + 1, 3), 0), ((self.world_size * 3 + 2, 3), 0), ((3, self.world_size * 3), 1), ((3, self.world_size * 3 + 1), 1), ((3, self.world_size * 3 + 2), 1), ] comm_mode = CommDebugMode() for input_size, shard_dim in input_sizes_and_shard_dim: shard_spec = [Shard(shard_dim)] # 1) test replicate -> shard forward local_replica = torch.randn( input_size, device=self.device_type, requires_grad=True ) splitted_list = list( torch.chunk(local_replica, self.world_size, dim=shard_dim) ) # make local tensor as the element of the corresponding chunked list local_tensor = map_local_tensor_for_rank( splitted_list, self.rank, lambda tl, r: tl[r] ) replica_tensor = distribute_tensor(local_replica, device_mesh, replica_spec) with comm_mode: reshard_tensor = replica_tensor.redistribute(device_mesh, shard_spec) self.assertEqual(reshard_tensor.size(), replica_tensor.size()) self.assertEqual(reshard_tensor.placements, shard_spec) self.assertEqual(reshard_tensor.to_local(), local_tensor) self.assertEqual(comm_mode.get_total_counts(), 0) # 2) test replicate -> shard backward: # should give gradient as replicate grad_output = torch.ones_like(reshard_tensor) with comm_mode: reshard_tensor.backward(grad_output) grad_input = replica_tensor.grad self.assertEqual(grad_input.placements, replica_spec) self.assertEqual(grad_input.to_local(), torch.ones(input_size)) self.assertEqual(comm_mode.get_total_counts(), 1) self.assertEqual( comm_mode.get_comm_counts()[funcol.all_gather_into_tensor], 1 ) @with_comms @parametrize("dtype", [torch.float32, torch.cfloat]) def test_partial_to_replicate_forward_backward(self, dtype): # Although we don't allow user to reshard to produce a partial # placement (i.e. user can't reshard to partial), we do allow # replicate to partial internally, and also partial to replicate # backward should work as expected device_mesh = self.build_device_mesh() partial_local = torch.ones( 12, 3, device=self.device_type, requires_grad=True, dtype=dtype ) partial_spec = [Partial()] replica_spec = [Replicate()] comm_mode = CommDebugMode() # test partial -> replicate, which trigger all_reduce partial_tensor = DTensor.from_local(partial_local, device_mesh, partial_spec) with comm_mode: global_partial_tensor = partial_tensor.redistribute( device_mesh, replica_spec ) self.assertEqual(partial_tensor.size(), partial_local.size()) self.assertEqual( partial_local * self.world_size, global_partial_tensor.to_local() ) self.assertEqual(comm_mode.get_comm_counts()[funcol.all_reduce], 1) # test backward to have replicate grad on partial # for from_local backward, we want the replicate() -> partial() to be # pass through. with comm_mode: global_partial_tensor.backward(torch.ones_like(global_partial_tensor)) self.assertIsNotNone(partial_local.grad) self.assertEqual(partial_local.grad.size(), partial_local.size()) self.assertEqual( partial_local.grad, torch.ones_like(partial_local, dtype=dtype) ) self.assertEqual(comm_mode.get_total_counts(), 0) @with_comms def test_replicate_to_replicate_forward_backward_datatype_conversion(self): device_mesh = self.build_device_mesh() replica_spec = [Replicate()] forward_datatypes = [ torch.bfloat16, torch.bfloat16, torch.float32, torch.float32, torch.bfloat16, torch.float32, None, None, ] backward_datatypes = [ torch.bfloat16, torch.float32, torch.bfloat16, torch.float32, None, None, torch.bfloat16, torch.float32, ] comm_mode = CommDebugMode() for forward_dtype, backward_dtype in zip(forward_datatypes, backward_datatypes): local_tensor = torch.randn( 12, 3, device=self.device_type, requires_grad=True ) # 1) test replicate -> replicate forward # forward datatype cast to self.forward_dtype and backward datatype cast to self.backward_dtype replica_tensor = distribute_tensor(local_tensor, device_mesh, replica_spec) with comm_mode: reshard_replica_tensor = replica_tensor.redistribute( device_mesh, replica_spec, forward_dtype=forward_dtype, backward_dtype=backward_dtype, ) self.assertEqual(replica_tensor.size(), local_tensor.size()) self.assertEqual(replica_tensor.to(forward_dtype), reshard_replica_tensor) self.assertEqual(comm_mode.get_total_counts(), 0) # 2) test replicate -> replicate backward: # should give gradient as replicate grad_output = torch.ones_like(reshard_replica_tensor) with comm_mode: reshard_replica_tensor.backward(grad_output) grad_input = replica_tensor.grad self.assertEqual(grad_input.placements, replica_spec) self.assertEqual(grad_input.to_local(), torch.ones(12, 3)) self.assertEqual(comm_mode.get_total_counts(), 0) @with_comms def test_shard_to_replicate_forward_backward_datatype_conversion(self): device_mesh = self.build_device_mesh() replica_spec = [Replicate()] shard_dim_and_input_sizes = [ (0, (self.world_size * 3, 3)), (0, (self.world_size * 3 + 1, 3)), (0, (self.world_size * 3 + 2, 3)), (1, (3, self.world_size * 3)), (1, (3, self.world_size * 3 + 1)), (1, (3, self.world_size * 3 + 2)), ] forward_datatypes = [ torch.bfloat16, torch.bfloat16, torch.float32, torch.float32, torch.bfloat16, torch.float32, None, None, ] backward_datatypes = [ torch.bfloat16, torch.float32, torch.bfloat16, torch.float32, None, None, torch.bfloat16, torch.float32, ] comm_mode = CommDebugMode() for forward_dtype, backward_dtype in zip(forward_datatypes, backward_datatypes): for shard_dim, input_size in shard_dim_and_input_sizes: # 1) test shard -> replicate forward shard_spec = [Shard(shard_dim)] expected_tensor = torch.randn( input_size, device=self.device_type, requires_grad=True ) dtensor = distribute_tensor(expected_tensor, device_mesh, shard_spec) with comm_mode: reshard_dtensor = dtensor.redistribute( device_mesh, replica_spec, forward_dtype=forward_dtype, backward_dtype=backward_dtype, ) self.assertEqual(reshard_dtensor.size(), torch.Size(input_size)) self.assertEqual( expected_tensor.to(forward_dtype), reshard_dtensor.to_local() ) self.assertEqual( comm_mode.get_comm_counts()[funcol.all_gather_into_tensor], 1 ) # 2) test shard -> replicate backward: # should give gradient as shard grad_output = torch.ones_like(reshard_dtensor) with comm_mode: reshard_dtensor.backward(grad_output) grad_input = dtensor.grad self.assertEqual(grad_input.placements, shard_spec) self.assertEqual( grad_input.to_local(), torch.ones(dtensor.to_local().size()) ) self.assertEqual(comm_mode.get_total_counts(), 0) @with_comms def test_replicate_to_partial(self): device_mesh = self.build_device_mesh() local_tensor = torch.randn(12, 3, device=self.device_type, requires_grad=True) partial_spec = Partial() replica_spec = Replicate() # 1) test replicate -> partial forward replica_tensor = distribute_tensor(local_tensor, device_mesh, [replica_spec]) with self.assertRaisesRegex(RuntimeError, "Can not redistribute"): partial_tensor = replica_tensor.redistribute(device_mesh, [partial_spec]) from torch.distributed.tensor._redistribute import Redistribute comm_mode = CommDebugMode() with comm_mode: partial_tensor = Redistribute.apply( replica_tensor, device_mesh, [partial_spec] ) self.assertEqual(partial_tensor.size(), local_tensor.size()) # test it successfully zero out the contents on other ranks self.assertEqual( replica_tensor.to_local() / self.world_size, partial_tensor.to_local() ) self.assertEqual(comm_mode.get_total_counts(), 0) # replicate to partial on sub groups local_tensor = torch.randn(12, 3, device=self.device_type) device_mesh = DeviceMesh( self.device_type, torch.arange(self.world_size).reshape(self.world_size // 2, 2), ) # 1) test replicate -> partial on 2d-mesh subgroups replica_tensor = distribute_tensor( local_tensor, device_mesh, [replica_spec, replica_spec] ) with comm_mode: partial_tensor = Redistribute.apply( replica_tensor, device_mesh, [partial_spec, partial_spec] ) self.assertEqual(partial_tensor.size(), local_tensor.size()) self.assertEqual( replica_tensor.to_local() / self.world_size, partial_tensor.to_local(), ) self.assertEqual(comm_mode.get_total_counts(), 0) @with_comms @parametrize("dtype", [torch.float32, torch.cfloat]) def test_partial_to_shard(self, dtype): device_mesh = self.build_device_mesh() partial_spec = [Partial()] my_rank = self.rank input_sizes_and_shard_dim = [ ((self.world_size * 3, 3), 0), ((self.world_size * 3 + 1, 3), 0), ((self.world_size * 3 + 2, 3), 0), ((3, self.world_size * 3), 1), ((3, self.world_size * 3 + 1), 1), ((3, self.world_size * 3 + 2), 1), ] comm_mode = CommDebugMode() for input_size, shard_dim in input_sizes_and_shard_dim: shard_spec = [Shard(shard_dim)] partial_local = torch.ones(input_size, device=self.device_type, dtype=dtype) partial_tensor = DTensor.from_local( partial_local, device_mesh, partial_spec, run_check=False ) full_chunk_size = ( input_size[shard_dim] + self.world_size - 1 ) // self.world_size chunk_sizes = [ max( min(input_size[shard_dim], full_chunk_size * (idx + 1)) - full_chunk_size * idx, 0, ) for idx in range(self.world_size) ] @maybe_run_for_local_tensor def _compute_local_shape(rank) -> list[int]: local_shape = list(input_size) local_shape[shard_dim] = chunk_sizes[rank] return local_shape local_shape = _compute_local_shape(my_rank) # test partial to shard, trigger reduce_scatter with comm_mode: scatter_shard_tensor = partial_tensor.redistribute( device_mesh, shard_spec ) self.assertEqual(scatter_shard_tensor.size(), partial_tensor.size()) self.assertEqual(scatter_shard_tensor.placements, shard_spec) self.assertEqual( scatter_shard_tensor.to_local(), torch.ones(local_shape, dtype=dtype) * self.world_size, ) self.assertEqual( comm_mode.get_comm_counts()[funcol.reduce_scatter_tensor], 1 ) @with_comms def test_redistribute_negative_shard_dim(self): device_mesh = self.build_device_mesh() local_tensor = torch.randn(12, 3, device=self.device_type, requires_grad=True) shard_spec = [Shard(1)] shard_minus_spec = [Shard(-1)] shard_tensor = distribute_tensor(local_tensor, device_mesh, shard_spec) self.assertEqual(shard_tensor.placements[0].dim, 1) reshard_tensor = shard_tensor.redistribute(device_mesh, shard_minus_spec) self.assertEqual(reshard_tensor.placements[0].dim, 1) @with_comms def test_redistribute_uneven_sharding(self): mesh = DeviceMesh(self.device_type, torch.arange(self.world_size).reshape(2, 2)) data_to_test = [ # uneven on last mesh dim torch.randn((10, 5), device=self.device_type), # uneven on both mesh dims torch.randn((9, 5), device=self.device_type), # smaller than mesh dim shape torch.randn((3, 5), device=self.device_type), torch.randn((1, 3), device=self.device_type), ] sharding_to_tests = [ [Shard(0), Shard(0)], [Shard(0), Shard(1)], ] for input_tensor in data_to_test: for placements in sharding_to_tests: dt = distribute_tensor(input_tensor, mesh, placements) dt_full_tensor = dt.full_tensor() self.assertEqual(dt_full_tensor, input_tensor) @skip_if_lt_x_gpu(4) @with_comms @parametrize("dtype", [torch.float32, torch.cfloat]) def test_redistribute_shard_dim_change(self, dtype): # test 1d device mesh mesh_1d = self.build_device_mesh() data_to_test = [ # evenly sharded case torch.randn((8, 8), device=self.device_type, dtype=dtype), # 3d or more dims torch.randn((8, 8, 8), device=self.device_type, dtype=dtype), # uneven case 1 torch.randn((8, 5), device=self.device_type, dtype=dtype), # uneven case 2 torch.randn((5, 8), device=self.device_type, dtype=dtype), # uneven case 3 torch.randn((5, 5), device=self.device_type, dtype=dtype), ] sharding_src_dst_pairs = [([Shard(0)], [Shard(1)]), ([Shard(1)], [Shard(0)])] comm_mode = CommDebugMode() for input_data in data_to_test: for src, dst in sharding_src_dst_pairs: expected_dt = distribute_tensor(input_data.clone(), mesh_1d, dst) sharded_dt = distribute_tensor(input_data, mesh_1d, src) with comm_mode: out_dt = sharded_dt.redistribute(mesh_1d, dst) self.assertEqual(out_dt.placements, expected_dt.placements) local_out_dt = out_dt.to_local() local_expected_dt = expected_dt.to_local() self.assertEqual(out_dt.to_local(), expected_dt.to_local()) if torch.accelerator.is_available(): self.assertEqual( comm_mode.get_comm_counts()[ torch.ops._dtensor.shard_dim_alltoall ], 1, ) else: # TODO: Integrate local tensor with CommDebugMode if not self.is_local_tensor_enabled: self.assertEqual( comm_mode.get_comm_counts()[funcol.all_gather_into_tensor], 1, ) # test 2d device mesh mesh_2d = DeviceMesh( self.device_type, torch.arange(self.world_size).reshape(2, 2) ) data_to_test_2d = [ # evenly sharded case torch.randn((8, 8), device=self.device_type, dtype=dtype), # 3d or more dims torch.randn((8, 8, 8), device=self.device_type, dtype=dtype), # uneven case 1 torch.randn((8, 5), device=self.device_type, dtype=dtype), # uneven case 2 torch.randn((5, 8), device=self.device_type, dtype=dtype), # uneven case 3 torch.randn((5, 5), device=self.device_type, dtype=dtype), ] sharding_src_dst_pairs_2d = [ ([Shard(0), Shard(1)], [Shard(0), Shard(0)]), ([Shard(0), Shard(1)], [Shard(1), Shard(0)]), ([Shard(0), Shard(0)], [Shard(1), Shard(1)]), ] comm_counts_2d = [ 1, # 1: S1 -> S0 2, # 1: S1 -> R, 0: S0 -> S1, 1: R -> S0 2, # 1: S0 -> R, 0: S0 -> S1, 1: R -> S1 ] for input_data in data_to_test_2d: if input_data.ndim > 2: sharding_spec_combs = sharding_src_dst_pairs_2d + [ ([Shard(0), Shard(2)], [Shard(1), Shard(0)]), ([Shard(1), Shard(1)], [Shard(1), Shard(2)]), ] comm_counts_2d = comm_counts_2d + [ 2, # 1. S2 -> R, 0: S0 -> S1, 1: R -> S0 1, # 1: S1 -> S2 ] else: sharding_spec_combs = sharding_src_dst_pairs_2d for idx, (src, dst) in enumerate(sharding_spec_combs): expected_dt = distribute_tensor(input_data.clone(), mesh_2d, dst) sharded_dt = distribute_tensor(input_data, mesh_2d, src) with comm_mode: out_dt = sharded_dt.redistribute(mesh_2d, dst) self.assertEqual(out_dt.placements, expected_dt.placements) if not self.is_local_tensor_enabled: self.assertEqual(comm_mode.get_total_counts(), comm_counts_2d[idx]) local_out_dt = out_dt.to_local() local_expected_dt = expected_dt.to_local() self.assertEqual(local_out_dt, local_expected_dt) @with_comms @parametrize("dtype", [torch.float32, torch.cfloat]) def test_shard_dim_alltoall(self, dtype): # init 2d mesh here so we can test when group_rank != global_rank mesh = init_device_mesh(self.device_type, (2, 2)) tensor = torch.randn(12, self.world_size, device=self.device_type, dtype=dtype) new_tensor = shard_dim_alltoall(tensor, 0, 1, mesh, 0) meta_tensor = torch.randn(12, self.world_size, device="meta") new_meta_tensor = shard_dim_alltoall(meta_tensor, 0, 1, mesh, 0) self.assertEqual(new_tensor.shape, new_meta_tensor.shape) self.assertEqual(new_tensor.stride(), new_meta_tensor.stride()) @with_comms def test_one_chunk_mesh(self): # mesh size is 1 on second dim mesh = init_device_mesh(self.device_type, (4, 1)) srcs = [Shard(1), Replicate(), Partial()] dsts = [Shard(0), Shard(1), Replicate()] comm_mode = CommDebugMode() for src, dst in itertools.product(srcs, dsts): tensor = torch.randn(16, 8, device=self.device_type) dt = DTensor.from_local(tensor, mesh, [Shard(0), src]) with comm_mode: out = dt.redistribute(mesh, [Shard(0), dst]) self.assertEqual(comm_mode.get_total_counts(), 0) self.assertEqual(out.placements, [Shard(0), dst]) @with_comms def test_redistribute_to_partial(self): mesh = init_device_mesh(self.device_type, (2, 2)) tensor = torch.randn(12, 8, device=self.device_type) test_cases = [ # Partial to Partial is allowed ([Partial(), Shard(0)], [Partial(), Shard(0)], True), ([Partial(), Shard(0)], [Partial(), Shard(1)], True), ([Shard(0), Partial()], [Replicate(), Partial()], True), ([Shard(0), Partial("prod")], [Replicate(), Partial("prod")], True), # Non-Partial to Partial is NOT allowed ([Shard(0), Replicate()], [Shard(0), Partial()], False), ([Shard(0), Replicate()], [Replicate(), Partial()], False), ([Shard(0), Shard(1)], [Replicate(), Partial()], False), # Partial to partial is allowed, if only the reduction ops is the same ([Shard(0), Partial("prod")], [Replicate(), Partial("sum")], False), ] for src, dst, allow in test_cases: dt = DTensor.from_local(tensor, mesh, src) raise_context = ( self.assertRaisesRegex(RuntimeError, "Can not redistribute") if not allow else contextlib.nullcontext() ) with raise_context: out = dt.redistribute(mesh, dst) self.assertEqual(out.placements, dst) instantiate_parametrized_tests(RedistributeTest)
RedistributeTest